/* Minification failed. Returning unminified contents.
(1241,11-12): run-time error JS1010: Expected identifier: .
(1241,11-12): run-time error JS1195: Expected expression: .
 */
/// <reference path="jquery-1.4.4.js" />

/*!
** Unobtrusive Ajax support library for jQuery
** Copyright (C) Microsoft Corporation. All rights reserved.
*/

/*jslint white: true, browser: true, onevar: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, newcap: true, immed: true, strict: false */
/*global window: false, jQuery: false */

(function ($) {
	var data_click = "unobtrusiveAjaxClick",
	    data_validation = "unobtrusiveValidation";

	function getFunction(code, argNames) {
		var fn = window, parts = (code || "").split(".");
		while (fn && parts.length) {
			fn = fn[parts.shift()];
		}
		if (typeof (fn) === "function") {
			return fn;
		}
		argNames.push(code);
		return Function.constructor.apply(null, argNames);
	}

	function isMethodProxySafe(method) {
		return method === "GET" || method === "POST";
	}

	function asyncOnBeforeSend(xhr, method) {
		if (!isMethodProxySafe(method)) {
			xhr.setRequestHeader("X-HTTP-Method-Override", method);
		}
	}

	function asyncOnSuccess(element, data, contentType) {
		var mode;

		if (contentType.indexOf("application/x-javascript") !== -1) {  // jQuery already executes JavaScript for us
			return;
		}

		mode = (element.getAttribute("data-ajax-mode") || "").toUpperCase();
		$(element.getAttribute("data-ajax-update")).each(function (i, update) {
			var top;

			switch (mode) {
				case "BEFORE":
					top = update.firstChild;
					$("<div />").html(data).contents().each(function () {
						update.insertBefore(this, top);
					});
					break;
				case "AFTER":
					$("<div />").html(data).contents().each(function () {
						update.appendChild(this);
					});
					break;
				default:
					$(update).html(data);
					break;
			}
		});
	}

	function asyncRequest(element, options) {
		var confirm, loading, method, duration;

		confirm = element.getAttribute("data-ajax-confirm");
		if (confirm && !window.confirm(confirm)) {
			return;
		}

		loading = $(element.getAttribute("data-ajax-loading"));
		duration = element.getAttribute("data-ajax-loading-duration") || 0;

		$.extend(options, {
			type: element.getAttribute("data-ajax-method") || undefined,
			url: element.getAttribute("data-ajax-url") || undefined,
			beforeSend: function (xhr) {
				var result;
				asyncOnBeforeSend(xhr, method);
				result = getFunction(element.getAttribute("data-ajax-begin"), ["xhr"]).apply(this, arguments);
				if (result !== false) {
					loading.show(duration);
				}
				return result;
			},
			complete: function () {
				loading.hide(duration);
				getFunction(element.getAttribute("data-ajax-complete"), ["xhr", "status"]).apply(this, arguments);
			},
			success: function (data, status, xhr) {
				asyncOnSuccess(element, data, xhr.getResponseHeader("Content-Type") || "text/html");
				getFunction(element.getAttribute("data-ajax-success"), ["data", "status", "xhr"]).apply(this, arguments);
			},
			error: getFunction(element.getAttribute("data-ajax-failure"), ["xhr", "status", "error"])
		});

		options.data.push({ name: "X-Requested-With", value: "XMLHttpRequest" });

		method = options.type.toUpperCase();
		if (!isMethodProxySafe(method)) {
			options.type = "POST";
			options.data.push({ name: "X-HTTP-Method-Override", value: method });
		}

		$.ajax(options);
	}

	function validate(form) {
		var validationInfo = $(form).data(data_validation);
		return !validationInfo || !validationInfo.validate || validationInfo.validate();
	}

	$("a[data-ajax=true]").on("click", function (evt) {
		evt.preventDefault();
		asyncRequest(this, {
			url: this.href,
			type: "GET",
			data: []
		});
	});

	$("form[data-ajax=true] input[type=image]").on("click", function (evt) {
		var name = evt.target.name,
		    $target = $(evt.target),
		    form = $target.parents("form")[0],
		    offset = $target.offset();

		$(form).data(data_click, [
		    { name: name + ".x", value: Math.round(evt.pageX - offset.left) },
		    { name: name + ".y", value: Math.round(evt.pageY - offset.top) }
		]);

		setTimeout(function () {
			$(form).removeData(data_click);
		}, 0);
	});

	$("form[data-ajax=true] :submit").on("click", function (evt) {
		var name = evt.target.name,
		    form = $(evt.target).parents("form")[0];

		$(form).data(data_click, name ? [{ name: name, value: evt.target.value }] : []);

		setTimeout(function () {
			$(form).removeData(data_click);
		}, 0);
	});

	$("form[data-ajax=true]").on("submit", function (evt) {
		var clickInfo = $(this).data(data_click) || [];
		evt.preventDefault();
		if (!validate(this)) {
			return;
		}
		asyncRequest(this, {
			url: this.action,
			type: this.method || "GET",
			data: clickInfo.concat($(this).serializeArray())
		});
	});
}(jQuery));;
/*
 * jQuery QuickFlip v2.1.1
 * http://jonraasch.com/blog/quickflip-2-jquery-plugin
 *
 * Copyright (c) 2009 Jon Raasch (http://jonraasch.com/)
 * Licensed under the FreeBSD License:
 * http://dev.jonraasch.com/quickflip/docs#licensing
 *
 */
(function(c){var a=false,b=null;c.quickFlip={wrappers:[],opts:[],objs:[],init:function(d,f){var d=d||{};d.closeSpeed=d.closeSpeed||180;d.openSpeed=d.openSpeed||120;d.ctaSelector=d.ctaSelector||".quickFlipCta";d.refresh=d.refresh||a;d.easing=d.easing||"swing";d.noResize=d.noResize||a;d.vertical=d.vertical||a;var g=typeof(f)!="undefined"?c(f):c(".quickFlip"),h=g.children();if(g.css("position")=="static"){g.css("position","relative")}var e=c.quickFlip.wrappers.length;h.each(function(i){var k=c(this);if(d.ctaSelector){k.find(d.ctaSelector).click(function(j){j.preventDefault();c.quickFlip.flip(e)})}if(i){k.hide()}});c.quickFlip.opts.push(d);c.quickFlip.objs.push({$box:c(g),$kids:c(h)});c.quickFlip.build(e);if(!d.noResize){c(window).resize(function(){for(var j=0;j<c.quickFlip.wrappers.length;j++){c.quickFlip.removeFlipDivs(j);c.quickFlip.build(j)}})}},build:function(f,h){c.quickFlip.opts[f].panelWidth=c.quickFlip.opts[f].panelWidth||c.quickFlip.objs[f].$box.width();c.quickFlip.opts[f].panelHeight=c.quickFlip.opts[f].panelHeight||c.quickFlip.objs[f].$box.height();var e=c.quickFlip.opts[f],g={wrapper:c.quickFlip.objs[f].$box,index:f,half:parseInt((e.vertical?e.panelHeight:e.panelWidth)/2),panels:[],flipDivs:[],flipDivCols:[],currPanel:h||0,options:e};c.quickFlip.objs[f].$kids.each(function(k){var i=c(this).css({position:"absolute",top:0,left:0,margin:0,padding:0,width:e.panelWidth,height:e.panelHeight});g.panels[k]=i;var l=d(g,k).hide().appendTo(g.wrapper);g.flipDivs[k]=l;g.flipDivCols[k]=l.children()});c.quickFlip.wrappers[f]=g;function d(i,p){function o(q,t){var r=c("<div></div>"),s=q.panels[t].clone().show();r.css(l);r.html(s);return r}var n=c("<div></div>"),j=i.panels[p].html(),l={width:e.vertical?e.panelWidth:i.half,height:e.vertical?i.half:e.panelHeight,position:"absolute",overflow:"hidden",margin:0,padding:0};if(e.vertical){l.left=0}else{l.top=0}var m=c(o(i,p)).appendTo(n),k=c(o(i,p)).appendTo(n);if(e.vertical){m.css("bottom",i.half);k.css("top",i.half);k.children().css({top:b,bottom:0})}else{m.css("right",i.half);k.css("left",i.half);k.children().css({right:0,left:"auto"})}return n}},flip:function(g,q,l,r){function h(j,i){j=j||{};i=i||{};for(opt in j){i[opt]=j[opt]}return i}if(typeof g!="number"||typeof c.quickFlip.wrappers[g]=="undefined"){return}var n=c.quickFlip.wrappers[g],f=n.currPanel,e=(typeof(q)!="undefined"&&q!=b)?q:(n.panels.length>f+1)?f+1:0;n.currPanel=e,l=(typeof(l)!="undefined"&&l!=b)?l:1;r=h(r,c.quickFlip.opts[g]);n.panels[f].hide();if(r.refresh){c.quickFlip.removeFlipDivs(g);c.quickFlip.build(g,e);n=c.quickFlip.wrappers[g]}n.flipDivs[f].show();var p=0,o=0,d=r.vertical?{height:0}:{width:0},m=r.vertical?{height:n.half}:{width:n.half};n.flipDivCols[f].animate(d,r.closeSpeed,r.easing,function(){if(!p){p++}else{n.flipDivs[e].show();n.flipDivCols[e].css(d);n.flipDivCols[e].animate(m,r.openSpeed,r.easing,function(){if(!o){o++}else{n.flipDivs[e].hide();n.panels[e].show();switch(l){case 0:case -1:c.quickFlip.flip(g,b,-1);break;case 1:break;default:c.quickFlip.flip(g,b,l-1);break}}})}})},removeFlipDivs:function(e){for(var d=0;d<c.quickFlip.wrappers[e].flipDivs.length;d++){c.quickFlip.wrappers[e].flipDivs[d].remove()}}};c.fn.quickFlip=function(d){this.each(function(){new c.quickFlip.init(d,this)});return this};c.fn.whichQuickFlip=function(){function f(j,h){if(!j||!h||!j.length||!h.length||j.length!=h.length){return a}for(var g=0;g<j.length;g++){if(j[g]!==h[g]){return a}}return true}var d=b;for(var e=0;e<c.quickFlip.wrappers.length;e++){if(f(this,c(c.quickFlip.wrappers[e].wrapper))){d=e}}return d};c.fn.quickFlipper=function(d,f,e){this.each(function(){var h=c(this),g=h.whichQuickFlip();if(g==b){h.quickFlip(d);g=h.whichQuickFlip()}c.quickFlip.flip(g,f,e,d)})}})(jQuery);;
//Global variables
"use strict";

var setNumbersOnProcessbar = false;
var numberOfHits = 10;

// IE Polyfill for forEach
if (window.NodeList && !NodeList.prototype.forEach) {
    NodeList.prototype.forEach = Array.prototype.forEach;
}

/****** Global functions ******/

/* Places the arrow on the process page which indicates on what page in the process you're on. */
function placePointerOnProcessPage() {
    //get the selected processbar element
    var selectedElement = $(".flow_element.selected"),
        pointer = $(".border_wrapper .pointer");
    if (pointer.length > 0 && selectedElement.length > 0) {
        //update the css of the arrow pointer
        pointer.css({
            left: selectedElement.position().left + selectedElement.width() / 2,
            display: "block"
        });
    }
}

/* Updates the "Hade du nytta av informationen"-block (meaning: x av y (z%) hade nytta av informationen). After the update the comments block is opened. */
function UpdateStatistics(data, value) {
    //get the data to update "Hade du nytta av informationen"-block
    var ajaxUrl = "/PageInformationStatistics/?id=" + parseInt(value);

    $.ajax({
        cache: false,
        url: ajaxUrl,
        type: "GET",
        success: editSuccess
    });

    /* If the ajax-call succedes insert the data into the "Hade du nytta av informationen"-block (.benefit_result and open the comments field */
    function editSuccess(data) {
        $(".benefit_result").html(data);

        var commentContainer = $(".comments_shadow_container");

        if (!commentContainer.hasClass("open")) {
            commentContainer.slideToggle();
            commentContainer.addClass("open");
        }
    }
}
/* Change from number to name, or vice versa, on the processbar elements depending on screen size. */
function toggleProcessPageMobile(mobile) {
    //mobile view (lesser screen width) gets numbers
    if (mobile) {
        $(".processpage .flow_element a").each(function () {
            $(this).html($(this).attr("data-number"));
        });
        $(".border_wrapper .pointer").css({
            display: "none"
        });
    } else {
        $(".processpage .flow_element a").each(function () {
            $(this).html($(this).attr("data-name"));
        });
        placePointerOnProcessPage();
    }
}

/******************/
$(document).ready(function () {

/* Script for downloading sas-report */
    if ($('.reportModal').length > 0) {
        document.getElementsByTagName("sas-report")[0].addEventListener("click",
            function(e) {
                if (e.target.title == "spara image") {
                    const canvases = document.getElementsByTagName('canvas');
                    for (var i = 0; i < canvases.length; i++) {
                        try {
                            dataURL = canvases[i].toDataURL(type = "image/png");
                        } catch (e) {
                            continue;
                        }
                        const a = document.createElement("a");
                        a.href = dataURL;
                        a.download = "Folkhalsokollen_report.png";
                        a.click();
                    }
                }
            });
    }
    

    /* If header image right exists */
    if ($('.header-image-right').length > 0) {
        // Add same hight to top image as left container
        setTimeout(function () {
            let leftContainerHeight = $('.header-image-right .top-section .container-left').outerHeight();
            $('.header-image-right .top-section .container-right').outerHeight(leftContainerHeight);
        }, 100) 
    }

    /* Macro Vardcentral Page */
    if ($('.vardcentralpage').length > 0) {
        // Add same hight to top banner as left container
        let leftContainerHeight = $('.vardcentral-page .container-left').outerHeight();
        $('.vardcentral-page .container-right .top-banner').outerHeight(leftContainerHeight);
    }

    /* Start Page */
    if ($('.startpage .block_row.full_width').length > 0) {
        let bgColor = $('.block_row.full_width').find('.puff-block').css('background-color');
        $('.block_row.full_width').css('background-color', bgColor);
    }

    /* Footer Puff block */
    let $footerPuffBlock = $('.page_footer .puff-block');
    if ($footerPuffBlock.length > 0) {
        $footerPuffBlock.each(function () {
            $(this).find('a').addClass('footer_puff_link');
        });
    }

    /*****************/

    // Left submenu
    $('nav.sub_nav a.show-more').on('click', function (e) {
        e.preventDefault();
        let currentAriaExpanded = $(this).attr('aria-expanded');

        if (currentAriaExpanded === 'false') {
            $(this).attr('aria-expanded', 'true');
            $(this).siblings('ul.child').slideDown().attr('aria-hidden', 'false');
        } else {
            $(this).attr('aria-expanded', 'false');
            $(this).siblings('ul.child').slideUp().attr('aria-hidden', 'true');
        }
    });

    $(".no-backgroundsize .split_content .background_container").each(function (e) {
        $(this).css('background-image', 'url(' + $(this).data("image") + ')');
    });

    /* COMMENTS */
    /* Clicking on the close comment icon in the comments field closes the field */
    $(".js .comments_shadow_container .close_comment").on("click", function () {
        var commentContainer = $(".comments_shadow_container");

        if (commentContainer.hasClass("open")) {
            commentContainer.slideToggle();
            commentContainer.removeClass("open");
            $('.benefit').find('input').removeAttr('checked');
        }
    });

    /* Limits the number of characters in the comments textarea for browser that doesn't support html-atrribute maxlength. */
    $("textarea#comment").keyup(function () {
        var limit = parseInt($(this).attr("maxlength"));
        var text = $(this).val();
        var chars = text.length;

        //check if there are more characters then allowed
        if (chars > limit) {
            //and if there are use substr to get the text before the limit
            var new_text = text.substr(0, limit);

            //and change the current text with the new text
            $(this).val(new_text);
        }
    });

    /* Flip images using jquery quickFlip */
    $("div.flip_blocks.flip-front div.flip_arrow").click(function () {
        var flipContainer = $(this).closest($(".flipbox-container"));
        flipContainer.quickFlipper();
    });

    $("div.flip_blocks.flip-back div.flip_arrow").click(function () {
        var flipContainer = $(this).closest($(".flipbox-container"));
        flipContainer.quickFlipper();
    });

    /*****************/

    /* clickable_block */

    $(".clickable_block").click(function (event) {
        if (event.target.nodeName == "A") {
            return true;
        } else {
            var allLinks = $(this).find("a");
            var lastLink = allLinks[allLinks.length - 1];
            lastLink.click();
        }

        return false;
    });

    /*********/

    /*****************/

    /* VIDEO */

    $(".main_content").fitVids();

    /*********/

    /* The arrow on the process page is only placed and visible if the window width is >= 1024px.
       If the window width is less than 1024px the arrow is removed and the names of the steps in the process
       is replaced with numbers. */

    function editProcessPage() {
        return {
            match: function match() {
                toggleProcessPageMobile(true);
                setNumbersOnProcessbar = true;
            },
            unmatch: function unmatch() {
                toggleProcessPageMobile(false);
            }
        };
    }


    /*Scrolls to anchorlink slowly*/
    $(function () {
        $('a[href*=#]:not([href=#], .component-services a)').click(function () {
            if (location.pathname.replace(/^\//, '') === this.pathname.replace(/^\//, '') && location.hostname === this.hostname) {
                var target = $(this.hash);
                target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
                if (target.length) {
                    $('html,body').animate({
                        scrollTop: target.offset().top
                    }, 1000);

                    target.focus();
                    if (target.is(":focus")) {
                        return false;
                    } else {
                        target.attr('tabindex', '-1');
                        target.focus();
                    };
                    return false;
                }
            }
        });
    });

    // Check checkbox item
    $('.checkbox_item span').click(function () {
        let checkbox = $(this).parents('.checkbox_item');

        if (checkbox.hasClass('checked')) {
            checkbox.removeClass('checked');
        } else {
            checkbox.addClass('checked');
        }
    });

    // Check checkbox item with enter key
    $('.checkbox_item label').keypress(function (e) {
        let checkbox = $(this).parents('.checkbox_item');
        let key = e.which;

        if (key == 13) {
            event.preventDefault();
            if (checkbox.hasClass('checked')) {
                checkbox.removeClass('checked');
            } else {
                checkbox.addClass('checked');
            }
        }
    });

    //External links should open in new window
    //$('a[href^="http://"]').attr('target', '_blank');

    /* OWL slider */

    $("#owl-demo").owlCarousel({
        navigation: true, // Show next and prev buttons
        slideSpeed: 800,
        paginationSpeed: 800,
        singleItem: true,
        navigationText: ["&nbsp&nbsp&nbsp<&nbsp&nbsp&nbsp", "&nbsp&nbsp&nbsp>&nbsp&nbsp&nbsp"],
        autoHeigt: 335,
        autoPlay: 7000,
        autoplay: true
    });
    /******************/

    /* Sort tables on filter search page */
    $("#filter-table").tablesorter();

    $("#title-sorter").click(function () {
        var self = $(this);
        sortFilters(self, 1);
        showSelectedClasses();
    });

    $("#published-sorter").click(function () {
        var self = $(this);
        sortFilters(self, 2);
        showSelectedClasses();
    });

    $("#type-sorter").click(function () {
        var self = $(this);
        sortFilters(self, 3);
        showSelectedClasses();
    });

    function sortFilters(self, column) {
        if (self.hasClass('up')) {
            $('.sorter').removeClass('up').removeClass('down');
            sortUpOrDown(column, 0);
            self.addClass('down');
        } else {
            $('.sorter').removeClass('down').removeClass('up');
            sortUpOrDown(column, 1);
            self.addClass('up');
        }
    }

    function sortUpOrDown(column, direction) {
        // set sorting column and direction, this will sort on the first and third column the column index starts at zero a
        var sorting = [[column, direction]];
        $("#filter-table").trigger("sorton", [sorting]);
        return false;
    }

    /*Filter tags functions*/
    initializeTags();

    function initializeTags() {
        var checkedFromStart = $('.available_tags .tag input:checkbox:checked');
        if (checkedFromStart.length < 1) {
            //$('.results').css('display', 'none');
            $('.latest_published').css('display', 'inline');
        }
        $.each(checkedFromStart, function (i, val) {
            markSelectedClass($(val).closest('.tag'));
        });
        showSelectedClasses();
    }

    function markSelectedClass(obj) {
        var self = $(obj);
        self.addClass('active');
        self.find('input:checkbox').prop('checked', true);
        $('.selected_tags .tag').filter(function () {
            if ($(this).data("tag") == self.data("tag")) {
                $(this).insertAfter($('.selected_tags .tag:last'));
                return this;
            }
            return false;
        }).addClass('active');
        showSelectedClasses();
    }

    function deselectClass(obj) {
        var self = $(obj);
        self.removeClass('active');
        $('.available_tags .tag, .selected_tags .tag').filter(function () {
            if ($(this).data("tag") == self.data("tag")) {
                $(this).find('input:checkbox').prop('checked', false);
                return this;
            }
            return false;
        }).removeClass('active');
        showSelectedClasses();
    }

    //Select tag
    $('.available_tags .tag').click(function () {
        numberOfHits = 10;
        $('.results').css('display', 'inline');
        $('.latest_published').css('display', 'none');

        if (!$(this).hasClass('active')) {
            markSelectedClass(this);
            return false;
        } else {
            deselectClass(this);
            return false;
        }
    });
    //Deselect tag
    $('.selected_tags .tag').click(function () {
        numberOfHits = 10;
        deselectClass(this);
    });

    $(".filter_result_page #showMore").click(function () {
        numberOfHits = +numberOfHits + 10;
        showSelectedClasses();
    });

    function showSelectedClasses() {
        var classesToShow = $('.selected_tags .tag.active');
        var selectionsString = '#filter-table tbody tr';
        $.each(classesToShow, function (i, val) {
            selectionsString = selectionsString + '.' + $(val).data("tag");
        });
        $('#filter-table tr').not('.hidden_column').addClass('hidden_column');
        var selections = $(selectionsString).slice(0, numberOfHits).removeClass('hidden_column');

        $('.number_of_hits').text($(selectionsString).length);

        //Are we able to show more results?
        if (+numberOfHits > selections.length) {
            $(".filter_result_page #showMore").hide();
        } else {
            $(".filter_result_page #showMore").show();
        }
    }

    $('.clear_selected_tags').click(function () {
        $('.selected_tags .tag').each(function () {
            $(this).click();
        });
    });

    $('.tag_category h3').click(function () {
        var currentWindow = $(window);
        if (currentWindow && currentWindow.width() < 600) {
            $('.tags div').first().slideToggle(500, function () {
                $(this).toggleClass('closedInMobile');
                $(this).removeAttr('style', '');
            });
            $('.tag_type').slideToggle(500, function () {
                $(this).toggleClass('closedInMobile');
                $(this).removeAttr('style', '');
            });
            $('.mobile-search').slideToggle(500, function () {
                $(this).toggleClass('closedInMobile');
                $(this).removeAttr('style', '');
            });
            $(this).toggleClass('closed-heading');
        }
    });

    // Language-options
    function getLanguages() {
        $.ajax({
            url: "/getlanguages",
            data: "lang=" + $('.change_language_form').attr('data-lang') + "&currentPageId=" + $(".change_language_form").attr('data-pageId'),
            type: "GET",
            dataType: "json",
            success: function success(data) {
                $.map(data, function (item) {
                    if (!item.Selected) {
                        $('.langList').append('<li><a href="#"  data-langid="' + item.Value + '">' + item.Text + '</a></li>');
                    } else {
                        $('.langList').append('<li class="lang-active"><a href="#"  data-langid="' + item.Value + '">' + item.Text + '</a></li>');
                    }
                });
            }
        });
    }
    $('.langList').on("click", "a", function (e) {
        e.preventDefault();
        var itemValue = $(this).attr('data-langId');
        $(".change_language_form").attr('action', '/changelanguage?currentPageID=' + $(".change_language_form").attr('data-pageId') + '&lang=' + itemValue);
        $(".change_language_form").submit();
    });

    getLanguages();

    $('.earthIcon').click(function (e) {
        var self = $(this).find('a.sprite.earth');
        $('.language_dropdown').focus();
    });

    $(".language_dropdown").each(function () {
        var $t = $(this),
            default_value = this.value;
        $t.css('color', '#929292');

        $t.focus(function () {
            if (this.value == default_value) {
                this.value = '';
                $t.css('color', 'black');
            }
        });

        $t.blur(function () {
            if ($.trim(this.value) == '') {
                $t.css('color', '#929292');
                this.value = default_value;
            }
        });
    });

    $(".language_dropdown").autocomplete({
        position: {
            my: "left top",
            at: "left top"
        },
        source: function source(request, response) {
            $.ajax({
                url: "/getlanguages",
                data: "currentPageId=" + $(".change_language_form").attr('data-pageId'),
                type: "GET",
                dataType: "json",
                success: function success(data) {
                    response($.map(data, function (item) {
                        if (!item.Selected) {
                            return { label: item.Text, value: item.Value, selected: false };
                        } else {
                            return { label: item.Text, value: item.Value, selected: true };
                        }
                    }));
                }
            });
        },
        minLength: 0,
        messages: {
            noResults: '',
            results: function results() { }
        },
        select: function select(event, ui) {
            $(".change_language_form").attr('action', '/changelanguage?currentPageID=' + $(".change_language_form").attr('data-pageId') + '&lang=' + ui.item.value);
            $(".change_language_form").submit();
            return false;
        },
        close: function close(event, ui) {
            if (!$('ul.ui-autocomplete').is(":focus") && !$('.language_dropdown').is(":focus") && !$('.earthIcon').is(":focus")) {
                $('.language_dropdown').autocomplete('close');
            } else {
                $(".language_dropdown").focus();
            }
        }
    }).bind('focus', function () {
        // $('.earthIcon').focus();
        $(this).autocomplete("search");
    }).each(function () {
        $(this).data("ui-autocomplete")._renderItem = function (ul, item) {
            var $a = $("<a></a>");
            if (item.label.toLowerCase() == $('.language_dropdown').attr('data-lang-name').toLowerCase()) {
                $a = $("<a style='background-color: #27769f;'></a>");
                $("<span class='selected-language'></span>").text(item.label).appendTo($a);
            } else {
                $("<span class='language'></span>").text(item.label).appendTo($a);
            }

            return $("<li></li>").append($a).appendTo(ul);
        };
    });

    $(document).ready(function () {

        var hs1 = new hideShow('openlangdesktop');
        var hs2 = new hideShow('openlangmobile');
    }); // end ready()

    //
    // function hideShow() is the constructor for a hideShow widget. it accepts the html ID of
    // an element to attach to.
    //
    // @param(id string) id is the html ID of the element to attach to
    //
    // @return N/A
    //
    function hideShow(id) {

        this.$id = $('#' + id);
        this.$region = $('#' + this.$id.attr('aria-controls'));

        this.keys = {
            enter: 13,
            space: 32
        };

        this.toggleSpeed = 100;

        // bind handlers
        this.bindHandlers();
    } // end hidShow() constructor

    //
    // Function bindHandlers() is a member function to bind event handlers to the hideShow region
    //
    // return N/A
    //
    hideShow.prototype.bindHandlers = function () {

        var thisObj = this;

        this.$id.click(function (e) {

            thisObj.toggleRegion();

            e.stopPropagation();
            return false;
        });
    };

    //
    // Function toggleRegion() is a member function to toggle the display of the hideShow region
    //
    // return N/A
    //
    hideShow.prototype.toggleRegion = function () {

        var thisObj = this;
        // toggle the region

        if (this.$region.attr('aria-expanded') == 'false') {
            // region is collapsed

            // update the aria-expanded attribute of the region
            this.$region.attr('aria-expanded', 'true');

            //add active class to region
            this.$region.addClass('active');

            // move focus to the region
            this.$region.attr("tabindex", "0").focus();

            // update the button label
            //thisObj.$id.find('span').html('Hide');
        } else {
            // region is expanded

            // update the aria-expanded attribute of the region
            this.$region.attr('aria-expanded', 'false');

            // update the button label
            //thisObj.$id.find('span').html('Show');
            this.$region.attr("tabindex", "-1");
            this.$id.focus();
            //remove active class from region
            this.$region.removeClass('active');
        }
    }; // end toggleRegion()

    $('#changelanguagedesktop .close').on("click", function (e) {
        e.preventDefault();
        $("#openlangdesktop").trigger("click");
    });

    $('#changelanguagemobile .close').on("click", function (e) {
        e.preventDefault();
        $("#openlangmobile").trigger("click");
    });

    $('#changelanguage2 .close').on("click", function (e) {
        e.preventDefault();
        $("#openlang2").trigger("click");
    });

    var mediaQuery = window.matchMedia('(min-width: 1023px)');

    // Add a listen event
    mediaQuery.addListener(moveGoogleTranslate);

    // Function to do something with the media query
    function moveGoogleTranslate(mediaQuery) {
        if (mediaQuery.matches) {
            if ($('.googleTranslateMove #google_translate_element:not(:empty)')) {
                $('.googleTranslateMove').remove().appendTo('#changelanguagedesktop .language_dropdown_container');
            }
        } else {
            if ($('.googleTranslateMove #google_translate_element:not(:empty)')) {
                $('.googleTranslateMove').remove().appendTo('#changelanguagemobile .language_dropdown_container');
            }
        }
    }

    // On load
    moveGoogleTranslate(mediaQuery);

    function get_browser() {
        var ua = navigator.userAgent,
            tem,
            M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
        if (/trident/i.test(M[1])) {
            tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
            return 'IE ' + (tem[1] || '');
        }
        if (M[1] === 'Chrome') {
            tem = ua.match(/\bOPR\/(\d+)/);
            if (tem != null) {
                return 'Opera ' + tem[1];
            }
        }
        M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
        if ((tem = ua.match(/version\/(\d+)/i)) != null) {
            M.splice(1, 1, tem[1]);
        }
        return M[0];
    }

    var isIEMatch = /^IE...$/.test(get_browser());
    if (isIEMatch) {
        $(".language_dropdown").off('blur').on('blur', function () {
            if (!$('ul.ui-autocomplete').is(":focus") && !$('.language_dropdown').is(":focus") && !$('.earthIcon').is(":focus")) {
                $('.language_dropdown').autocomplete('close');
            }
        });
    }
});


$(window).load(function () {
    window.scrollTo(0, 0);

    /* Special functionality for mobile browsers that does not support matchMedia (used with enquire for javascript media queries.  
       For these browsers the change from name (default) to numbers on the processbar elements is done here instead of being 
       done through the above media query */
    if (setNumbersOnProcessbar) {
        toggleProcessPageMobile(true);
    } else if ($(".site_header .toggle_nav_search").css("display") == "none") {
        toggleProcessPageMobile(false);
    }

    /* Special functionality for mobile browsers that does not support matchMedia (used with enquire for javascript media queries. 
       For these browsers the submenus in the mobile navigation menu are opened all the time */
    var matchMedia = window.matchMedia || window.msMatchMedia;
    if (!matchMedia) {
        if ($(".site_header .toggle_nav_search").css("display") == "block") {
            $('.main_nav ul.parent li.has_child').each(function () {
                var self = $(this);
                self.find("a").addClass("no_match_media");
                self.find(".expand").css("display", "none");
                self.find(".child").css("display", "block");
            });
        }
    }
});

/*
  Skip to content
*/
$(".skip").click(function (e) {
    e.preventDefault();
    // strip the leading hash and declare
    // the content we're skipping to
    var skipTo = "#" + this.href.split('#')[1];

    // Setting 'tabindex' to -1 takes an element out of normal 
    // tab flow but allows it to be focused via javascript
    $(skipTo).attr('tabindex', -1).on('blur focusout', function () {

        // when focus leaves this element, 
        // remove the tabindex attribute
        $(this).removeAttr('tabindex');

    }).focus(); // focus on the content container
});

// Reload page on orientation change
window.addEventListener("orientationchange", function () {
    location.reload();
}, false);

// Close share on click outside
$(document).mouseup(function (e) {
    let shareFunction = $("#shareFunction");

    if (!shareFunction.is(e.target) && shareFunction.has(e.target).length === 0) {
        $('#shareButton').attr('aria-expanded', 'false');
        $('#shareContent').attr('aria-hidden', 'true');
    }
}); 

// Add class when the user is tabbing
function handleFirstTab(e) {
    if (e.keyCode === 9) {
        document.body.classList.add('user_tabbing');
        window.removeEventListener('keydown', handleFirstTab);
    }
}

window.addEventListener('keydown', handleFirstTab);

//For ReportModal
$('.openReportModal').on('click', function (e) {
    e.preventDefault();
    $('.reportModal').addClass('active');
});

$('.closeReportModal').on('click', function (e) {
    e.preventDefault();
    $('.reportModal').removeClass('active');
});
;
/**
 * Accordion, jQuery Plugin
 *
 * This plugin provides an accordion with cookie support.
 *
 * Copyright (c) 2011 John Snyder (snyderplace.com)
 * @license http://www.snyderplace.com/accordion/license.txt New BSD
 * @version 1.1
 */
(function($) {
    $.fn.accordion = function(options) {

        //firewalling
        if (!this || this.length < 1) {
            return this;
        }

        initialize(this, options);

    };

    //create the initial accordion
    function initialize(obj, options) {

        //build main options before element iteration
        var opts = $.extend({}, $.fn.accordion.defaults, options);

        //store any opened default values to set cookie later
        var opened = '';

        //iterate each matched object, bind, and open/close
        obj.each(function() {
            var $this = $(this);
            saveOpts($this, opts);

            //bind it to the event
            if (opts.bind == 'mouseenter') {
                $this.bind('mouseenter', function(e) {
                    e.preventDefault();
                    toggle($this, opts);
                });
            }

            //bind it to the event
            if (opts.bind == 'mouseover') {
                $this.bind('mouseover',function(e) {
                    e.preventDefault();
                    toggle($this, opts);
                });
            }

            //bind it to the event
            if (opts.bind == 'click') {
                $this.bind('click', function(e) {
                    e.preventDefault();
                    toggle($this, opts);
                });
            }

            //bind it to the event
            if (opts.bind == 'dblclick') {
                $this.bind('dblclick', function(e) {
                    e.preventDefault();
                    toggle($this, opts);
                });
            }

            //initialize the panels
            //get the id for this element
            id = $this.attr('id');

            //if not using cookies, open defaults
            if (!useCookies(opts)) {
                //close it if not defaulted to open
                if (id != opts.defaultOpen) {
                    $this.addClass(opts.cssClose);
                    opts.loadClose($this, opts);
                } else { //its a default open, open it
                    $this.addClass(opts.cssOpen);
                    opts.loadOpen($this, opts);
                    opened = id;
                }
            } else { //can use cookies, use them now
                //has a cookie been set, this overrides default open
                if (issetCookie(opts)) {
                    if (inCookie(id, opts) === false) {
                        $this.addClass(opts.cssClose);
                        opts.loadClose($this, opts);
                    } else {
                        $this.addClass(opts.cssOpen);
                        opts.loadOpen($this, opts);
                        opened = id;
                    }
                } else { //a cookie hasn't been set open defaults
                    if (id != opts.defaultOpen) {
                        $this.addClass(opts.cssClose);
                        opts.loadClose($this, opts);
                    } else { //its a default open, open it
                        $this.addClass(opts.cssOpen);
                        opts.loadOpen($this, opts);
                        opened = id;
                    }
                }
            }
        });

        //now that the loop is done, set the cookie
        if (opened.length > 0 && useCookies(opts)) {
            setCookie(opened, opts);
        } else { //there are none open, set cookie
            setCookie('', opts);
        }

        return obj;
    };

    //load opts from object
    function loadOpts($this) {
        return $this.data('accordion-opts');
    }

    //save opts into object
    function saveOpts($this, opts) {
        return $this.data('accordion-opts', opts);
    }

    //hides a accordion panel
    function close(opts) {
        opened = $(document).find('.' + opts.cssOpen);
        $.each(opened, function() {
            //give the proper class to the linked element
            $(this).addClass(opts.cssClose).removeClass(opts.cssOpen);
            opts.animateClose($(this), opts);
        });
    }

    //opens a accordion panel
    function open($this, opts) {
        close(opts);
        //give the proper class to the linked element
        $this.removeClass(opts.cssClose).addClass(opts.cssOpen);

        //open the element
        opts.animateOpen($this, opts);

        //do cookies if plugin available
        if (useCookies(opts)) {
            // split the cookieOpen string by ","
            id = $this.attr('id');
            setCookie(id, opts);
        }
    }

    //toggle a accordion on an event
    function toggle($this, opts) {
        // close the only open item
        if ($this.hasClass(opts.cssOpen))
        {
            close(opts);
            //do cookies if plugin available
            if (useCookies(opts)) {
                // split the cookieOpen string by ","
                setCookie('', opts);
            }
            return false;
        }
        close(opts);
        //open a closed element
        open($this, opts);
        return false;
    }

    //use cookies?
    function useCookies(opts) {
        //return false if cookie plugin not present or if a cookie name is not provided
        if (!$.cookie || opts.cookieName == '') {
            return false;
        }

        //we can use cookies
        return true;
    }

    //set a cookie
    function setCookie(value, opts)
    {
        //can use the cookie plugin
        if (!useCookies(opts)) { //no, quit here
            return false;
        }

        //cookie plugin is available, lets set the cookie
        $.cookie(opts.cookieName, value, opts.cookieOptions);
    }

    //check if a accordion is in the cookie
    function inCookie(value, opts)
    {
        //can use the cookie plugin
        if (!useCookies(opts)) {
            return false;
        }

        //if its not there we don't need to remove from it
        if (!issetCookie(opts)) { //quit here, don't have a cookie
            return false;
        }

        //unescape it
        cookie = unescape($.cookie(opts.cookieName));

        //is this value in the cookie arrray
        if (cookie != value) { //no, quit here
            return false;
        }

        return true;
    }

    //check if a cookie is set
    function issetCookie(opts)
    {
        //can we use the cookie plugin
        if (!useCookies(opts)) { //no, quit here
            return false;
        }

        //is the cookie set
        if ($.cookie(opts.cookieName) == null) { //no, quit here
            return false;
        }

        return true;
    }

    // settings
    $.fn.accordion.defaults = {
        cssClose: 'accordion-close', //class you want to assign to a closed accordion header
        cssOpen: 'accordion-open', //class you want to assign an opened accordion header
        cookieName: 'accordion', //name of the cookie you want to set for this accordion
        cookieOptions: { //cookie options, see cookie plugin for details
            path: '/',
            expires: 7,
            domain: '',
            secure: ''
        },
        defaultOpen: '', //id that you want opened by default
        speed: 'slow', //speed of the slide effect
        bind: 'click', //event to bind to, supports click, dblclick, mouseover and mouseenter
        animateOpen: function (elem, opts) { //replace the standard slideDown with custom function
            elem.next().stop(true, true).slideDown(opts.speed);
        },
        animateClose: function (elem, opts) { //replace the standard slideUp with custom function
            elem.next().stop(true, true).slideUp(opts.speed);
        },
        loadOpen: function (elem, opts) { //replace the default open state with custom function
            elem.next().show();
        },
        loadClose: function (elem, opts) { //replace the default close state with custom function
            elem.next().hide();
        }
    };
})(jQuery);;
/* jshint -W003 */
/*!
 * jQuery Expander Plugin - v1.7.0 - 2016-03-12
 * https://kswedberg.github.io/jquery-expander/
 * Copyright (c) 2016 Karl Swedberg
 * Licensed MIT (http://www.opensource.org/licenses/mit-license.php)
 */

(function(factory) {
  if (typeof define === 'function' && define.amd) {
    define(['jquery'], factory);
  } else if (typeof module === 'object' && typeof module.exports === 'object') {
    module.exports = factory;
  } else {
    factory(jQuery);
  }
})(function($) {
  $.expander = {
    version: '1.7.0',
    defaults: {
      // the number of characters at which the contents will be sliced into two parts.
      slicePoint: 100,

      // a string of characters at which to slice the contents into two parts,
      // but only if the string appears before slicePoint
      // Useful for slicing at the first line break, e.g. {sliceOn: '<br'}
      sliceOn: null,

      // whether to keep the last word of the summary whole (true) or let it slice in the middle of a word (false)
      preserveWords: true,

      // whether to normalize the whitespace in the data to display (true) or not (false)
      normalizeWhitespace: true,

      // whether to count and display the number of words inside the collapsed text
      showWordCount: false,

      // text to include between summary and detail. Default ' ' prevents appearance of
      // collapsing two words into one.
      // Was hard-coded in script; now exposed as an option to fix issue #106.
      detailPrefix: ' ',

      // What to display around the counted number of words, set to '{{count}}' to show only the number
      wordCountText: ' ({{count}} words)',

      // a threshold of sorts for whether to initially hide/collapse part of the element's contents.
      // If after slicing the contents in two there are fewer words in the second part than
      // the value set by widow, we won't bother hiding/collapsing anything.
      widow: 4,

      // text displayed in a link instead of the hidden part of the element.
      // clicking this will expand/show the hidden/collapsed text
      expandText: 'read more',
      expandPrefix: '&hellip; ',

      expandAfterSummary: false,

      // Possible word endings to test against for when preserveWords: true
      wordEnd: /(&(?:[^;]+;)?|[0-9a-zA-Z\u00C0-\u0100]+|[^\u0000-\u007F]+)$/,

      // class names for summary element and detail element
      summaryClass: 'summary',
      detailClass: 'details',

      // class names for <span> around "read-more" link and "read-less" link
      moreClass: 'read-more',
      lessClass: 'read-less',

      // class names for <a> around "read-more" link and "read-less" link
      moreLinkClass: 'more-link',
      lessLinkClass: 'less-link',

      // number of milliseconds after text has been expanded at which to collapse the text again.
      // when 0, no auto-collapsing
      collapseTimer: 0,

      // effects for expanding and collapsing
      expandEffect: 'slideDown',
      expandSpeed: 250,
      collapseEffect: 'slideUp',
      collapseSpeed: 200,

      // allow the user to re-collapse the expanded text.
      userCollapse: true,

      // text to use for the link to re-collapse the text
      userCollapseText: 'read less',
      userCollapsePrefix: ' ',

      // all callback functions have the this keyword mapped to the element in the jQuery set when .expander() is called
      onSlice: null, // function() {}
      beforeExpand: null, // function() {},
      afterExpand: null, // function() {},
      onCollapse: null, // function(byUser) {}
      afterCollapse: null // function() {}
    }
  };

  $.fn.expander = function(options) {
    var meth = 'init';

    if (typeof options === 'string') {
      meth = options;
      options = {};
    }

    var opts = $.extend({}, $.expander.defaults, options);
    var rSelfClose = /^<(?:area|br|col|embed|hr|img|input|link|meta|param).*>$/i;
    var rAmpWordEnd = opts.wordEnd;
    var rOpenCloseTag = /<\/?(\w+)[^>]*>/g;
    var rOpenTag = /<(\w+)[^>]*>/g;
    var rCloseTag = /<\/(\w+)>/g;
    var rLastCloseTag = /(<\/([^>]+)>)\s*$/;
    var rTagPlus = /^(<[^>]+>)+.?/;
    var rMultiSpace = /\s\s+/g;
    var delayedCollapse;

    var removeSpaces = function(str) {
      return opts.normalizeWhitespace ? $.trim(str || '').replace(rMultiSpace, ' ') : str;
    };

    var methods = {
      init: function() {
        this.each(function() {
          var i, l, tmp, newChar, summTagless, summOpens, summCloses,
              lastCloseTag, detailText, detailTagless, html, expand;
          var $thisDetails, $readMore;
          var slicePointChanged;
          var openTagsForDetails = [];
          var closeTagsForsummaryText = [];
          var strayChars = '';
          var defined = {};
          var thisEl = this;
          var $this = $(this);
          var $summEl = $([]);
          var o = $.extend({}, opts, $this.data('expander') || $.meta && $this.data() || {});
          var hasDetails = !!$this.find('.' + o.detailClass).length;
          var hasBlocks = !!$this.find('*').filter(function() {
            var display = $(this).css('display');

            return (/^block|table|list/).test(display);
          }).length;
          var el = hasBlocks ? 'div' : 'span';
          var detailSelector = el + '.' + o.detailClass;
          var moreClass = o.moreClass + '';
          var lessClass = o.lessClass + '';
          var expandSpeed = o.expandSpeed || 0;
          var allHtml = removeSpaces($this.html());
          var summaryText = allHtml.slice(0, o.slicePoint);

          // allow multiple classes for more/less links
          o.moreSelector = 'span.' + moreClass.split(' ').join('.');
          o.lessSelector = 'span.' + lessClass.split(' ').join('.');
          // bail out if we've already set up the expander on this element
          if ($.data(this, 'expanderInit')) {
            return;
          }

          $.data(this, 'expanderInit', true);
          $.data(this, 'expander', o);
          // determine which callback functions are defined
          $.each(['onSlice','beforeExpand', 'afterExpand', 'onCollapse', 'afterCollapse'], function(index, val) {
            defined[val] = $.isFunction(o[val]);
          });

          // back up if we're in the middle of a tag or word
          summaryText = backup(summaryText);

          // summary text sans tags length
          summTagless = summaryText.replace(rOpenCloseTag, '').length;

          // add more characters to the summary, one for each character in the tags
          while (summTagless < o.slicePoint) {
            newChar = allHtml.charAt(summaryText.length);

            if (newChar === '<') {
              newChar = allHtml.slice(summaryText.length).match(rTagPlus)[0];
            }
            summaryText += newChar;
            summTagless++;
          }

          // SliceOn script, Closes #16, resolves #59
          // Original SliceEarlierAt code (since modfied): Sascha Peilicke @saschpe
          if (o.sliceOn) {
            slicePointChanged = changeSlicePoint({
              sliceOn: o.sliceOn,
              slicePoint: o.slicePoint,
              allHtml: allHtml,
              summaryText: summaryText
            });

            summaryText = slicePointChanged.summaryText;
          }

          summaryText = backup(summaryText, o.preserveWords && allHtml.slice(summaryText.length).length);

          // separate open tags from close tags and clean up the lists
          summOpens = summaryText.match(rOpenTag) || [];
          summCloses = summaryText.match(rCloseTag) || [];

          // filter out self-closing tags
          tmp = [];
          $.each(summOpens, function(index, val) {
            if (!rSelfClose.test(val)) {
              tmp.push(val);
            }
          });
          summOpens = tmp;

          // strip close tags to just the tag name
          l = summCloses.length;

          for (i = 0; i < l; i++) {
            summCloses[i] = summCloses[i].replace(rCloseTag, '$1');
          }
          // tags that start in summary and end in detail need:
          // a). close tag at end of summary
          // b). open tag at beginning of detail
          $.each(summOpens, function(index, val) {
            var thisTagName = val.replace(rOpenTag, '$1');
            var closePosition = $.inArray(thisTagName, summCloses);

            if (closePosition === -1) {
              openTagsForDetails.push(val);
              closeTagsForsummaryText.push('</' + thisTagName + '>');

            } else {
              summCloses.splice(closePosition, 1);
            }
          });

          // reverse the order of the close tags for the summary so they line up right
          closeTagsForsummaryText.reverse();

          // create necessary summary and detail elements if they don't already exist
          if (!hasDetails) {

            // end script if there is no detail text or if detail has fewer words than widow option
            detailText = allHtml.slice(summaryText.length);
            detailTagless = $.trim(detailText.replace(rOpenCloseTag, ''));

            if (detailTagless === '' || detailTagless.split(/\s+/).length < o.widow) {
              return;
            }
            // otherwise, continue...
            lastCloseTag = closeTagsForsummaryText.pop() || '';
            summaryText += closeTagsForsummaryText.join('');
            detailText = openTagsForDetails.join('') + detailText;
          } else {
            // assume that even if there are details, we still need readMore/readLess/summary elements
            // (we already bailed out earlier when readMore el was found)
            // but we need to create els differently

            // remove the detail from the rest of the content
            detailText = $this.find(detailSelector).remove().html();

            // The summary is what's left
            summaryText = $this.html();

            // allHtml is the summary and detail combined (this is needed when content has block-level elements)
            allHtml = summaryText + detailText;

            lastCloseTag = '';
          }
          o.moreLabel = $this.find(o.moreSelector).length ? '' : buildMoreLabel(o, detailText);

          if (hasBlocks) {
            detailText = allHtml;
            // Fixes issue #89; Tested by 'split html escapes'
          } else if (summaryText.charAt(summaryText.length - 1) === '&') {
            strayChars = /^[#\w\d\\]+;/.exec(detailText);

            if (strayChars) {
              detailText = detailText.slice(strayChars[0].length);
              summaryText += strayChars[0];
            }
          }
          summaryText += lastCloseTag;

          // onSlice callback
          o.summary = summaryText;
          o.details = detailText;
          o.lastCloseTag = lastCloseTag;

          if (defined.onSlice) {
            // user can choose to return a modified options object
            // one last chance for user to change the options. sneaky, huh?
            // but could be tricky so use at your own risk.
            tmp = o.onSlice.call(thisEl, o);

            // so, if the returned value from the onSlice function is an object with a details property, we'll use that!
            o = tmp && tmp.details ? tmp : o;
          }

          // build the html with summary and detail and use it to replace old contents
          html = buildHTML(o, hasBlocks);

          $this.empty().append(html);

          // set up details and summary for expanding/collapsing
          $thisDetails = $this.find(detailSelector);
          $readMore = $this.find(o.moreSelector);

          // Hide details span using collapseEffect unless
          // expandEffect is NOT slideDown and collapseEffect IS slideUp.
          // The slideUp effect sets span's "default" display to
          // inline-block. This is necessary for slideDown, but
          // problematic for other "showing" animations.
          // Fixes #46
          if (o.collapseEffect === 'slideUp' && o.expandEffect !== 'slideDown' || $this.is(':hidden')) {
            $thisDetails.css({display: 'none'});
          } else {
            $thisDetails[o.collapseEffect](0);
          }

          $summEl = $this.find('div.' + o.summaryClass);

          expand = function(event) {
            event.preventDefault();
            var exSpeed = event.startExpanded ? 0 : expandSpeed;
            $readMore.hide();
            $summEl.hide();

            if (defined.beforeExpand) {
              o.beforeExpand.call(thisEl);
            }

            $thisDetails.stop(false, true)[o.expandEffect](exSpeed, function() {
              $thisDetails.css({zoom: ''});

              if (defined.afterExpand) {
                o.afterExpand.call(thisEl);
              }
              delayCollapse(o, $thisDetails, thisEl);
            });
          };

          $readMore.find('a').unbind('click.expander').bind('click.expander', expand);

          if (o.userCollapse && !$this.find(o.lessSelector).length) {
            $this
            .find(detailSelector)
                .append('<span class="' + o.lessClass + '">' + o.userCollapsePrefix + '<a href="#" class="' + o.lessLinkClass + '">' + o.userCollapseText + '</a></span>');
          }

          $this
          .find(o.lessSelector + ' a')
          .unbind('click.expander')
          .bind('click.expander', function(event) {
            event.preventDefault();
            clearTimeout(delayedCollapse);
            var $detailsCollapsed = $(this).closest(detailSelector);
            reCollapse(o, $detailsCollapsed);

            if (defined.onCollapse) {
              o.onCollapse.call(thisEl, true);
            }
          });

          if (o.startExpanded) {
            expand({
              preventDefault: function() {},
              startExpanded: true
            });
          }

        }); // this.each
      },
      destroy: function() {

        this.each(function() {
          var o, details;
          var $this = $(this);

          if (!$this.data('expanderInit')) {
            return;
          }

          o = $.extend({}, $this.data('expander') || {}, opts);
          details = $this.find('.' + o.detailClass).contents();

          $this.removeData('expanderInit');
          $this.removeData('expander');

          $this.find(o.moreSelector).remove();
          $this.find('.' + o.summaryClass).remove();
          $this.find('.' + o.detailClass).after(details).remove();
          $this.find(o.lessSelector).remove();

        });
      }
    };

    // run the methods (almost always "init")
    if (methods[meth]) {
      methods[ meth ].call(this);
    }

    // utility functions
    function buildHTML(o, blocks) {
      var el = 'span';
      var summary = o.summary;
      var closingTagParts = rLastCloseTag.exec(summary);
      var closingTag = closingTagParts ? closingTagParts[2].toLowerCase() : '';

      if (blocks) {
        el = 'div';

        // if summary ends with a close tag, tuck the moreLabel inside it
        if (closingTagParts && closingTag !== 'a' && !o.expandAfterSummary) {
          summary = summary.replace(rLastCloseTag, o.moreLabel + '$1');
        } else {
          // otherwise (e.g. if ends with self-closing tag) just add moreLabel after summary
          // fixes #19
          summary += o.moreLabel;
        }

        // and wrap it in a div
        summary = '<div class="' + o.summaryClass + '">' + summary + '</div>';
      } else {
        summary += o.moreLabel;
      }

      return [
        summary,

        // after summary, add an optional prefix. Default single space prevents last word of summary
        // and first word of detail from collapsing together into what looks like a single word.
        // (could also be done with CSS, but this feels more natural)
        // Prefix made optional to fix issue #106
        o.detailPrefix || '',
        '<',
        el + ' class="' + o.detailClass + '"',
        '>',
        o.details,
        '</' + el + '>'
      ].join('');
    }

    function buildMoreLabel(o, detailText) {
      var ret = o.expandPrefix + '<span class="' + o.moreClass + '">';

      if (o.showWordCount) {

        o.wordCountText = o.wordCountText.replace(/\{\{count\}\}/, detailText.replace(rOpenCloseTag, '').replace(/\&(?:amp|nbsp);/g, '').replace(/(?:^\s+|\s+$)/, '').match(/\w+/g).length);

      } else {
        o.wordCountText = '';
      }
      ret += '<a href="#" class="' + o.moreLinkClass + '">' + o.expandText + o.wordCountText + '</a></span>';

      return ret;
    }

    function backup(txt, preserveWords) {
      if (txt.lastIndexOf('<') > txt.lastIndexOf('>')) {
        txt = txt.slice(0, txt.lastIndexOf('<'));
      }

      if (preserveWords) {
        txt = txt.replace(rAmpWordEnd, '');
      }

      return $.trim(txt);
    }

    function reCollapse(o, el) {
      el.stop(true, true)[o.collapseEffect](o.collapseSpeed, function() {
        var prevMore = el.prev('span.' + o.moreClass).show();

        if (!prevMore.length) {
          el.parent().children('div.' + o.summaryClass).show()
            .find('span.' + o.moreClass).show();
        }

        if (o.afterCollapse) {
          o.afterCollapse.call(el);
        }
      });
    }

    function delayCollapse(option, $collapseEl, thisEl) {
      if (option.collapseTimer) {
        delayedCollapse = setTimeout(function() {
          reCollapse(option, $collapseEl);

          if ($.isFunction(option.onCollapse)) {
            option.onCollapse.call(thisEl, false);
          }
        }, option.collapseTimer);
      }
    }

    function changeSlicePoint(info) {
      // Create placeholder string text
      var sliceOnTemp = 'ExpandMoreHere374216623';

      // Replace sliceOn with placeholder unaffected by .text() cleaning
      // (in case sliceOn contains html)
      var summaryTextClean = info.summaryText.replace(info.sliceOn, sliceOnTemp);
      summaryTextClean = $('<div>' + summaryTextClean + '</div>').text();

      // Find true location of sliceOn placeholder
      var sliceOnIndexClean = summaryTextClean.indexOf(sliceOnTemp);

      // Store location of html version too
      var sliceOnIndexHtml = info.summaryText.indexOf(info.sliceOn);

      // Base condition off of true sliceOn location...
      if (sliceOnIndexClean !== -1 && sliceOnIndexClean < info.slicePoint) {
        // ...but keep html in summaryText
        info.summaryText = info.allHtml.slice(0, sliceOnIndexHtml);
      }

      return info;
    }

    return this;
  };

  // plugin defaults
  $.fn.expander.defaults = $.expander.defaults;
});;
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('7(A 3c.3q!=="9"){3c.3q=9(e){9 t(){}t.5S=e;p 5R t}}(9(e,t,n){h r={1N:9(t,n){h r=c;r.$k=e(n);r.6=e.4M({},e.37.2B.6,r.$k.v(),t);r.2A=t;r.4L()},4L:9(){9 r(e){h n,r="";7(A t.6.33==="9"){t.6.33.R(c,[e])}l{1A(n 38 e.d){7(e.d.5M(n)){r+=e.d[n].1K}}t.$k.2y(r)}t.3t()}h t=c,n;7(A t.6.2H==="9"){t.6.2H.R(c,[t.$k])}7(A t.6.2O==="2Y"){n=t.6.2O;e.5K(n,r)}l{t.3t()}},3t:9(){h e=c;e.$k.v("d-4I",e.$k.2x("2w")).v("d-4F",e.$k.2x("H"));e.$k.z({2u:0});e.2t=e.6.q;e.4E();e.5v=0;e.1X=14;e.23()},23:9(){h e=c;7(e.$k.25().N===0){p b}e.1M();e.4C();e.$S=e.$k.25();e.E=e.$S.N;e.4B();e.$G=e.$k.17(".d-1K");e.$K=e.$k.17(".d-1p");e.3u="U";e.13=0;e.26=[0];e.m=0;e.4A();e.4z()},4z:9(){h e=c;e.2V();e.2W();e.4t();e.30();e.4r();e.4q();e.2p();e.4o();7(e.6.2o!==b){e.4n(e.6.2o)}7(e.6.O===j){e.6.O=4Q}e.19();e.$k.17(".d-1p").z("4i","4h");7(!e.$k.2m(":3n")){e.3o()}l{e.$k.z("2u",1)}e.5O=b;e.2l();7(A e.6.3s==="9"){e.6.3s.R(c,[e.$k])}},2l:9(){h e=c;7(e.6.1Z===j){e.1Z()}7(e.6.1B===j){e.1B()}e.4g();7(A e.6.3w==="9"){e.6.3w.R(c,[e.$k])}},3x:9(){h e=c;7(A e.6.3B==="9"){e.6.3B.R(c,[e.$k])}e.3o();e.2V();e.2W();e.4f();e.30();e.2l();7(A e.6.3D==="9"){e.6.3D.R(c,[e.$k])}},3F:9(){h e=c;t.1c(9(){e.3x()},0)},3o:9(){h e=c;7(e.$k.2m(":3n")===b){e.$k.z({2u:0});t.18(e.1C);t.18(e.1X)}l{p b}e.1X=t.4d(9(){7(e.$k.2m(":3n")){e.3F();e.$k.4b({2u:1},2M);t.18(e.1X)}},5x)},4B:9(){h e=c;e.$S.5n(\'<L H="d-1p">\').4a(\'<L H="d-1K"></L>\');e.$k.17(".d-1p").4a(\'<L H="d-1p-49">\');e.1H=e.$k.17(".d-1p-49");e.$k.z("4i","4h")},1M:9(){h e=c,t=e.$k.1I(e.6.1M),n=e.$k.1I(e.6.2i);7(!t){e.$k.I(e.6.1M)}7(!n){e.$k.I(e.6.2i)}},2V:9(){h t=c,n,r;7(t.6.2Z===b){p b}7(t.6.48===j){t.6.q=t.2t=1;t.6.1h=b;t.6.1s=b;t.6.1O=b;t.6.22=b;t.6.1Q=b;t.6.1R=b;p b}n=e(t.6.47).1f();7(n>(t.6.1s[0]||t.2t)){t.6.q=t.2t}7(t.6.1h!==b){t.6.1h.5g(9(e,t){p e[0]-t[0]});1A(r=0;r<t.6.1h.N;r+=1){7(t.6.1h[r][0]<=n){t.6.q=t.6.1h[r][1]}}}l{7(n<=t.6.1s[0]&&t.6.1s!==b){t.6.q=t.6.1s[1]}7(n<=t.6.1O[0]&&t.6.1O!==b){t.6.q=t.6.1O[1]}7(n<=t.6.22[0]&&t.6.22!==b){t.6.q=t.6.22[1]}7(n<=t.6.1Q[0]&&t.6.1Q!==b){t.6.q=t.6.1Q[1]}7(n<=t.6.1R[0]&&t.6.1R!==b){t.6.q=t.6.1R[1]}}7(t.6.q>t.E&&t.6.46===j){t.6.q=t.E}},4r:9(){h n=c,r,i;7(n.6.2Z!==j){p b}i=e(t).1f();n.3d=9(){7(e(t).1f()!==i){7(n.6.O!==b){t.18(n.1C)}t.5d(r);r=t.1c(9(){i=e(t).1f();n.3x()},n.6.45)}};e(t).44(n.3d)},4f:9(){h e=c;e.2g(e.m);7(e.6.O!==b){e.3j()}},43:9(){h t=c,n=0,r=t.E-t.6.q;t.$G.2f(9(i){h s=e(c);s.z({1f:t.M}).v("d-1K",3p(i));7(i%t.6.q===0||i===r){7(!(i>r)){n+=1}}s.v("d-24",n)})},42:9(){h e=c,t=e.$G.N*e.M;e.$K.z({1f:t*2,T:0});e.43()},2W:9(){h e=c;e.40();e.42();e.3Z();e.3v()},40:9(){h e=c;e.M=1F.4O(e.$k.1f()/e.6.q)},3v:9(){h e=c,t=(e.E*e.M-e.6.q*e.M)*-1;7(e.6.q>e.E){e.D=0;t=0;e.3z=0}l{e.D=e.E-e.6.q;e.3z=t}p t},3Y:9(){p 0},3Z:9(){h t=c,n=0,r=0,i,s,o;t.J=[0];t.3E=[];1A(i=0;i<t.E;i+=1){r+=t.M;t.J.2D(-r);7(t.6.12===j){s=e(t.$G[i]);o=s.v("d-24");7(o!==n){t.3E[n]=t.J[i];n=o}}}},4t:9(){h t=c;7(t.6.2a===j||t.6.1v===j){t.B=e(\'<L H="d-5A"/>\').5m("5l",!t.F.15).5c(t.$k)}7(t.6.1v===j){t.3T()}7(t.6.2a===j){t.3S()}},3S:9(){h t=c,n=e(\'<L H="d-4U"/>\');t.B.1o(n);t.1u=e("<L/>",{"H":"d-1n",2y:t.6.2U[0]||""});t.1q=e("<L/>",{"H":"d-U",2y:t.6.2U[1]||""});n.1o(t.1u).1o(t.1q);n.w("2X.B 21.B",\'L[H^="d"]\',9(e){e.1l()});n.w("2n.B 28.B",\'L[H^="d"]\',9(n){n.1l();7(e(c).1I("d-U")){t.U()}l{t.1n()}})},3T:9(){h t=c;t.1k=e(\'<L H="d-1v"/>\');t.B.1o(t.1k);t.1k.w("2n.B 28.B",".d-1j",9(n){n.1l();7(3p(e(c).v("d-1j"))!==t.m){t.1g(3p(e(c).v("d-1j")),j)}})},3P:9(){h t=c,n,r,i,s,o,u;7(t.6.1v===b){p b}t.1k.2y("");n=0;r=t.E-t.E%t.6.q;1A(s=0;s<t.E;s+=1){7(s%t.6.q===0){n+=1;7(r===s){i=t.E-t.6.q}o=e("<L/>",{"H":"d-1j"});u=e("<3N></3N>",{4R:t.6.39===j?n:"","H":t.6.39===j?"d-59":""});o.1o(u);o.v("d-1j",r===s?i:s);o.v("d-24",n);t.1k.1o(o)}}t.35()},35:9(){h t=c;7(t.6.1v===b){p b}t.1k.17(".d-1j").2f(9(){7(e(c).v("d-24")===e(t.$G[t.m]).v("d-24")){t.1k.17(".d-1j").Z("2d");e(c).I("2d")}})},3e:9(){h e=c;7(e.6.2a===b){p b}7(e.6.2e===b){7(e.m===0&&e.D===0){e.1u.I("1b");e.1q.I("1b")}l 7(e.m===0&&e.D!==0){e.1u.I("1b");e.1q.Z("1b")}l 7(e.m===e.D){e.1u.Z("1b");e.1q.I("1b")}l 7(e.m!==0&&e.m!==e.D){e.1u.Z("1b");e.1q.Z("1b")}}},30:9(){h e=c;e.3P();e.3e();7(e.B){7(e.6.q>=e.E){e.B.3K()}l{e.B.3J()}}},55:9(){h e=c;7(e.B){e.B.3k()}},U:9(e){h t=c;7(t.1E){p b}t.m+=t.6.12===j?t.6.q:1;7(t.m>t.D+(t.6.12===j?t.6.q-1:0)){7(t.6.2e===j){t.m=0;e="2k"}l{t.m=t.D;p b}}t.1g(t.m,e)},1n:9(e){h t=c;7(t.1E){p b}7(t.6.12===j&&t.m>0&&t.m<t.6.q){t.m=0}l{t.m-=t.6.12===j?t.6.q:1}7(t.m<0){7(t.6.2e===j){t.m=t.D;e="2k"}l{t.m=0;p b}}t.1g(t.m,e)},1g:9(e,n,r){h i=c,s;7(i.1E){p b}7(A i.6.1Y==="9"){i.6.1Y.R(c,[i.$k])}7(e>=i.D){e=i.D}l 7(e<=0){e=0}i.m=i.d.m=e;7(i.6.2o!==b&&r!=="4e"&&i.6.q===1&&i.F.1x===j){i.1t(0);7(i.F.1x===j){i.1L(i.J[e])}l{i.1r(i.J[e],1)}i.2r();i.4l();p b}s=i.J[e];7(i.F.1x===j){i.1T=b;7(n===j){i.1t("1w");t.1c(9(){i.1T=j},i.6.1w)}l 7(n==="2k"){i.1t(i.6.2v);t.1c(9(){i.1T=j},i.6.2v)}l{i.1t("1m");t.1c(9(){i.1T=j},i.6.1m)}i.1L(s)}l{7(n===j){i.1r(s,i.6.1w)}l 7(n==="2k"){i.1r(s,i.6.2v)}l{i.1r(s,i.6.1m)}}i.2r()},2g:9(e){h t=c;7(A t.6.1Y==="9"){t.6.1Y.R(c,[t.$k])}7(e>=t.D||e===-1){e=t.D}l 7(e<=0){e=0}t.1t(0);7(t.F.1x===j){t.1L(t.J[e])}l{t.1r(t.J[e],1)}t.m=t.d.m=e;t.2r()},2r:9(){h e=c;e.26.2D(e.m);e.13=e.d.13=e.26[e.26.N-2];e.26.5f(0);7(e.13!==e.m){e.35();e.3e();e.2l();7(e.6.O!==b){e.3j()}}7(A e.6.3y==="9"&&e.13!==e.m){e.6.3y.R(c,[e.$k])}},X:9(){h e=c;e.3A="X";t.18(e.1C)},3j:9(){h e=c;7(e.3A!=="X"){e.19()}},19:9(){h e=c;e.3A="19";7(e.6.O===b){p b}t.18(e.1C);e.1C=t.4d(9(){e.U(j)},e.6.O)},1t:9(e){h t=c;7(e==="1m"){t.$K.z(t.2z(t.6.1m))}l 7(e==="1w"){t.$K.z(t.2z(t.6.1w))}l 7(A e!=="2Y"){t.$K.z(t.2z(e))}},2z:9(e){p{"-1G-1a":"2C "+e+"1z 2s","-1W-1a":"2C "+e+"1z 2s","-o-1a":"2C "+e+"1z 2s",1a:"2C "+e+"1z 2s"}},3H:9(){p{"-1G-1a":"","-1W-1a":"","-o-1a":"",1a:""}},3I:9(e){p{"-1G-P":"1i("+e+"V, C, C)","-1W-P":"1i("+e+"V, C, C)","-o-P":"1i("+e+"V, C, C)","-1z-P":"1i("+e+"V, C, C)",P:"1i("+e+"V, C,C)"}},1L:9(e){h t=c;t.$K.z(t.3I(e))},3L:9(e){h t=c;t.$K.z({T:e})},1r:9(e,t){h n=c;n.29=b;n.$K.X(j,j).4b({T:e},{54:t||n.6.1m,3M:9(){n.29=j}})},4E:9(){h e=c,r="1i(C, C, C)",i=n.56("L"),s,o,u,a;i.2w.3O="  -1W-P:"+r+"; -1z-P:"+r+"; -o-P:"+r+"; -1G-P:"+r+"; P:"+r;s=/1i\\(C, C, C\\)/g;o=i.2w.3O.5i(s);u=o!==14&&o.N===1;a="5z"38 t||t.5Q.4P;e.F={1x:u,15:a}},4q:9(){h e=c;7(e.6.27!==b||e.6.1U!==b){e.3Q();e.3R()}},4C:9(){h e=c,t=["s","e","x"];e.16={};7(e.6.27===j&&e.6.1U===j){t=["2X.d 21.d","2N.d 3U.d","2n.d 3V.d 28.d"]}l 7(e.6.27===b&&e.6.1U===j){t=["2X.d","2N.d","2n.d 3V.d"]}l 7(e.6.27===j&&e.6.1U===b){t=["21.d","3U.d","28.d"]}e.16.3W=t[0];e.16.2K=t[1];e.16.2J=t[2]},3R:9(){h t=c;t.$k.w("5y.d",9(e){e.1l()});t.$k.w("21.3X",9(t){p e(t.1d).2m("5C, 5E, 5F, 5N")})},3Q:9(){9 s(e){7(e.2b!==W){p{x:e.2b[0].2c,y:e.2b[0].41}}7(e.2b===W){7(e.2c!==W){p{x:e.2c,y:e.41}}7(e.2c===W){p{x:e.52,y:e.53}}}}9 o(t){7(t==="w"){e(n).w(r.16.2K,a);e(n).w(r.16.2J,f)}l 7(t==="Q"){e(n).Q(r.16.2K);e(n).Q(r.16.2J)}}9 u(n){h u=n.3h||n||t.3g,a;7(u.5a===3){p b}7(r.E<=r.6.q){p}7(r.29===b&&!r.6.3f){p b}7(r.1T===b&&!r.6.3f){p b}7(r.6.O!==b){t.18(r.1C)}7(r.F.15!==j&&!r.$K.1I("3b")){r.$K.I("3b")}r.11=0;r.Y=0;e(c).z(r.3H());a=e(c).2h();i.2S=a.T;i.2R=s(u).x-a.T;i.2P=s(u).y-a.5o;o("w");i.2j=b;i.2L=u.1d||u.4c}9 a(o){h u=o.3h||o||t.3g,a,f;r.11=s(u).x-i.2R;r.2I=s(u).y-i.2P;r.Y=r.11-i.2S;7(A r.6.2E==="9"&&i.3C!==j&&r.Y!==0){i.3C=j;r.6.2E.R(r,[r.$k])}7((r.Y>8||r.Y<-8)&&r.F.15===j){7(u.1l!==W){u.1l()}l{u.5L=b}i.2j=j}7((r.2I>10||r.2I<-10)&&i.2j===b){e(n).Q("2N.d")}a=9(){p r.Y/5};f=9(){p r.3z+r.Y/5};r.11=1F.3v(1F.3Y(r.11,a()),f());7(r.F.1x===j){r.1L(r.11)}l{r.3L(r.11)}}9 f(n){h s=n.3h||n||t.3g,u,a,f;s.1d=s.1d||s.4c;i.3C=b;7(r.F.15!==j){r.$K.Z("3b")}7(r.Y<0){r.1y=r.d.1y="T"}l{r.1y=r.d.1y="3i"}7(r.Y!==0){u=r.4j();r.1g(u,b,"4e");7(i.2L===s.1d&&r.F.15!==j){e(s.1d).w("3a.4k",9(t){t.4S();t.4T();t.1l();e(t.1d).Q("3a.4k")});a=e.4N(s.1d,"4V").3a;f=a.4W();a.4X(0,0,f)}}o("Q")}h r=c,i={2R:0,2P:0,4Y:0,2S:0,2h:14,4Z:14,50:14,2j:14,51:14,2L:14};r.29=j;r.$k.w(r.16.3W,".d-1p",u)},4j:9(){h e=c,t=e.4m();7(t>e.D){e.m=e.D;t=e.D}l 7(e.11>=0){t=0;e.m=0}p t},4m:9(){h t=c,n=t.6.12===j?t.3E:t.J,r=t.11,i=14;e.2f(n,9(s,o){7(r-t.M/20>n[s+1]&&r-t.M/20<o&&t.34()==="T"){i=o;7(t.6.12===j){t.m=e.4p(i,t.J)}l{t.m=s}}l 7(r+t.M/20<o&&r+t.M/20>(n[s+1]||n[s]-t.M)&&t.34()==="3i"){7(t.6.12===j){i=n[s+1]||n[n.N-1];t.m=e.4p(i,t.J)}l{i=n[s+1];t.m=s+1}}});p t.m},34:9(){h e=c,t;7(e.Y<0){t="3i";e.3u="U"}l{t="T";e.3u="1n"}p t},4A:9(){h e=c;e.$k.w("d.U",9(){e.U()});e.$k.w("d.1n",9(){e.1n()});e.$k.w("d.19",9(t,n){e.6.O=n;e.19();e.32="19"});e.$k.w("d.X",9(){e.X();e.32="X"});e.$k.w("d.1g",9(t,n){e.1g(n)});e.$k.w("d.2g",9(t,n){e.2g(n)})},2p:9(){h e=c;7(e.6.2p===j&&e.F.15!==j&&e.6.O!==b){e.$k.w("57",9(){e.X()});e.$k.w("58",9(){7(e.32!=="X"){e.19()}})}},1Z:9(){h t=c,n,r,i,s,o;7(t.6.1Z===b){p b}1A(n=0;n<t.E;n+=1){r=e(t.$G[n]);7(r.v("d-1e")==="1e"){4s}i=r.v("d-1K");s=r.17(".5b");7(A s.v("1J")!=="2Y"){r.v("d-1e","1e");4s}7(r.v("d-1e")===W){s.3K();r.I("4u").v("d-1e","5e")}7(t.6.4v===j){o=i>=t.m}l{o=j}7(o&&i<t.m+t.6.q&&s.N){t.4w(r,s)}}},4w:9(e,n){9 o(){e.v("d-1e","1e").Z("4u");n.5h("v-1J");7(r.6.4x==="4y"){n.5j(5k)}l{n.3J()}7(A r.6.2T==="9"){r.6.2T.R(c,[r.$k])}}9 u(){i+=1;7(r.2Q(n.3l(0))||s===j){o()}l 7(i<=2q){t.1c(u,2q)}l{o()}}h r=c,i=0,s;7(n.5p("5q")==="5r"){n.z("5s-5t","5u("+n.v("1J")+")");s=j}l{n[0].1J=n.v("1J")}u()},1B:9(){9 s(){h r=e(n.$G[n.m]).2G();n.1H.z("2G",r+"V");7(!n.1H.1I("1B")){t.1c(9(){n.1H.I("1B")},0)}}9 o(){i+=1;7(n.2Q(r.3l(0))){s()}l 7(i<=2q){t.1c(o,2q)}l{n.1H.z("2G","")}}h n=c,r=e(n.$G[n.m]).17("5w"),i;7(r.3l(0)!==W){i=0;o()}l{s()}},2Q:9(e){h t;7(!e.3M){p b}t=A e.4D;7(t!=="W"&&e.4D===0){p b}p j},4g:9(){h t=c,n;7(t.6.2F===j){t.$G.Z("2d")}t.1D=[];1A(n=t.m;n<t.m+t.6.q;n+=1){t.1D.2D(n);7(t.6.2F===j){e(t.$G[n]).I("2d")}}t.d.1D=t.1D},4n:9(e){h t=c;t.4G="d-"+e+"-5B";t.4H="d-"+e+"-38"},4l:9(){9 a(e){p{2h:"5D",T:e+"V"}}h e=c,t=e.4G,n=e.4H,r=e.$G.1S(e.m),i=e.$G.1S(e.13),s=1F.4J(e.J[e.m])+e.J[e.13],o=1F.4J(e.J[e.m])+e.M/2,u="5G 5H 5I 5J";e.1E=j;e.$K.I("d-1P").z({"-1G-P-1P":o+"V","-1W-4K-1P":o+"V","4K-1P":o+"V"});i.z(a(s,10)).I(t).w(u,9(){e.3m=j;i.Q(u);e.31(i,t)});r.I(n).w(u,9(){e.36=j;r.Q(u);e.31(r,n)})},31:9(e,t){h n=c;e.z({2h:"",T:""}).Z(t);7(n.3m&&n.36){n.$K.Z("d-1P");n.3m=b;n.36=b;n.1E=b}},4o:9(){h e=c;e.d={2A:e.2A,5P:e.$k,S:e.$S,G:e.$G,m:e.m,13:e.13,1D:e.1D,15:e.F.15,F:e.F,1y:e.1y}},3G:9(){h r=c;r.$k.Q(".d d 21.3X");e(n).Q(".d d");e(t).Q("44",r.3d)},1V:9(){h e=c;7(e.$k.25().N!==0){e.$K.3r();e.$S.3r().3r();7(e.B){e.B.3k()}}e.3G();e.$k.2x("2w",e.$k.v("d-4I")||"").2x("H",e.$k.v("d-4F"))},5T:9(){h e=c;e.X();t.18(e.1X);e.1V();e.$k.5U()},5V:9(t){h n=c,r=e.4M({},n.2A,t);n.1V();n.1N(r,n.$k)},5W:9(e,t){h n=c,r;7(!e){p b}7(n.$k.25().N===0){n.$k.1o(e);n.23();p b}n.1V();7(t===W||t===-1){r=-1}l{r=t}7(r>=n.$S.N||r===-1){n.$S.1S(-1).5X(e)}l{n.$S.1S(r).5Y(e)}n.23()},5Z:9(e){h t=c,n;7(t.$k.25().N===0){p b}7(e===W||e===-1){n=-1}l{n=e}t.1V();t.$S.1S(n).3k();t.23()}};e.37.2B=9(t){p c.2f(9(){7(e(c).v("d-1N")===j){p b}e(c).v("d-1N",j);h n=3c.3q(r);n.1N(t,c);e.v(c,"2B",n)})};e.37.2B.6={q:5,1h:b,1s:[60,4],1O:[61,3],22:[62,2],1Q:b,1R:[63,1],48:b,46:b,1m:2M,1w:64,2v:65,O:b,2p:b,2a:b,2U:["1n","U"],2e:j,12:b,1v:j,39:b,2Z:j,45:2M,47:t,1M:"d-66",2i:"d-2i",1Z:b,4v:j,4x:"4y",1B:b,2O:b,33:b,3f:j,27:j,1U:j,2F:b,2o:b,3B:b,3D:b,2H:b,3s:b,1Y:b,3y:b,3w:b,2E:b,2T:b}})(67,68,69)',62,382,'||||||options|if||function||false|this|owl||||var||true|elem|else|currentItem|||return|items|||||data|on|||css|typeof|owlControls|0px|maximumItem|itemsAmount|browser|owlItems|class|addClass|positionsInArray|owlWrapper|div|itemWidth|length|autoPlay|transform|off|apply|userItems|left|next|px|undefined|stop|newRelativeX|removeClass||newPosX|scrollPerPage|prevItem|null|isTouch|ev_types|find|clearInterval|play|transition|disabled|setTimeout|target|loaded|width|goTo|itemsCustom|translate3d|page|paginationWrapper|preventDefault|slideSpeed|prev|append|wrapper|buttonNext|css2slide|itemsDesktop|swapSpeed|buttonPrev|pagination|paginationSpeed|support3d|dragDirection|ms|for|autoHeight|autoPlayInterval|visibleItems|isTransition|Math|webkit|wrapperOuter|hasClass|src|item|transition3d|baseClass|init|itemsDesktopSmall|origin|itemsTabletSmall|itemsMobile|eq|isCss3Finish|touchDrag|unWrap|moz|checkVisible|beforeMove|lazyLoad||mousedown|itemsTablet|setVars|roundPages|children|prevArr|mouseDrag|mouseup|isCssFinish|navigation|touches|pageX|active|rewindNav|each|jumpTo|position|theme|sliding|rewind|eachMoveUpdate|is|touchend|transitionStyle|stopOnHover|100|afterGo|ease|orignalItems|opacity|rewindSpeed|style|attr|html|addCssSpeed|userOptions|owlCarousel|all|push|startDragging|addClassActive|height|beforeInit|newPosY|end|move|targetElement|200|touchmove|jsonPath|offsetY|completeImg|offsetX|relativePos|afterLazyLoad|navigationText|updateItems|calculateAll|touchstart|string|responsive|updateControls|clearTransStyle|hoverStatus|jsonSuccess|moveDirection|checkPagination|endCurrent|fn|in|paginationNumbers|click|grabbing|Object|resizer|checkNavigation|dragBeforeAnimFinish|event|originalEvent|right|checkAp|remove|get|endPrev|visible|watchVisibility|Number|create|unwrap|afterInit|logIn|playDirection|max|afterAction|updateVars|afterMove|maximumPixels|apStatus|beforeUpdate|dragging|afterUpdate|pagesInArray|reload|clearEvents|removeTransition|doTranslate|show|hide|css2move|complete|span|cssText|updatePagination|gestures|disabledEvents|buildButtons|buildPagination|mousemove|touchcancel|start|disableTextSelect|min|loops|calculateWidth|pageY|appendWrapperSizes|appendItemsSizes|resize|responsiveRefreshRate|itemsScaleUp|responsiveBaseWidth|singleItem|outer|wrap|animate|srcElement|setInterval|drag|updatePosition|onVisibleItems|block|display|getNewPosition|disable|singleItemTransition|closestItem|transitionTypes|owlStatus|inArray|moveEvents|response|continue|buildControls|loading|lazyFollow|lazyPreload|lazyEffect|fade|onStartup|customEvents|wrapItems|eventTypes|naturalWidth|checkBrowser|originalClasses|outClass|inClass|originalStyles|abs|perspective|loadContent|extend|_data|round|msMaxTouchPoints|5e3|text|stopImmediatePropagation|stopPropagation|buttons|events|pop|splice|baseElWidth|minSwipe|maxSwipe|dargging|clientX|clientY|duration|destroyControls|createElement|mouseover|mouseout|numbers|which|lazyOwl|appendTo|clearTimeout|checked|shift|sort|removeAttr|match|fadeIn|400|clickable|toggleClass|wrapAll|top|prop|tagName|DIV|background|image|url|wrapperWidth|img|500|dragstart|ontouchstart|controls|out|input|relative|textarea|select|webkitAnimationEnd|oAnimationEnd|MSAnimationEnd|animationend|getJSON|returnValue|hasOwnProperty|option|onstartup|baseElement|navigator|new|prototype|destroy|removeData|reinit|addItem|after|before|removeItem|1199|979|768|479|800|1e3|carousel|jQuery|window|document'.split('|'),0,{}));

var TastyCookieManager = {

    init: function () {
        var _self = this;
        $.ajax({
            type: 'GET',
            url: '/api/cookieinfo',
            contentType: "application/json",
            success: function (response) {
                _self.setCookie(response);
            }
        });
    },


    setCookie: function (response) {
        var _self = this;
        var data = JSON.parse(response);
        data.cookieGroups.forEach(function (group) {
            group.triggerReload = false;
            group.cookies= [{
                cookieInit: function () {
                    _self.cookieCallback(group.groupId);
                }
            }]
        });

        var TastyCookieProps = data;
        TastyCookieProps.modal.tastyCookieDuration = 365;
        TastyCookieProps.modal.cookieAccordions = false;
        window.TastyCookie(TastyCookieProps);
    },

    cookieCallback: function (type) {
        var elems = Array.from(
            $("script[data-cookie-type='" + type + "']")
        );

        if (elems.length) {
            elems.forEach(function(item) {
                const newScriptTag = document.createElement('script');
                newScriptTag.type = 'application/javascript';

                if (item.src && item.src.length > 0) {
                    newScriptTag.setAttribute('src', item.src);
                }

                if (item.getAttribute('data-src') && item.getAttribute('data-src').length > 0) {
                    newScriptTag.setAttribute('src', item.getAttribute('data-src'));
                }

                newScriptTag.appendChild(document.createTextNode(item.innerText));
                item.parentNode.replaceChild(newScriptTag, item);
            });
        }
    }
}

TastyCookieManager.init();;
$(document).ready(function () {
    $('body').on('click', '[data-joblisting-loadmore]', function (e) {
        e.preventDefault();
        var $clickedElement = $(this);
        var $container = $clickedElement.parent().parent();
        $.get('/JobListingBlock/LoadAdditionalListings/', { skip: $container.children('div').length, contentLink: $(this).data('contentlink') }, function (data) {
            $clickedElement.parent().remove();
            $('.link_show_all').parent().remove();
            $container.append(data);            
        });
    });
});;
/*
 * 
 * TableSorter 2.0 - Client-side table sorting with ease!
 * Version 2.0.5b
 * @requires jQuery v1.2.3
 * 
 * Copyright (c) 2007 Christian Bach
 * Examples and docs at: http://tablesorter.com
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * 
 */
/**
 * 
 * @description Create a sortable table with multi-column sorting capabilitys
 * 
 * @example $('table').tablesorter();
 * @desc Create a simple tablesorter interface.
 * 
 * @example $('table').tablesorter({ sortList:[[0,0],[1,0]] });
 * @desc Create a tablesorter interface and sort on the first and secound column column headers.
 * 
 * @example $('table').tablesorter({ headers: { 0: { sorter: false}, 1: {sorter: false} } });
 *          
 * @desc Create a tablesorter interface and disableing the first and second  column headers.
 *      
 * 
 * @example $('table').tablesorter({ headers: { 0: {sorter:"integer"}, 1: {sorter:"currency"} } });
 * 
 * @desc Create a tablesorter interface and set a column parser for the first
 *       and second column.
 * 
 * 
 * @param Object
 *            settings An object literal containing key/value pairs to provide
 *            optional settings.
 * 
 * 
 * @option String cssHeader (optional) A string of the class name to be appended
 *         to sortable tr elements in the thead of the table. Default value:
 *         "header"
 * 
 * @option String cssAsc (optional) A string of the class name to be appended to
 *         sortable tr elements in the thead on a ascending sort. Default value:
 *         "headerSortUp"
 * 
 * @option String cssDesc (optional) A string of the class name to be appended
 *         to sortable tr elements in the thead on a descending sort. Default
 *         value: "headerSortDown"
 * 
 * @option String sortInitialOrder (optional) A string of the inital sorting
 *         order can be asc or desc. Default value: "asc"
 * 
 * @option String sortMultisortKey (optional) A string of the multi-column sort
 *         key. Default value: "shiftKey"
 * 
 * @option String textExtraction (optional) A string of the text-extraction
 *         method to use. For complex html structures inside td cell set this
 *         option to "complex", on large tables the complex option can be slow.
 *         Default value: "simple"
 * 
 * @option Object headers (optional) An array containing the forces sorting
 *         rules. This option let's you specify a default sorting rule. Default
 *         value: null
 * 
 * @option Array sortList (optional) An array containing the forces sorting
 *         rules. This option let's you specify a default sorting rule. Default
 *         value: null
 * 
 * @option Array sortForce (optional) An array containing forced sorting rules.
 *         This option let's you specify a default sorting rule, which is
 *         prepended to user-selected rules. Default value: null
 * 
 * @option Boolean sortLocaleCompare (optional) Boolean flag indicating whatever
 *         to use String.localeCampare method or not. Default set to true.
 * 
 * 
 * @option Array sortAppend (optional) An array containing forced sorting rules.
 *         This option let's you specify a default sorting rule, which is
 *         appended to user-selected rules. Default value: null
 * 
 * @option Boolean widthFixed (optional) Boolean flag indicating if tablesorter
 *         should apply fixed widths to the table columns. This is usefull when
 *         using the pager companion plugin. This options requires the dimension
 *         jquery plugin. Default value: false
 * 
 * @option Boolean cancelSelection (optional) Boolean flag indicating if
 *         tablesorter should cancel selection of the table headers text.
 *         Default value: true
 * 
 * @option Boolean debug (optional) Boolean flag indicating if tablesorter
 *         should display debuging information usefull for development.
 * 
 * @type jQuery
 * 
 * @name tablesorter
 * 
 * @cat Plugins/Tablesorter
 * 
 * @author Christian Bach/christian.bach@polyester.se
 */

(function ($) {
    $.extend({
        tablesorter: new
        function () {

            var parsers = [],
                widgets = [];

            this.defaults = {
                cssHeader: "header",
                cssAsc: "headerSortUp",
                cssDesc: "headerSortDown",
                cssChildRow: "expand-child",
                sortInitialOrder: "asc",
                sortMultiSortKey: "shiftKey",
                sortForce: null,
                sortAppend: null,
                sortLocaleCompare: true,
                textExtraction: "simple",
                parsers: {}, widgets: [],
                widgetZebra: {
                    css: ["even", "odd"]
                }, headers: {}, widthFixed: false,
                cancelSelection: true,
                sortList: [],
                headerList: [],
                dateFormat: "us",
                decimal: '/\.|\,/g',
                onRenderHeader: null,
                selectorHeaders: 'thead th',
                debug: false
            };

            /* debuging utils */

            function benchmark(s, d) {
                log(s + "," + (new Date().getTime() - d.getTime()) + "ms");
            }

            this.benchmark = benchmark;

            function log(s) {
                if (typeof console != "undefined" && typeof console.debug != "undefined") {
                    console.log(s);
                } else {
                    alert(s);
                }
            }

            /* parsers utils */

            function buildParserCache(table, $headers) {

                if (table.config.debug) {
                    var parsersDebug = "";
                }

                if (table.tBodies.length == 0) return; // In the case of empty tables
                var rows = table.tBodies[0].rows;

                if (rows[0]) {

                    var list = [],
                        cells = rows[0].cells,
                        l = cells.length;

                    for (var i = 0; i < l; i++) {

                        var p = false;

                        if ($.metadata && ($($headers[i]).metadata() && $($headers[i]).metadata().sorter)) {

                            p = getParserById($($headers[i]).metadata().sorter);

                        } else if ((table.config.headers[i] && table.config.headers[i].sorter)) {

                            p = getParserById(table.config.headers[i].sorter);
                        }
                        if (!p) {

                            p = detectParserForColumn(table, rows, -1, i);
                        }

                        if (table.config.debug) {
                            parsersDebug += "column:" + i + " parser:" + p.id + "\n";
                        }

                        list.push(p);
                    }
                }

                if (table.config.debug) {
                    log(parsersDebug);
                }

                return list;
            };

            function detectParserForColumn(table, rows, rowIndex, cellIndex) {
                var l = parsers.length,
                    node = false,
                    nodeValue = false,
                    keepLooking = true;
                while (nodeValue == '' && keepLooking) {
                    rowIndex++;
                    if (rows[rowIndex]) {
                        node = getNodeFromRowAndCellIndex(rows, rowIndex, cellIndex);
                        nodeValue = trimAndGetNodeText(table.config, node);
                        if (table.config.debug) {
                            log('Checking if value was empty on row:' + rowIndex);
                        }
                    } else {
                        keepLooking = false;
                    }
                }
                for (var i = 1; i < l; i++) {
                    if (parsers[i].is(nodeValue, table, node)) {
                        return parsers[i];
                    }
                }
                // 0 is always the generic parser (text)
                return parsers[0];
            }

            function getNodeFromRowAndCellIndex(rows, rowIndex, cellIndex) {
                return rows[rowIndex].cells[cellIndex];
            }

            function trimAndGetNodeText(config, node) {
                return $.trim(getElementText(config, node));
            }

            function getParserById(name) {
                var l = parsers.length;
                for (var i = 0; i < l; i++) {
                    if (parsers[i].id.toLowerCase() == name.toLowerCase()) {
                        return parsers[i];
                    }
                }
                return false;
            }

            /* utils */

            function buildCache(table) {

                if (table.config.debug) {
                    var cacheTime = new Date();
                }

                var totalRows = (table.tBodies[0] && table.tBodies[0].rows.length) || 0,
                    totalCells = (table.tBodies[0].rows[0] && table.tBodies[0].rows[0].cells.length) || 0,
                    parsers = table.config.parsers,
                    cache = {
                        row: [],
                        normalized: []
                    };

                for (var i = 0; i < totalRows; ++i) {

                    /** Add the table data to main data array */
                    var c = $(table.tBodies[0].rows[i]),
                        cols = [];

                    // if this is a child row, add it to the last row's children and
                    // continue to the next row
                    if (c.hasClass(table.config.cssChildRow)) {
                        cache.row[cache.row.length - 1] = cache.row[cache.row.length - 1].add(c);
                        // go to the next for loop
                        continue;
                    }

                    cache.row.push(c);

                    for (var j = 0; j < totalCells; ++j) {
                        cols.push(parsers[j].format(getElementText(table.config, c[0].cells[j]), table, c[0].cells[j]));
                    }

                    cols.push(cache.normalized.length); // add position for rowCache
                    cache.normalized.push(cols);
                    cols = null;
                };

                if (table.config.debug) {
                    benchmark("Building cache for " + totalRows + " rows:", cacheTime);
                }

                return cache;
            };

            function getElementText(config, node) {

                var text = "";

                if (!node) return "";

                if (!config.supportsTextContent) config.supportsTextContent = node.textContent || false;

                if (config.textExtraction == "simple") {
                    if (config.supportsTextContent) {
                        text = node.textContent;
                    } else {
                        if (node.childNodes[0] && node.childNodes[0].hasChildNodes()) {
                            text = node.childNodes[0].innerHTML;
                        } else {
                            text = node.innerHTML;
                        }
                    }
                } else {
                    if (typeof(config.textExtraction) == "function") {
                        text = config.textExtraction(node);
                    } else {
                        text = $(node).text();
                    }
                }
                return text;
            }

            function appendToTable(table, cache) {

                if (table.config.debug) {
                    var appendTime = new Date()
                }

                var c = cache,
                    r = c.row,
                    n = c.normalized,
                    totalRows = n.length,
                    checkCell = (n[0].length - 1),
                    tableBody = $(table.tBodies[0]),
                    rows = [];


                for (var i = 0; i < totalRows; i++) {
                    var pos = n[i][checkCell];

                    rows.push(r[pos]);

                    if (!table.config.appender) {

                        //var o = ;
                        var l = r[pos].length;
                        for (var j = 0; j < l; j++) {
                            tableBody[0].appendChild(r[pos][j]);
                        }

                        // 
                    }
                }



                if (table.config.appender) {

                    table.config.appender(table, rows);
                }

                rows = null;

                if (table.config.debug) {
                    benchmark("Rebuilt table:", appendTime);
                }

                // apply table widgets
                applyWidget(table);

                // trigger sortend
                setTimeout(function () {
                    $(table).trigger("sortEnd");
                }, 0);

            };

            function buildHeaders(table) {

                if (table.config.debug) {
                    var time = new Date();
                }

                var meta = ($.metadata) ? true : false;
                
                var header_index = computeTableHeaderCellIndexes(table);

                $tableHeaders = $(table.config.selectorHeaders, table).each(function (index) {

                    this.column = header_index[this.parentNode.rowIndex + "-" + this.cellIndex];
                    // this.column = index;
                    this.order = formatSortingOrder(table.config.sortInitialOrder);
                    
					
					this.count = this.order;

                    if (checkHeaderMetadata(this) || checkHeaderOptions(table, index)) this.sortDisabled = true;
					if (checkHeaderOptionsSortingLocked(table, index)) this.order = this.lockedOrder = checkHeaderOptionsSortingLocked(table, index);

                    if (!this.sortDisabled) {
                        var $th = $(this).addClass(table.config.cssHeader);
                        if (table.config.onRenderHeader) table.config.onRenderHeader.apply($th);
                    }

                    // add cell to headerList
                    table.config.headerList[index] = this;
                });

                if (table.config.debug) {
                    benchmark("Built headers:", time);
                    log($tableHeaders);
                }

                return $tableHeaders;

            };

            // from:
            // http://www.javascripttoolbox.com/lib/table/examples.php
            // http://www.javascripttoolbox.com/temp/table_cellindex.html


            function computeTableHeaderCellIndexes(t) {
                var matrix = [];
                var lookup = {};
                var thead = t.getElementsByTagName('THEAD')[0];
                var trs = thead.getElementsByTagName('TR');

                for (var i = 0; i < trs.length; i++) {
                    var cells = trs[i].cells;
                    for (var j = 0; j < cells.length; j++) {
                        var c = cells[j];

                        var rowIndex = c.parentNode.rowIndex;
                        var cellId = rowIndex + "-" + c.cellIndex;
                        var rowSpan = c.rowSpan || 1;
                        var colSpan = c.colSpan || 1
                        var firstAvailCol;
                        if (typeof(matrix[rowIndex]) == "undefined") {
                            matrix[rowIndex] = [];
                        }
                        // Find first available column in the first row
                        for (var k = 0; k < matrix[rowIndex].length + 1; k++) {
                            if (typeof(matrix[rowIndex][k]) == "undefined") {
                                firstAvailCol = k;
                                break;
                            }
                        }
                        lookup[cellId] = firstAvailCol;
                        for (var k = rowIndex; k < rowIndex + rowSpan; k++) {
                            if (typeof(matrix[k]) == "undefined") {
                                matrix[k] = [];
                            }
                            var matrixrow = matrix[k];
                            for (var l = firstAvailCol; l < firstAvailCol + colSpan; l++) {
                                matrixrow[l] = "x";
                            }
                        }
                    }
                }
                return lookup;
            }

            function checkCellColSpan(table, rows, row) {
                var arr = [],
                    r = table.tHead.rows,
                    c = r[row].cells;

                for (var i = 0; i < c.length; i++) {
                    var cell = c[i];

                    if (cell.colSpan > 1) {
                        arr = arr.concat(checkCellColSpan(table, headerArr, row++));
                    } else {
                        if (table.tHead.length == 1 || (cell.rowSpan > 1 || !r[row + 1])) {
                            arr.push(cell);
                        }
                        // headerArr[row] = (i+row);
                    }
                }
                return arr;
            };

            function checkHeaderMetadata(cell) {
                if (($.metadata) && ($(cell).metadata().sorter === false)) {
                    return true;
                };
                return false;
            }

            function checkHeaderOptions(table, i) {
                if ((table.config.headers[i]) && (table.config.headers[i].sorter === false)) {
                    return true;
                };
                return false;
            }
			
			 function checkHeaderOptionsSortingLocked(table, i) {
                if ((table.config.headers[i]) && (table.config.headers[i].lockedOrder)) return table.config.headers[i].lockedOrder;
                return false;
            }
			
            function applyWidget(table) {
                var c = table.config.widgets;
                var l = c.length;
                for (var i = 0; i < l; i++) {

                    getWidgetById(c[i]).format(table);
                }

            }

            function getWidgetById(name) {
                var l = widgets.length;
                for (var i = 0; i < l; i++) {
                    if (widgets[i].id.toLowerCase() == name.toLowerCase()) {
                        return widgets[i];
                    }
                }
            };

            function formatSortingOrder(v) {
                if (typeof(v) != "Number") {
                    return (v.toLowerCase() == "desc") ? 1 : 0;
                } else {
                    return (v == 1) ? 1 : 0;
                }
            }

            function isValueInArray(v, a) {
                var l = a.length;
                for (var i = 0; i < l; i++) {
                    if (a[i][0] == v) {
                        return true;
                    }
                }
                return false;
            }

            function setHeadersCss(table, $headers, list, css) {
                // remove all header information
                $headers.removeClass(css[0]).removeClass(css[1]);

                var h = [];
                $headers.each(function (offset) {
                    if (!this.sortDisabled) {
                        h[this.column] = $(this);
                    }
                });

                var l = list.length;
                for (var i = 0; i < l; i++) {
                    h[list[i][0]].addClass(css[list[i][1]]);
                }
            }

            function fixColumnWidth(table, $headers) {
                var c = table.config;
                if (c.widthFixed) {
                    var colgroup = $('<colgroup>');
                    $("tr:first td", table.tBodies[0]).each(function () {
                        colgroup.append($('<col>').css('width', $(this).width()));
                    });
                    $(table).prepend(colgroup);
                };
            }

            function updateHeaderSortCount(table, sortList) {
                var c = table.config,
                    l = sortList.length;
                for (var i = 0; i < l; i++) {
                    var s = sortList[i],
                        o = c.headerList[s[0]];
                    o.count = s[1];
                    o.count++;
                }
            }

            /* sorting methods */

            function multisort(table, sortList, cache) {

                if (table.config.debug) {
                    var sortTime = new Date();
                }

                var dynamicExp = "var sortWrapper = function(a,b) {",
                    l = sortList.length;

                // TODO: inline functions.
                for (var i = 0; i < l; i++) {

                    var c = sortList[i][0];
                    var order = sortList[i][1];
                    // var s = (getCachedSortType(table.config.parsers,c) == "text") ?
                    // ((order == 0) ? "sortText" : "sortTextDesc") : ((order == 0) ?
                    // "sortNumeric" : "sortNumericDesc");
                    // var s = (table.config.parsers[c].type == "text") ? ((order == 0)
                    // ? makeSortText(c) : makeSortTextDesc(c)) : ((order == 0) ?
                    // makeSortNumeric(c) : makeSortNumericDesc(c));
                    var s = (table.config.parsers[c].type == "text") ? ((order == 0) ? makeSortFunction("text", "asc", c) : makeSortFunction("text", "desc", c)) : ((order == 0) ? makeSortFunction("numeric", "asc", c) : makeSortFunction("numeric", "desc", c));
                    var e = "e" + i;

                    dynamicExp += "var " + e + " = " + s; // + "(a[" + c + "],b[" + c
                    // + "]); ";
                    dynamicExp += "if(" + e + ") { return " + e + "; } ";
                    dynamicExp += "else { ";

                }

                // if value is the same keep orignal order
                var orgOrderCol = cache.normalized[0].length - 1;
                dynamicExp += "return a[" + orgOrderCol + "]-b[" + orgOrderCol + "];";

                for (var i = 0; i < l; i++) {
                    dynamicExp += "}; ";
                }

                dynamicExp += "return 0; ";
                dynamicExp += "}; ";

                if (table.config.debug) {
                    benchmark("Evaling expression:" + dynamicExp, new Date());
                }

                eval(dynamicExp);

                cache.normalized.sort(sortWrapper);

                if (table.config.debug) {
                    benchmark("Sorting on " + sortList.toString() + " and dir " + order + " time:", sortTime);
                }

                return cache;
            };

            function makeSortFunction(type, direction, index) {
                var a = "a[" + index + "]",
                    b = "b[" + index + "]";
                if (type == 'text' && direction == 'asc') {
                    return "(" + a + " == " + b + " ? 0 : (" + a + " === null ? Number.POSITIVE_INFINITY : (" + b + " === null ? Number.NEGATIVE_INFINITY : (" + a + " < " + b + ") ? -1 : 1 )));";
                } else if (type == 'text' && direction == 'desc') {
                    return "(" + a + " == " + b + " ? 0 : (" + a + " === null ? Number.POSITIVE_INFINITY : (" + b + " === null ? Number.NEGATIVE_INFINITY : (" + b + " < " + a + ") ? -1 : 1 )));";
                } else if (type == 'numeric' && direction == 'asc') {
                    return "(" + a + " === null && " + b + " === null) ? 0 :(" + a + " === null ? Number.POSITIVE_INFINITY : (" + b + " === null ? Number.NEGATIVE_INFINITY : " + a + " - " + b + "));";
                } else if (type == 'numeric' && direction == 'desc') {
                    return "(" + a + " === null && " + b + " === null) ? 0 :(" + a + " === null ? Number.POSITIVE_INFINITY : (" + b + " === null ? Number.NEGATIVE_INFINITY : " + b + " - " + a + "));";
                }
            };

            function makeSortText(i) {
                return "((a[" + i + "] < b[" + i + "]) ? -1 : ((a[" + i + "] > b[" + i + "]) ? 1 : 0));";
            };

            function makeSortTextDesc(i) {
                return "((b[" + i + "] < a[" + i + "]) ? -1 : ((b[" + i + "] > a[" + i + "]) ? 1 : 0));";
            };

            function makeSortNumeric(i) {
                return "a[" + i + "]-b[" + i + "];";
            };

            function makeSortNumericDesc(i) {
                return "b[" + i + "]-a[" + i + "];";
            };

            function sortText(a, b) {
                if (table.config.sortLocaleCompare) return a.localeCompare(b);
                return ((a < b) ? -1 : ((a > b) ? 1 : 0));
            };

            function sortTextDesc(a, b) {
                if (table.config.sortLocaleCompare) return b.localeCompare(a);
                return ((b < a) ? -1 : ((b > a) ? 1 : 0));
            };

            function sortNumeric(a, b) {
                return a - b;
            };

            function sortNumericDesc(a, b) {
                return b - a;
            };

            function getCachedSortType(parsers, i) {
                return parsers[i].type;
            }; /* public methods */
            this.construct = function (settings) {
                return this.each(function () {
                    // if no thead or tbody quit.
                    if (!this.tHead || !this.tBodies) return;
                    // declare
                    var $this, $document, $headers, cache, config, shiftDown = 0,
                        sortOrder;
                    // new blank config object
                    this.config = {};
                    // merge and extend.
                    config = $.extend(this.config, $.tablesorter.defaults, settings);
                    // store common expression for speed
                    $this = $(this);
                    // save the settings where they read
                    $.data(this, "tablesorter", config);
                    // build headers
                    $headers = buildHeaders(this);
                    // try to auto detect column type, and store in tables config
                    this.config.parsers = buildParserCache(this, $headers);
                    // build the cache for the tbody cells
                    cache = buildCache(this);
                    // get the css class names, could be done else where.
                    var sortCSS = [config.cssDesc, config.cssAsc];
                    // fixate columns if the users supplies the fixedWidth option
                    fixColumnWidth(this);
                    // apply event handling to headers
                    // this is to big, perhaps break it out?
                    $headers.click(

                    function (e) {
                        var totalRows = ($this[0].tBodies[0] && $this[0].tBodies[0].rows.length) || 0;
                        if (!this.sortDisabled && totalRows > 0) {
                            // Only call sortStart if sorting is
                            // enabled.
                            $this.trigger("sortStart");
                            // store exp, for speed
                            var $cell = $(this);
                            // get current column index
                            var i = this.column;
                            // get current column sort order
                            this.order = this.count++ % 2;
							// always sort on the locked order.
							if(this.lockedOrder) this.order = this.lockedOrder;
							
							// user only whants to sort on one
                            // column
                            if (!e[config.sortMultiSortKey]) {
                                // flush the sort list
                                config.sortList = [];
                                if (config.sortForce != null) {
                                    var a = config.sortForce;
                                    for (var j = 0; j < a.length; j++) {
                                        if (a[j][0] != i) {
                                            config.sortList.push(a[j]);
                                        }
                                    }
                                }
                                // add column to sort list
                                config.sortList.push([i, this.order]);
                                // multi column sorting
                            } else {
                                // the user has clicked on an all
                                // ready sortet column.
                                if (isValueInArray(i, config.sortList)) {
                                    // revers the sorting direction
                                    // for all tables.
                                    for (var j = 0; j < config.sortList.length; j++) {
                                        var s = config.sortList[j],
                                            o = config.headerList[s[0]];
                                        if (s[0] == i) {
                                            o.count = s[1];
                                            o.count++;
                                            s[1] = o.count % 2;
                                        }
                                    }
                                } else {
                                    // add column to sort list array
                                    config.sortList.push([i, this.order]);
                                }
                            };
                            setTimeout(function () {
                                // set css for headers
                                setHeadersCss($this[0], $headers, config.sortList, sortCSS);
                                appendToTable(
	                                $this[0], multisort(
	                                $this[0], config.sortList, cache)
								);
                            }, 1);
                            // stop normal event by returning false
                            return false;
                        }
                        // cancel selection
                    }).mousedown(function () {
                        if (config.cancelSelection) {
                            this.onselectstart = function () {
                                return false
                            };
                            return false;
                        }
                    });
                    // apply easy methods that trigger binded events
                    $this.bind("update", function () {
                        var me = this;
                        setTimeout(function () {
                            // rebuild parsers.
                            me.config.parsers = buildParserCache(
                            me, $headers);
                            // rebuild the cache map
                            cache = buildCache(me);
                        }, 1);
                    }).bind("updateCell", function (e, cell) {
                        var config = this.config;
                        // get position from the dom.
                        var pos = [(cell.parentNode.rowIndex - 1), cell.cellIndex];
                        // update cache
                        cache.normalized[pos[0]][pos[1]] = config.parsers[pos[1]].format(
                        getElementText(config, cell), cell);
                    }).bind("sorton", function (e, list) {
                        $(this).trigger("sortStart");
                        config.sortList = list;
                        // update and store the sortlist
                        var sortList = config.sortList;
                        // update header count index
                        updateHeaderSortCount(this, sortList);
                        // set css for headers
                        setHeadersCss(this, $headers, sortList, sortCSS);
                        // sort the table and append it to the dom
                        appendToTable(this, multisort(this, sortList, cache));
                    }).bind("appendCache", function () {
                        appendToTable(this, cache);
                    }).bind("applyWidgetId", function (e, id) {
                        getWidgetById(id).format(this);
                    }).bind("applyWidgets", function () {
                        // apply widgets
                        applyWidget(this);
                    });
                    if ($.metadata && ($(this).metadata() && $(this).metadata().sortlist)) {
                        config.sortList = $(this).metadata().sortlist;
                    }
                    // if user has supplied a sort list to constructor.
                    if (config.sortList.length > 0) {
                        $this.trigger("sorton", [config.sortList]);
                    }
                    // apply widgets
                    applyWidget(this);
                });
            };
            this.addParser = function (parser) {
                var l = parsers.length,
                    a = true;
                for (var i = 0; i < l; i++) {
                    if (parsers[i].id.toLowerCase() == parser.id.toLowerCase()) {
                        a = false;
                    }
                }
                if (a) {
                    parsers.push(parser);
                };
            };
            this.addWidget = function (widget) {
                widgets.push(widget);
            };
            this.formatFloat = function (s) {
                var i = parseFloat(s);
                return (isNaN(i)) ? 0 : i;
            };
            this.formatInt = function (s) {
                var i = parseInt(s);
                return (isNaN(i)) ? 0 : i;
            };
            this.isDigit = function (s, config) {
                // replace all an wanted chars and match.
                return /^[-+]?\d*$/.test($.trim(s.replace(/[,.']/g, '')));
            };
            this.clearTableBody = function (table) {
                if ($.browser.msie) {
                    function empty() {
                        while (this.firstChild)
                        this.removeChild(this.firstChild);
                    }
                    empty.apply(table.tBodies[0]);
                } else {
                    table.tBodies[0].innerHTML = "";
                }
            };
        }
    });

    // extend plugin scope
    $.fn.extend({
        tablesorter: $.tablesorter.construct
    });

    // make shortcut
    var ts = $.tablesorter;

    // add default parsers
    ts.addParser({
        id: "text",
        is: function (s) {
            return true;
        }, format: function (s) {
            return $.trim(s.toLocaleLowerCase());
        }, type: "text"
    });

    ts.addParser({
        id: "digit",
        is: function (s, table) {
            var c = table.config;
            return $.tablesorter.isDigit(s, c);
        }, format: function (s) {
            return $.tablesorter.formatFloat(s);
        }, type: "numeric"
    });

    ts.addParser({
        id: "currency",
        is: function (s) {
            return /^[£$€?.]/.test(s);
        }, format: function (s) {
            return $.tablesorter.formatFloat(s.replace(new RegExp(/[£$€]/g), ""));
        }, type: "numeric"
    });

    ts.addParser({
        id: "ipAddress",
        is: function (s) {
            return /^\d{2,3}[\.]\d{2,3}[\.]\d{2,3}[\.]\d{2,3}$/.test(s);
        }, format: function (s) {
            var a = s.split("."),
                r = "",
                l = a.length;
            for (var i = 0; i < l; i++) {
                var item = a[i];
                if (item.length == 2) {
                    r += "0" + item;
                } else {
                    r += item;
                }
            }
            return $.tablesorter.formatFloat(r);
        }, type: "numeric"
    });

    ts.addParser({
        id: "url",
        is: function (s) {
            return /^(https?|ftp|file):\/\/$/.test(s);
        }, format: function (s) {
            return jQuery.trim(s.replace(new RegExp(/(https?|ftp|file):\/\//), ''));
        }, type: "text"
    });

    ts.addParser({
        id: "isoDate",
        is: function (s) {
            return /^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(s);
        }, format: function (s) {
            return $.tablesorter.formatFloat((s != "") ? new Date(s.replace(
            new RegExp(/-/g), "/")).getTime() : "0");
        }, type: "numeric"
    });

    ts.addParser({
        id: "percent",
        is: function (s) {
            return /\%$/.test($.trim(s));
        }, format: function (s) {
            return $.tablesorter.formatFloat(s.replace(new RegExp(/%/g), ""));
        }, type: "numeric"
    });

    ts.addParser({
        id: "usLongDate",
        is: function (s) {
            return s.match(new RegExp(/^[A-Za-z]{3,10}\.? [0-9]{1,2}, ([0-9]{4}|'?[0-9]{2}) (([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(AM|PM)))$/));
        }, format: function (s) {
            return $.tablesorter.formatFloat(new Date(s).getTime());
        }, type: "numeric"
    });

    ts.addParser({
        id: "shortDate",
        is: function (s) {
            return /\d{1,2}[\/\-]\d{1,2}[\/\-]\d{2,4}/.test(s);
        }, format: function (s, table) {
            var c = table.config;
            s = s.replace(/\-/g, "/");
            if (c.dateFormat == "us") {
                // reformat the string in ISO format
                s = s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/, "$3/$1/$2");
            } else if (c.dateFormat == "uk") {
                // reformat the string in ISO format
                s = s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/, "$3/$2/$1");
            } else if (c.dateFormat == "dd/mm/yy" || c.dateFormat == "dd-mm-yy") {
                s = s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{2})/, "$1/$2/$3");
            }
            return $.tablesorter.formatFloat(new Date(s).getTime());
        }, type: "numeric"
    });
    ts.addParser({
        id: "time",
        is: function (s) {
            return /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/.test(s);
        }, format: function (s) {
            return $.tablesorter.formatFloat(new Date("2000/01/01 " + s).getTime());
        }, type: "numeric"
    });
    ts.addParser({
        id: "metadata",
        is: function (s) {
            return false;
        }, format: function (s, table, cell) {
            var c = table.config,
                p = (!c.parserMetadataName) ? 'sortValue' : c.parserMetadataName;
            return $(cell).metadata()[p];
        }, type: "numeric"
    });
    // add default widgets
    ts.addWidget({
        id: "zebra",
        format: function (table) {
            if (table.config.debug) {
                var time = new Date();
            }
            var $tr, row = -1,
                odd;
            // loop through the visible rows
            $("tr:visible", table.tBodies[0]).each(function (i) {
                $tr = $(this);
                // style children rows the same way the parent
                // row was styled
                if (!$tr.hasClass(table.config.cssChildRow)) row++;
                odd = (row % 2 == 0);
                $tr.removeClass(
                table.config.widgetZebra.css[odd ? 0 : 1]).addClass(
                table.config.widgetZebra.css[odd ? 1 : 0])
            });
            if (table.config.debug) {
                $.tablesorter.benchmark("Applying Zebra widget", time);
            }
        }
    });
})(jQuery);;
$(document).ready(function() {
    $('.listen').click(function () {
        var read_button = $('#readspeaker_button');
        read_button.addClass('visible');
        var playButton = $('.rsbtn_play');
        setTimeout(playButton.click(), 1000);
    });

    var pdfs = $('a[href$=".pdf"]').not('a[href^="http://"]');
    pdfs.each(function () {
        $(this).append('<a rel="nofollow" href="http://docreader.readspeaker.com/docreader/?cid=bvzls&amp;lang=sv_se&amp;url=' + window.location.hostname + $(this).attr('href') + '" onclick="window.open(this.href, ' + 'dcrwin' + '); return false;" title="Öppna detta dokument med ReadSpeaker docReader" style="text-decoration: none; margin-left: 6px; color: #3333aa; font-weight: bold;"> <img src="/\Static/\img\/icon_16px.gif" style="border-style: none; vertical-align: text-bottom; display: inline;" alt="ReadSpeaker"></a>');
    });

});
;
$(document).on('click', '.button_container button', function () {
    let buttonIsExpanded = $(this).attr('aria-expanded');
    let buttonTextShow = $(this).attr('data-show-more-text');
    let buttonTextHide = $(this).attr('data-show-less-text');

    if (buttonIsExpanded === 'false') {
        $(this).text(buttonTextHide);
        $(this).closest('.content').find('.expander_block_hidden').slideDown();

        // Focus link in hidden text if exists
        if ($(this).closest('.content').find('.expander_block_hidden a').length > 0) {
            $(this).closest('.content').find('.expander_block_hidden a').first().focus();
        }
    } else {
        $(this).text(buttonTextShow);
        $(this).closest('.content').find('.expander_block_hidden').slideUp();
    }
});
;
$(document).on('click', '.faq_block_expander', function () {
    let linkIsExpanded = $(this).attr('aria-expanded');

    if (linkIsExpanded === 'false') {
        $(this).find('.expander_icon').toggleClass('icon-plus icon-minus');
        $(this).closest('.faq_block').find('.faq_block_hidden').slideDown();
    } else {
        $(this).find('.expander_icon').toggleClass('icon-minus icon-plus');
        $(this).closest('.faq_block').find('.faq_block_hidden').slideUp();
    }
});
;
let $contactBlock = $('.contact_block');

if ($contactBlock.length >= 1) {
    let $showHideLink = $contactBlock.find('.contact_block_expander');

    $showHideLink.on('click', function (e) {
        let linkIsExpanded = $(this).attr('aria-expanded');

        if (linkIsExpanded === 'false') {
            $(this).find('.expander_icon').toggleClass('icon-plus icon-minus');
            $(this).closest('.contact_block').find('.contact_block_hidden').slideDown();
        } else {
            $(this).find('.expander_icon').toggleClass('icon-minus icon-plus');
            $(this).closest('.contact_block').find('.contact_block_hidden').slideUp();
        }
    });
}
;
let $videoBlock = $('.video-block');

if ($videoBlock.length >= 1) {
    let $videoPlayBtn = $videoBlock.find('button.button-play');

    $videoPlayBtn.on('click', function (e) {
        let videoSrc = $(this).parent().find('iframe').attr('src');
        let playVideoSrc = videoSrc + "?&autoplay=1&modestbranding=1&playsinline=1";

        $(this).parent().find('iframe').attr('src', playVideoSrc);        
        $(this).closest('.video-block_content').addClass('play');       
        e.preventDefault();
    });
};
$(function () {
  $('.js-step-number').click(function (e) {
    const id = e.target.id;
    const index = $('#' + id).attr('data-index');
    const amountOfFilters = parseInt($('input[name=activeStep]').val());

    if (index <= amountOfFilters) {
      $('.js-step-number').each(function (i, obj) {
        $(obj).removeClass('step-active');
        $(obj).removeClass('step-active-nofade');
      });

      $('.step-divider').each(function (i, obj) {
        $(obj).removeClass('divider-active');
        $(obj).removeClass('divider-active-nofade');
      });

      $('.step-container').each(function (i, obj) {
        $(obj).addClass('hide-step');
      });

      $('#step-' + index).removeClass('hide-step');

      const $filterInput = $('#step-filters');
      $filterInput.val('');

      switch (index) {
        case '1':
          $('.js-chosen-filters').each(function (i, obj) {
            $(obj).addClass('chosen-filters-hide');
          });
          $('#i1step1').addClass('step-active');
          $('#i1divider1').addClass('divider-active');
          $('input[name=filter1Val]').val('');
          $('input[name=filter2Val]').val('');
          $('input[name=filter3Val]').val('');
          $('input[name=activeStep]').val(1);
          break;
        case '2':
          $('#i1step1').addClass('step-active-nofade');
          $('#i1divider1').addClass('divider-active-nofade');

          $('#i2step1').addClass('step-active-nofade');
          $('#i2divider1').addClass('divider-active-nofade');

          $('#i2step2').addClass('step-active');
          $('#i2divider2').addClass('divider-active');
          $('input[name=filter2Val]').val('');
          $('input[name=filter3Val]').val('');
          $('input[name=activeStep]').val(2);
          break;
        case '3':
          $('#i1step1').addClass('step-active');
          $('#i1divider1').addClass('divider-active');

          $('#i2step1').addClass('step-active');
          $('#i2divider1').addClass('divider-active');

          $('#i2step2').addClass('step-active');
          $('#i2divider2').addClass('divider-active');

          $('#i3step1').addClass('step-active');
          $('#i3divider1').addClass('divider-active');

          $('#i3step2').addClass('step-active');
          $('#i3divider2').addClass('divider-active');

          $('#i3step3').addClass('step-active');
          $('#i3divider3').addClass('divider-active');
          $('input[name=activeStep]').val(3);
          $('input[name=filter3Val]').val('');
          break;
        default:
          break;
      }
    }
    $('#receptiontable').html('');
    AppendFilters();
  });

  $('.js-step-number').keydown(function (e) {
    if (e.keyCode === 13) {
      const id = e.target.id;
      const index = $('#' + id).attr('data-index');
      const amountOfFilters = parseInt($('input[name=activeStep]').val());

      if (index <= amountOfFilters) {
        $('.js-step-number').each(function (i, obj) {
          $(obj).removeClass('step-active');
          $(obj).removeClass('step-active-nofade');
        });

        $('.step-divider').each(function (i, obj) {
          $(obj).removeClass('divider-active');
          $(obj).removeClass('divider-active-nofade');
        });

        $('.step-container').each(function (i, obj) {
          $(obj).addClass('hide-step');
        });

        $('#step-' + index).removeClass('hide-step');

        const $filterInput = $('#step-filters');
        $filterInput.val('');

        switch (index) {
          case '1':
            $('#i1step1').addClass('step-active');
            $('#i1divider1').addClass('divider-active');
            $('input[name=filter1Val]').val('');
            $('input[name=filter2Val]').val('');
            $('input[name=filter3Val]').val('');
            $('input[name=activeStep]').val(1);
            break;
          case '2':
            $('#i1step1').addClass('step-active-nofade');
            $('#i1divider1').addClass('divider-active-nofade');

            $('#i2step1').addClass('step-active-nofade');
            $('#i2divider1').addClass('divider-active-nofade');

            $('#i2step2').addClass('step-active');
            $('#i2divider2').addClass('divider-active');
            $('input[name=filter2Val]').val('');
            $('input[name=filter3Val]').val('');
            $('input[name=activeStep]').val(2);
            break;
          case '3':
            $('#i1step1').addClass('step-active');
            $('#i1divider1').addClass('divider-active');

            $('#i2step1').addClass('step-active');
            $('#i2divider1').addClass('divider-active');

            $('#i2step2').addClass('step-active');
            $('#i2divider2').addClass('divider-active');

            $('#i3step1').addClass('step-active');
            $('#i3divider1').addClass('divider-active');

            $('#i3step2').addClass('step-active');
            $('#i3divider2').addClass('divider-active');

            $('#i3step3').addClass('step-active');
            $('#i3divider3').addClass('divider-active');
            $('input[name=activeStep]').val(3);
            $('input[name=filter3Val]').val('');
            break;
          default:
            break;
        }
      }
      $('#receptiontable').html('');
      AppendFilters();
    }
  });

  $('.js-step-sort-btn-option').click(function (e) {
    HandleClickFilterOption(e);
  });

  function HandleClickFilterOption(e, callback) {
    const id = e.target.id;
    const key = $('#' + id).attr('data-key');
    const value = $('#' + id).attr('data-value');
    const index = $('#' + id).attr('data-index');

    let newIndex = parseInt(index);
    newIndex++;

    $('.js-step-number').each(function (i, obj) {
      $(obj).removeClass('step-active');
    });
    $('.step-container').each(function (i, obj) {
      $(obj).addClass('hide-step');
    });

    $('#step-' + newIndex).removeClass('hide-step');

    setTimeout(function () {
      showStep(newIndex, key, value);
      AppendFilters();
    }, 0);
    $('.js-chosen-filters').each(function (i, obj) {
      $(obj).removeClass('chosen-filters-hide');
    });
  }

  function showStep(newIndex, key, value) {
    switch (newIndex) {
      case 2:
        $('#i2step1').addClass('step-active-nofade');
        $('#i2divider1').addClass('divider-active-nofade');

        $('#i2step2').addClass('step-active');
        $('#i2divider2').addClass('divider-active');

        $('input[name=filter1]').val(key);
        $('input[name=filter1Val]').val(value);
        $('input[name=activeStep]').val(1);
        break;
      case 3:
        $('#i3step1').addClass('step-active-nofade');
        $('#i3divider1').addClass('divider-active-nofade');

        $('#i3step2').addClass('step-active-nofade');
        $('#i3divider2').addClass('divider-active-nofade');

        $('#i3step3').addClass('step-active');
        $('#i3divider3').addClass('divider-active');

        $('input[name=filter2]').val(key);
        $('input[name=filter2Val]').val(value);
        $('input[name=activeStep]').val(2);
        break;
      case 4:
        $('input[name=activeStep]').val(3);
        $('input[name=filter3Val]').val(value);
        $('input[name=filter3]').val(key);

        const $filter1 = $('input[name=filter1]').val().split('-')[0];
        const $filter2 = $('input[name=filter2]').val().split('-')[0];
        const $filter3 = $('input[name=filter3]').val().split('-')[0];

        GetReceptions($filter1, $filter2, $filter3);

        $('#last1').addClass('step-active');

        $('#last2').addClass('step-active');

        $('#last3').addClass('step-active');

        $('#i4step2').addClass('divider-active');
        $('#i4step3').addClass('divider-active');

        $('#step-last').removeClass('hide-step');

        break;
      default:
        break;
    }
  }

  function AppendFilters() {
    const hideFilters = $('.js-chosen-filters').hasClass('chosen-filters-hide');
    if (hideFilters) {
      $('.js-chosen-filters').html('');
    } else {
      $('.js-chosen-filters').html('<p style="font-weight: bold; margin: 0 !important">Valda filter:</p>');
      for (i = 1; i <= 3; i++) {
        var value = $('input[name=filter' + i + 'Val]').val();
        $('.js-chosen-filters').append('<p class="step-filter-text">' + value + '</p>');
      }
    }
  }

  function GetReceptions(filter1, filter2, filter3) {
    $('#no-result-text').addClass('no-result-text-hide');
    $('#loadingSpinner').show();
    const urlWithParameters = 'HHReceptionStepByStep/GetReceptions?filter1=' + filter1 + '&filter2=' + filter2 + '&filter3=' + filter3;
    $.ajax({
      url: urlWithParameters,
      type: 'GET',

      success: function (result) {
        if (result) {
          $('#receptiontable').html('');

          if (result.length > 0) {
            for (i = 0; i < result.length; i++) {
              var address = result[i].ReceptionAddress
                ? "<div class='receptionList-meta-item'><img class='documentList-icon' src='/Static/img/slso-map-marker-green.svg' /> <a target='_blank' href='" +
                  result[i].ReceptionGoogleMapsLink +
                  "'>" +
                  result[i].ReceptionAddress +
                  '</a></div>'
                : '';
              var phone = result[i].PhoneNumberNewPatients
                ? "<div class='receptionList-meta-item'><img class='documentList-icon' src='/Static/img/slso-phone-green.svg' /> <a href='tel:" +
                  result[i].PhoneNumberNewPatients +
                  "'>" +
                  result[i].PhoneNumberNewPatients +
                  '</a></div>'
                : '';
              var openingHours = result[i].ReceptionOpeningHours
                ? "<div class='receptionList-meta-item'><img class='documentList-icon' src='/Static/img/slso-clock-green.svg' /> <p>" +
                  result[i].ReceptionOpeningHours +
                  '</p></div>'
                : '';
              var bookAppointment = result[i].BookAppointmentUrl
                ? "<div class='receptionList-meta-item'><img class='documentList-icon' src='/Static/img/slso-calendar-green.svg' /> <a target='_blank' href=" +
                  result[i].BookAppointmenUrl +
                  '>Boka tid</a></div>'
                : '';

              $('#receptiontable').append(
                "<div style='margin-bottom: 20px;'><div style='flex-wrap: wrap;' class='receptionList-color-light  filter-result-block-header'>" +
                  "<a class='filterList-heading' href='" +
                  result[i].PageLink +
                  "'><h3>" +
                  result[i].Heading +
                  '</h3></a>' +
                  "<a class='filter-desktop' href='" +
                  result[i].PageLink +
                  "'>Läs mer</a>" +
                  '</div>' +
                  "<div class='receptionList-meta'>" +
                  address +
                  phone +
                  openingHours +
                  bookAppointment +
                  '</div>' +
                  "<div class='filter-mobile  filter-result-block-body'>" +
                  // ' <p>' +
                  // result[i].TeaserText +
                  // '</p>' +
                  "<a class='read-more-receptionList filter-body-link' href='" +
                  result[i].PageLink +
                  "'>Läs mer</a>" +
                  ' </div>' +
                  "<div class='filter-desktop'>" +
                  "<a class='read-more-receptionList filter-mobile filter-body-link' href='" +
                  result[i].PageLink +
                  "'>Läs mer</a>" +
                  '</div></div>'
              );

              $('#receptiontable').slideDown(500, function () {
                $(this).css('display", "block');
              });

              $('#loadingSpinner').hide();
            }
          } else {
            $('#loadingSpinner').hide();
            $('#no-result-text').removeClass('no-result-text-hide');
          }
        }
      },
    });
  }

  $('.js-sort-btn-item-single').click(function (e) {
    HandleClickFilterOption(e);
  });

  $('.js-sort-btn-item-single').keydown(function (e) {
    if (e.keyCode === 13) {
      HandleClickFilterOption(e);
    }
  });
  $('.js-sort-btn-single').click(function (e) {
    HandleClickFilterOption(e);
  });
  $('.js-sort-btn-single').keydown(function (e) {
    if (e.keyCode === 13) {
      HandleClickFilterOption(e);
    }
  });
});
;
// Button hide/show based on ID in aria-controls
$(document).on('click', 'button[aria-controls]', function (e) {
    e.preventDefault();
    let ariaControlsId = $(this).attr('aria-controls');
    let ariaExpanded = $(this).attr('aria-expanded');

    if (ariaExpanded === 'false') {
        $(this).attr('aria-expanded', 'true');
        $(this).parent().siblings('#' + ariaControlsId).attr('aria-hidden', 'false');

    } else {
        $(this).attr('aria-expanded', 'false');
        $(this).parent().siblings('#' + ariaControlsId).attr('aria-hidden', 'true');
    }
});
;
// On page anchor menu for Standard and Campaign Info Page
let $standardPage = $('.standardpage, .buparticle');
let $campaignInfoPage = $('.campaigninfopage');

// Campaign Info Page
if ($campaignInfoPage.length >= 1) {
    let $campaignAsideContent = $campaignInfoPage.find('aside');
    let campaignAsideContentPxLeft = 0;
    if ($campaignAsideContent.length >= 1) {
        campaignAsideContentPxLeft = $campaignAsideContent.offset().left;
    }
    let $campaignAnchorMenu = $campaignInfoPage.find('.anchor_menu');
    let $campaignAsideAnchorMenuContainer = $campaignInfoPage.find('.aside_anchor_menu_container');

    $campaignAsideAnchorMenuContainer.width($campaignAsideContent.width());

    if ($campaignAnchorMenu.length >= 1) {
        let asideAnchorMenuTop = $campaignAsideAnchorMenuContainer.offset().top;

        $(window).scroll(function () {
            fixAsideAnchorMenu(asideAnchorMenuTop, $campaignAsideAnchorMenuContainer, campaignAsideContentPxLeft, $campaignAsideContent);

            showCurrent($campaignAnchorMenu);
        });
    }
}

// Standard Page
if ($standardPage.length >= 1) {
    let $mainContent = $standardPage.find('.main_content');
    let $asideContent = $standardPage.find('.aside_content');
    let asideContentPxLeft = 0;
    if ($asideContent.length >= 1) {
        asideContentPxLeft = $asideContent.offset().left;
    }
    let $topAnchorMenu = $mainContent.find('.anchor_menu');
    let $anchorMenus = $standardPage.find('.anchor_menu');
    let $asideAnchorMenuContainer = $standardPage.find('.aside_anchor_menu_container');
    let $asideAnchorMenu = $asideAnchorMenuContainer.find('.anchor_menu');
    let $contentUl = $anchorMenus.find('ul');
    let idH2Count = 1;
    let labeledByCount = 1;

    $asideAnchorMenuContainer.width($asideContent.width());

    // Unique ID on heading for aria-labelledby
    $anchorMenus.each(function (e) {
        let currentH2Id = $(this).find('h2').attr('id');

        $(this).attr('aria-labelledby', currentH2Id + labeledByCount);
        $(this).find('h2').attr('id', currentH2Id + labeledByCount);
        labeledByCount++;
    });

    // Add aria-hidden on aside anchor menu
    $asideAnchorMenu.attr('aria-hidden', 'true');

    // If three or more h2 exist on the page
    if ($mainContent.find('h2:not(.anchor_menu_heading)').length >= 3) {
        $topAnchorMenu.addClass('show');
        $asideAnchorMenuContainer.addClass('show');

        // Add id on h2 and generate anchor menu
        $mainContent.find('h2:not(.anchor_menu_heading)').each(function () {
            $(this).attr('id', 'h2-' + idH2Count);
            $contentUl.append("<li><a href='#h2-" + idH2Count + "'>" + $(this).text() + '</a></li>');
            //$contentUl.append("<li><a href='#h2-" + idH2Count + "' tabindex='-1'>" + $(this).text() + '</a></li>');

            idH2Count++;
        });

        if ($topAnchorMenu.length >= 1) {
            let anchorMenuBottom = $topAnchorMenu.offset().top + $topAnchorMenu.outerHeight(true);
            let asideAnchorMenuTop = $asideAnchorMenuContainer.offset().top;

            $(window).scroll(function (e) {
                showHideAsideAnchorMenu(anchorMenuBottom, $asideAnchorMenu);

                fixAsideAnchorMenu(asideAnchorMenuTop, $asideAnchorMenuContainer, asideContentPxLeft, $asideContent);

                showCurrent($asideAnchorMenuContainer);
            });
        }


    }
}

function fixAsideAnchorMenu(currAsideAnchorMenuTop, currAsideAnchorMenuContainer, currAsideContentPxLeft, currAsideContent) {
    let y = $(this).scrollTop();

    if (y >= currAsideAnchorMenuTop) {
        currAsideAnchorMenuContainer.addClass('fixed');
        currAsideAnchorMenuContainer.css('left', currAsideContentPxLeft);
    } else {
        currAsideAnchorMenuContainer.removeClass('fixed');
        currAsideAnchorMenuContainer.width(currAsideContent.width());
    }
}

function showHideAsideAnchorMenu(anchorMenuBottom, currAsideAnchorMenu) {
    let scroll = $(this).scrollTop();

    if (scroll >= anchorMenuBottom) {
        currAsideAnchorMenu.show();
        currAsideAnchorMenu.removeClass('visually_hidden_aside');
    }
    else if (scroll <= anchorMenuBottom) {
        currAsideAnchorMenu.addClass('visually_hidden_aside');
        setTimeout(function () {
            currAsideAnchorMenu.hide();
        }, 300);
    }
}

function showCurrent(currentAsideAnchorMenu) {
    let menuItems = currentAsideAnchorMenu.find('a');
    let scrollItems = menuItems.map(function () {
        let item = $($(this).attr('href'));
        if (item.length) { return item; }
    });
    let scroll = $(this).scrollTop() + 50;

    // Get id of current scroll item
    let current = scrollItems.map(function () {
        if ($(this).offset().top < scroll)
            return this;
    });

    // Get the id of the current element
    current = current[current.length - 1];
    let id = current && current.length ? current[0].id : "";

    // Set/remove current class
    menuItems
        .parent().removeClass('current')
        .end().filter("[href='#" + id + "']").parent().addClass('current');
}

$(document).ready(function () {
    if ($('.anchor_menu').length > 0 && $('.sub_nav_heading').length > 0) {
        var subMenuHeading = $('.sub_nav_heading').text();
        var createHeading = $("<p class='anchor_menu_heading_legible'></p>").text(subMenuHeading);
        $('.anchor_menu').prepend(createHeading);
    }
});
;
if ($('.EPiServerForms').length > 0) {

    // Add class to form if several or one steps
    $('.EPiServerForms').each(function () {
        if ($(this).find('[data-f-type="step"]').length > 1) {
            $(this).addClass('formMultiSteps');
        }
        else {
            $(this).addClass('formOneStep');
        }
    });
  
    // Keyboard enter
    $('.EPiServerForms input, .EPiServerForms select, .EPiServerForms label').keypress(function (e) {
        var key = e.which;
        if (key == 13) {
            e.preventDefault();

            // If File Upload Input
            if ($(this).hasClass('FormFileUpload__Input')) {
                $(this).click();
            }
            // else If radio
            else if ($(this).hasClass('FormChoice__Input--Radio')) {
                $(this).parent().find('input[type="radio"]').click();
            }
            // else If checkbox
            else if ($(this).hasClass('FormChoice__Input--Checkbox')) {
                $(this).parent().find('input[type="checkbox"]').click();
            }
        }
    });

    // Adds current value under form range
    $(".FormRange").each(function (index) {
        var thisFormRange = $(this);
        thisFormRange.find('span').eq(0).append('<span class="FormRange__Value"></span>');
        thisFormRange.find('input').on('input change', function () {
            var inputMax = parseInt(thisFormRange.find('.FormRange__Max').text());
            var inputVal = parseInt(thisFormRange.find('input').val());
            var inputWidth = thisFormRange.find('input').width();
            var inputSteps = inputWidth / inputMax;
            thisFormRange.find('.FormRange__Value').css('width', inputSteps);
            thisFormRange.find('.FormRange__Value').css('margin-left', -(inputSteps / 2));
            thisFormRange.find('.FormRange__Value').css('left', (inputVal * inputSteps));
            thisFormRange.find('.FormRange__Value').text(inputVal);
        }).trigger('change');
    });

    $('.FormChoice label').each(function (i, v) {
        $(v).contents().eq(2).wrap('<span class="choice"/>')
    });

    $('.FormFileUpload').each(function (i, v) {
        var thisItem = $(this);
        thisItem.find('input').wrap('<div class="wrap row"/>')
        thisItem.find('.wrap').append('<span class="FormFileUpload__Btn columns shrink">Välj fil</span>');
        thisItem.find('.wrap').append('<span class="FormFileUpload__Txt columns shrink">Ingen fil har valts</span>');

        var input = thisItem.find('input');
        var label = $(this).find('.FormFileUpload__Txt');
        var labelVal = $(this).find('.FormFileUpload__Txt').text();

        input.on('change', function (e) {
            var fileName = '';
            if (this.files && this.files.length > 1) {
                fileName = (this.getAttribute('data-multiple-caption') || '').replace('{count}', this.files.length);
            } else {
                fileName = e.target.value.split('\\').pop();
            }
            if (fileName) {
                label.text(fileName);
            } else {
                label.text(labelVal);
            }
        });
    });

    $('.Form__NavigationBar .btnNext').on("click", function (e) {
        setTimeout(function () {
            if ($('.ValidationFail').length > 0) {
                $('html,body').animate({ scrollTop: $('.EPiServerForms .ValidationFail:first').offset().top }, 900);
            }
        }, 200);
    });

    $('.EPiServerForms').on('submit', function (e) {

        let currentForm = $(this);
        let isValid = true;

        $(currentForm).find('[required]').each(function (c) {
            if ($(this).attr('type') !== 'checkbox') {
                $(this).next('span').addClass('hidden');
                if ($(this).val() === '') {
                    isValid = false;
                    $(this).next('.hidden').removeClass('hidden');
                }
                else if ($(this).attr('type') === 'number') {
                    if (isNaN($(this).val())) {
                        isValid = false;
                        $(this).next('.hidden').removeClass('hidden');
                    }
                }
            }
            else {
                $(this).parents('fieldset').next('span').addClass('hidden');
                if (!$(this).is(':checked')) {
                    isValid = false;
                    $(this).parents('fieldset').next('span').removeClass('hidden');
                }
                
            }
        });
        return isValid;

    });
}
;
$(document).ready(function () {
    let $megaMenu = $('.mega_menu');
    let $desktopMainNav = $('.desktop-menu-nav .js-nav-system');
    let $navItemWithChild = $desktopMainNav.find('li.js-nav-system__item.has_child');
    let $showThirdLevelBtn = $megaMenu.find('.js-show');
    let $allPageTriangles = $('.desktop-menu-nav .icon-triangle');
    let $currentPageTriangle = $desktopMainNav.find('li.current.js-nav-system__item .icon-triangle');
    let timer;

    // Add class depending on item count
    let $menuContent = $megaMenu.find('ul.secondLevel');
    $menuContent.each(function () {
        let totalItems = $(this).find('li').length;

        if (totalItems > 40 && totalItems < 50) {
            $(this).addClass('more-height')
        }
        else if (totalItems > 50 && totalItems < 70) {
            $(this).addClass('even-more-height')
        }
        else if (totalItems > 69) {
            $(this).addClass('max-height')
        }
    });

    // On hover with delay
    $navItemWithChild.mouseenter(function () {
        var current = $(this);
        timer = setTimeout(function () {
            showMegaMenu(current);
        }, 150);
    });

    $navItemWithChild.mouseleave(function () {
        clearTimeout(timer);
        hideMegaMenu($(this));
    });

    // On keyboard tab
    $navItemWithChild.focusin(function () {
        showMegaMenu($(this));
    });

    function showMegaMenu(current) {
        $allPageTriangles.hide();
        current.toggleClass('closed opened');
        current.find('.js-nav-system__link').attr('aria-expanded', 'true');
        current.find('.icon-triangle').css('display', 'block');
        current.find('.mega_menu').attr('aria-hidden', 'false').show();
    }

    function hideMegaMenu(current) {        
        $currentPageTriangle.show();
        current.toggleClass('opened closed');
        current.find('.js-nav-system__link').attr('aria-expanded', 'false');
        current.find('.icon-triangle').hide();
        current.find('.mega_menu').attr('aria-hidden', 'true').hide();        
    }

    // Show/hide third level on click
    $showThirdLevelBtn.on('click', function (e) {
        e.preventDefault();
        showHideLevel3($(this));
    });

    // Show/hide third level on keypress enter
    $showThirdLevelBtn.keydown(function (event) {
        if (event.keyCode == '13') {
            showHideLevel3($(this));
        }
    });

    function showHideLevel3(currentBtn) {
        let ariaExpanded = currentBtn.attr('aria-expanded');

        if (ariaExpanded == 'false') {
            currentBtn.attr('aria-expanded', 'true');
            currentBtn.closest('li').find('ul.thirdLevel').attr('aria-hidden', 'false').slideDown();
        } else {
            currentBtn.attr('aria-expanded', 'false');
            currentBtn.closest('li').find('ul.thirdLevel').attr('aria-hidden', 'true').slideUp();
        }
    }
});;
if ($('#menu-button').length > 0) {
    let $mobileMenu = $('#mobile-menu-nav');
    let $closeBtn = $mobileMenu.find('.closebtn');
    let $menuBtn = $('#menu-button');
    let $body = $('body');

    $menuBtn.on('click', function (e) {
        e.preventDefault();
        $menuBtn.attr('aria-expanded', 'true');
        $mobileMenu.css('width', 'auto').attr('aria-hidden', 'false');
        $body.addClass('mobile-menu-open');
    });

    $closeBtn.on('click', function (e) {
        e.preventDefault();
        $menuBtn.attr('aria-expanded', 'false');
        $mobileMenu.attr('aria-hidden', 'true');
        $body.removeClass('mobile-menu-open');
    });

    $(document).ready(function () {
        /* When the page loads, make sure that no list elements with subelements have class 'opened' but 'closed' instead */
        $(".main_nav ul.parent li:has('.child')").removeClass("opened").addClass("has_child closed");
        $(".main_nav ul.parent li.has_child .child li:has('child')").removeClass("opened").addClass("has_child closed");

        // Open all parent levels from current page
        $('li.current').parents('.has_child').removeClass('closed').addClass('opened');

        // Open mobile submenus on click on the plus symbol with class 'expand'
        $(".main_nav ul.parent li.has_child .expand").on("click tap", function (e) {
            toggleSubmenus(e, $(this));
        });

        // Open mobile submenus on keypress enter
        $(".main_nav ul.parent li.has_child .expand").on('keypress', function (e) {
            if (e.which == 13) {
                toggleSubmenus(e, $(this));
            }
        });

        function toggleSubmenus(e, current) {
            var moParent = current.parent(".mo");
            var has_child = moParent.siblings(".has_child");
            var thisParent = moParent.parent("li");
            let dataTextClose = current.find('.icon-plus').attr('data-text-close');
            let dataTextOpen = current.find('.icon-plus').attr('data-text-open');

            if (thisParent.hasClass("closed")) {
                thisParent.siblings(".opened").removeClass("opened").addClass("closed");
                thisParent.removeClass("closed").addClass("opened");

                current.find('.icon-plus').attr('aria-label', dataTextClose);
            } else if (thisParent.hasClass("opened")) {
                e.preventDefault();
                thisParent.removeClass("opened").addClass("closed");
                has_child.removeClass("opened").addClass("closed");

                current.find('.icon-plus').attr('aria-label', dataTextOpen);
            }
        }
    });
};
$(window).scroll(function () {
    if ($(this).scrollTop() > 400) {
        $('.scroll-to-top').fadeIn();
    } else {
        $('.scroll-to-top').fadeOut();
    }
});

$('.scroll-to-top').click(function (e) {
    e.preventDefault();
    $('html, body').animate({ scrollTop: 0 }, 800);
    $('h1').focus();
    if ($('h1').is(":focus")) {
        return false;
    } else {
        $('h1').attr('tabindex', '-1');
        $('h1').focus();
    };
    return false;
});;
$(function () {
    if ($('.care_area_selection').length > 0) {
        let currentSearchRequest = null;
        let form = $('.care_area_selection').parents('form')[0];
        let $toggleFiltersButton = $('#search-filters-button');
        let $filtersContent = $('#search-filters');

        // Toggle filters
        $toggleFiltersButton.on('click', function () {
            let ariaExpanded = $toggleFiltersButton.attr('aria-expanded');

            if (ariaExpanded === 'false') {
                $toggleFiltersButton.attr('aria-expanded', true);
                $filtersContent.attr('aria-hidden', false).slideDown();
            } else {
                $toggleFiltersButton.attr('aria-expanded', false);
                $filtersContent.attr('aria-hidden', true).slideUp();
            }
        });

        //Desktop: Add correct aria hidden attr on search result items
        $('.event_sorters .event_sorter').on('click', function () {
            $('.event_list li.event').each(function () {
                if ($(this).is(':visible')) {
                    $(this).attr('aria-hidden', 'false');
                } else {
                    $(this).attr('aria-hidden', 'true');
                }
            });
        });

        // Desktop: Clear all checked filters
        $('#search-filters .clear_all_container a').on('click', function (e) {
            e.preventDefault();
            let checkbox = $('#search-filters .checkbox_item');
            if (checkbox.hasClass('checked')) {
                checkbox.removeClass('checked');
            }

            resetForm()
        });

        // Mobile: Clear all checked filters
        $('.search_filter #option-all').on('click', function (e) {
            e.preventDefault();
            let checkbox = $('.search_filter .checkbox_item');
            if (checkbox.hasClass('checked')) {
                checkbox.removeClass('checked');
            }

            resetForm()
        });

        // Ajax post on filter click
        $('#search-filters .care_area_selection input').on('click', function (e) {
            postForm();
        });

        // Ajax post on filter click with enter key
        $('#search-filters .care_area_selection label').keypress(function (e) {
            let key = e.which;

            if (key == 13) {
                postForm();
            }
        });

        function postForm() {
            if (currentSearchRequest !== null)
                currentSearchRequest.abort();

            currentSearchRequest = $.post(form.action, $(form).serialize(), function (data) {
                $('.main_section').replaceWith(data);
            });
        }

        function resetForm() {
            $.post(form.action, function (data) {
                $('.main_section').replaceWith(data);
            });
        }


        // Accessible filter dropdown
        const SPACEBAR_KEY_CODE = [0, 32];
        const ENTER_KEY_CODE = 13;
        const DOWN_ARROW_KEY_CODE = 40;
        const UP_ARROW_KEY_CODE = 38;
        const ESCAPE_KEY_CODE = 27;

        const filterList = document.querySelector(".search_filter .dropdown__list");
        const filterListContainer = document.querySelector(".search_filter .dropdown__list-container");
        const filterDropdownArrow = document.querySelector(".search_filter .dropdown__arrow");
        const filterListItems = document.querySelectorAll(".search_filter .dropdown__list-item_button");
        const filterDropdownSelectedNode = document.querySelector(".search_filter #dropdown-filter__selected");
        const filterListItemIds = [];

        filterDropdownSelectedNode.addEventListener("click", function (e) {
            toggleListVisibilityFilter(e)
        });
        filterDropdownSelectedNode.addEventListener("keydown", function (e) {
            toggleListVisibilityFilter(e)
        });
        filterDropdownArrow.addEventListener("click", function (e) {
            toggleListVisibilityFilter(e)
        });

        filterListItems.forEach(function (item) {
            filterListItemIds.push(item.id)
        });

        filterListItems.forEach(function (item) {
            item.addEventListener("click", function (e) {
                setSelectedListItemFilter(e);
                closeListFilter();
            });

            item.addEventListener("keydown", function (e) {
                switch (e.keyCode) {
                    case ENTER_KEY_CODE:
                        setSelectedListItemFilter(e);
                        closeListFilter();
                        return;

                    case DOWN_ARROW_KEY_CODE:
                        focusNextListItemFilter(DOWN_ARROW_KEY_CODE);
                        return;

                    case UP_ARROW_KEY_CODE:
                        focusNextListItemFilter(UP_ARROW_KEY_CODE);
                        return;

                    case ESCAPE_KEY_CODE:
                        closeListFilter();
                        return;

                    default:
                        return;
                }
            });
        });

        function setSelectedListItemFilter(e) {
            let selectedTextToAppend = document.createTextNode(e.target.innerText);
            filterDropdownSelectedNode.innerHTML = null;
            filterDropdownSelectedNode.appendChild(selectedTextToAppend);
        }

        function closeListFilter() {
            filterList.classList.remove("open");
            filterDropdownArrow.classList.remove("expanded");
            filterListContainer.setAttribute("aria-expanded", false);
        }

        function toggleListVisibilityFilter(e) {
            let openDropDown =
                SPACEBAR_KEY_CODE.includes(e.keyCode) || e.keyCode === ENTER_KEY_CODE;

            if (e.keyCode === ESCAPE_KEY_CODE) {
                closeList();
            }

            if (e.type === "click" || openDropDown) {
                filterList.classList.toggle("open");
                filterDropdownArrow.classList.toggle("expanded");
                filterListContainer.setAttribute(
                    "aria-expanded",
                    filterList.classList.contains("open")
                );
            }

            if (e.keyCode === DOWN_ARROW_KEY_CODE) {
                focusNextListItemFilter(DOWN_ARROW_KEY_CODE);
            }

            if (e.keyCode === UP_ARROW_KEY_CODE) {
                focusNextListItemFilter(UP_ARROW_KEY_CODE);
            }
        }

        function focusNextListItemFilter(direction) {
            const activeElementId = document.activeElement.id;
            if (activeElementId === "dropdown__selected") {
                document.querySelector("#" + filterListItemIds[0]).focus();
            } else {
                const currentActiveElementIndex = filterListItemIds.indexOf(
                    activeElementId
                );
                if (direction === DOWN_ARROW_KEY_CODE) {
                    const currentActiveElementIsNotLastItem =
                        currentActiveElementIndex < filterListItemIds.length - 1;
                    if (currentActiveElementIsNotLastItem) {
                        const nextListItemId = filterListItemIds[currentActiveElementIndex + 1];
                        document.querySelector("#" + nextListItemId).focus();
                    }
                } else if (direction === UP_ARROW_KEY_CODE) {
                    const currentActiveElementIsNotFirstItem =
                        currentActiveElementIndex > 0;
                    if (currentActiveElementIsNotFirstItem) {
                        const nextListItemId = filterListItemIds[currentActiveElementIndex - 1];
                        document.querySelector("#" + nextListItemId).focus();
                    }
                }
            }
        }
    }
});;
$(function () {
    if ($('.filter-function').length > 0) {
        let currentSearchRequest = null;
        let form = $('.filter-function').parents('form')[0];
        const filterButtonContainer = document.querySelector('.filter-function_checkbox_container');

        if (window.location.search.indexOf('selectedCategory') > -1) {
            let queryParts = window.location.search.split('&');
            let selectedCategories = [];
            queryParts.forEach(function (item) {
                item = item.replace('?', '');
                if (item.startsWith('selectedCategory')) selectedCategories.push(item.split('=')[1]);
            });

            selectedCategories.forEach(function (id) {
                let input = $('.dropdown__list .dropdown__list-item input[value="' + id + '"]');

                input.prop('checked', true);

                let selectedName = input.data('categoryname');
                let newButton = filterButtonContainer.firstElementChild.cloneNode(true);
                newButton.setAttribute('data-categoryName', selectedName);
                $(newButton).show();
                let newText = newButton.querySelector('.text');
                newText.innerText = selectedName;
                filterButtonContainer.appendChild(newButton);
            });
        }

        $('.dropdown__list .dropdown__list-item input').on('click', function (e) {
            let selectedName = $(e.target).data('categoryname');

            if (e.target.checked) {
                let newButton = filterButtonContainer.firstElementChild.cloneNode(true);
                newButton.setAttribute('data-categoryName', selectedName);
                $(newButton).show();
                let newText = newButton.querySelector('.text');
                newText.innerText = selectedName;
                filterButtonContainer.appendChild(newButton);
            } else {
                let elementToRemove = $(filterButtonContainer).find('[data-categoryName="' + selectedName + '"]');

                if (elementToRemove !== null) {
                    elementToRemove.remove();
                }
            }
            updateURL();
            postForm();
        });

        $('.filter-function_checkbox_container').on('click', '.checkbox_item', function (e) {
            let clickedItem = e.currentTarget;
            let categoryName = $(clickedItem).data('categoryname');

            $('.dropdown__list .dropdown__list-item input[data-categoryName="' + categoryName + '"]').removeProp('checked');

            e.currentTarget.remove();
            updateURL();
            postForm();
        });

        // Ajax post on filter click with enter key
        $('.dropdown__list .dropdown__list-item label').keypress(function (e) {
            let key = e.which;

            if (key == 13) {
                postForm();
            }
        });

        function postForm() {
            if (currentSearchRequest !== null) currentSearchRequest.abort();

            currentSearchRequest = $.post(form.action, $(form).serialize(), function (data) {
                $('.main_section').replaceWith(data);
            });
        }

        function updateURL() {
            var searchParts = window.location.search.split('&');
            var nonCategoryParts = [];
            searchParts.forEach(function (item) {
                item = item.replace('?', '');
                if (item.indexOf('selectedCategory') < 0) {
                    nonCategoryParts.push(item);
                }
            });
            var serializedCategories = $('[name="selectedCategory"]').serialize();

            var searchString = window.location.pathname;
            searchString += '?';
            if (nonCategoryParts.length > 0) {
                searchString += nonCategoryParts.join('&');
            }

            if (nonCategoryParts.length > 0 && serializedCategories.length > 0) searchString += '&';

            searchString += serializedCategories;

            window.history.pushState('', '', searchString);
        }

        //// Accessible filter dropdown
        const SPACEBAR_KEY_CODE = [0, 32];
        const ENTER_KEY_CODE = 13;
        const DOWN_ARROW_KEY_CODE = 40;
        const UP_ARROW_KEY_CODE = 38;
        const ESCAPE_KEY_CODE = 27;

        const filterList = document.querySelector('.filter-function .dropdown__list');
        const filterListContainer = document.querySelector('.filter-function .dropdown__list-container');
        const filterDropdownArrow = document.querySelector('.filter-function .dropdown__arrow');
        const filterListItems = document.querySelectorAll('.filter-function .dropdown__list-item_button');
        const filterDropdownSelectedNode = document.querySelector('.filter-function #filter-function-dropdown__selected');
        const filterListItemIds = [];

        // Close on click outside
        document.addEventListener(
            'click',
            function(e) {
                if (e.target.closest('ul.dropdown')) return;
                closeListFilter(e);
            },
            false
        );

        filterDropdownSelectedNode.addEventListener('click', function (e) {
            toggleListVisibilityFilter(e);
        });
        filterDropdownSelectedNode.addEventListener('keydown', function (e) {
            toggleListVisibilityFilter(e);
        });
        filterDropdownArrow.addEventListener('click', function (e) {
            toggleListVisibilityFilter(e);
        });

        filterListItems.forEach(function (item) {
            filterListItemIds.push(item.id);
        });

        filterListItems.forEach(function (item) {
            item.addEventListener('click', function (e) {
                setSelectedListItemFilter(e);
                closeListFilter();
            });

            item.addEventListener('keydown', function (e) {
                switch (e.keyCode) {
                    case ENTER_KEY_CODE:
                        setSelectedListItemFilter(e);
                        closeListFilter();
                        return;

                    case DOWN_ARROW_KEY_CODE:
                        focusNextListItemFilter(DOWN_ARROW_KEY_CODE);
                        return;

                    case UP_ARROW_KEY_CODE:
                        focusNextListItemFilter(UP_ARROW_KEY_CODE);
                        return;

                    case ESCAPE_KEY_CODE:
                        closeListFilter();
                        return;

                    default:
                        return;
                }
            });
        });

        function setSelectedListItemFilter(e) {
            let selectedTextToAppend = document.createTextNode(e.target.innerText);
            filterDropdownSelectedNode.innerHTML = null;
            filterDropdownSelectedNode.appendChild(selectedTextToAppend);
        }

        function closeListFilter() {
            filterList.classList.remove('open');
            filterDropdownArrow.classList.remove('expanded');
            filterListContainer.setAttribute('aria-expanded', false);
        }

        function toggleListVisibilityFilter(e) {
            let openDropDown = SPACEBAR_KEY_CODE.includes(e.keyCode) || e.keyCode === ENTER_KEY_CODE;

            if (e.keyCode === ESCAPE_KEY_CODE) {
                closeList();
            }

            if (e.type === 'click' || openDropDown) {
                filterList.classList.toggle('open');
                filterDropdownArrow.classList.toggle('expanded');
                filterListContainer.setAttribute('aria-expanded', filterList.classList.contains('open'));
            }

            if (e.keyCode === DOWN_ARROW_KEY_CODE) {
                focusNextListItemFilter(DOWN_ARROW_KEY_CODE);
            }

            if (e.keyCode === UP_ARROW_KEY_CODE) {
                focusNextListItemFilter(UP_ARROW_KEY_CODE);
            }
        }

        function focusNextListItemFilter(direction) {
            const activeElementId = document.activeElement.id;
            if (activeElementId === 'filter-function-dropdown__selected') {
                document.querySelector('#' + filterListItemIds[0]).focus();
            } else {
                const currentActiveElementIndex = filterListItemIds.indexOf(activeElementId);
                if (direction === DOWN_ARROW_KEY_CODE) {
                    const currentActiveElementIsNotLastItem = currentActiveElementIndex < filterListItemIds.length - 1;
                    if (currentActiveElementIsNotLastItem) {
                        const nextListItemId = filterListItemIds[currentActiveElementIndex + 1];
                        document.querySelector('#' + nextListItemId).focus();
                    }
                } else if (direction === UP_ARROW_KEY_CODE) {
                    const currentActiveElementIsNotFirstItem = currentActiveElementIndex > 0;
                    if (currentActiveElementIsNotFirstItem) {
                        const nextListItemId = filterListItemIds[currentActiveElementIndex - 1];
                        document.querySelector('#' + nextListItemId).focus();
                    }
                }
            }
        }
    }

  

});
;
$(function () {
  function closeAllFilterDropdowns() {
    $filterOptions = $('.js-filter-btn');
    var mq = window.matchMedia('(min-width: 1025px)');
    if (mq.matches) {
      $filterOptions.each(function (i, obj) {
        $(obj).attr('aria-pressed', 'false');
        var $btnContent = $('#content-' + obj.id);
        $('.js-filter-content').removeClass('filter-btn-content-show');
        $btnContent.removeClass('filter-btn-content-show');
      });
    }
  }

  function toggleDropdown(target) {
    var $target = $('#' + target.id);

    var $ariaPressed = $target.attr('aria-pressed');
    var $newAriaPressed = $ariaPressed === 'true' ? 'false' : 'true';
    $target.attr('aria-pressed', $newAriaPressed);
    var $btnContent = $('#content-' + target.id);

    var mq = window.matchMedia('(min-width: 1025px)');

    if (mq.matches) {
      $('.js-filter-content').removeClass('filter-btn-content-show');

      $('.js-filter-btn').each(function (i, obj) {
        if (obj.id !== target.id) {
          $(obj).attr('aria-pressed', 'false');
        } else {
          $(obj).attr('aria-pressed', $newAriaPressed);
        }
      });
    }

    $newAriaPressed === 'true' ? $btnContent.addClass('filter-btn-content-show') : $btnContent.removeClass('filter-btn-content-show');
  }

  $('.filter-btn-item').on('click', '*', function (e) {
    e.stopPropagation();

    if (!$(e.target).hasClass('filter-btn-option') && !$(e.target).hasClass('dont-close')) {
      e.target.type != null ? toggleDropdown(e.target) : toggleDropdown(e.target.parentElement);
    }
  });

  $('.filter-btn-filterCount').on('click', function (e) {
    e.stopPropagation();

    toggleDropdown(e.target.parentElement.parentElement);
  });

  function getFilterCategoryFromFilterName(target) {
    var filterName = target.getAttribute('data-filterName');
    if (filterName) return filterName.split('|')[0];
    return '';
  }

  function setActiveOptions(target, id, setAriaChecked) {
    //Checkbox icon
    var $targetSpan = $('#' + id).find('span');
    if (setAriaChecked === 'true') {
      $targetSpan.addClass('filter-btn-option-checkmark-show');
      $(target).addClass('filter-btn-option-active');
    } else {
      $targetSpan.removeClass('filter-btn-option-checkmark-show');
      $(target).removeClass('filter-btn-option-active');
    }

    //Input
    //Checkbox icon
    var $targetInput = $('#' + id).find('input');
    $targetInput.attr('aria-checked', setAriaChecked);
  }
  function clearCounterFilterOptions() {
    $('.js-filter-btn').each(function (i, obj) {
      //Clear all options
      var objChildren = $(obj).children('div');
      $(objChildren).children('p').text('');
      $(objChildren).children('p').removeClass('show');

      //Clear all filter id's to query string
      var filterName = obj.getAttribute('data-filterName').split('|')[0];
      var $inputQuery = $('input[name=' + filterName + ']');
      $inputQuery.val('');
    });
  }
  function clearCounterFilterOptionsSpecific(category) {
    $('.js-filter-btn').each(function (i, obj) {
      var objId = $(obj).attr('data-filtername').split('|')[0];

      if (category === objId) {
        //Clear all options
        var objChildren = $(obj).children('div');
        $(objChildren).children('p').text('');
        $(objChildren).children('p').removeClass('show');

        //Clear all filter id's to query string
        var filterName = obj.getAttribute('data-filterName').split('|')[0];
        var $inputQuery = $('input[name=' + filterName + ']');
        $inputQuery.val('');
      }
    });
  }

  function setCounterFilteredOptions(target) {
    //Option counter
    $('.js-filter-btn').each(function (i, obj) {
      var j = 0;
      var optionsChecked = 0;
      var filterName = obj.getAttribute('data-filterName').split('|')[0];
      var listOfFiltered = [];

      //Iterate each option of look for a matching filterName in dropdown parent and dropdown item
      $('.js-filter-btn-option :input').each(function (ix, optObj) {
        if ($(optObj.parentElement).attr('data-filterName')) {
          $parentFilterName = $(optObj.parentElement).attr('data-filterName').split('|')[0];

          if (filterName === $parentFilterName) {
            $checked = $(optObj).attr('aria-checked');

            if ($checked === 'true') {
              listOfFiltered.push(optObj);
              optionsChecked++;
            }
          }
        }
      });

      if (filterName === getFilterCategoryFromFilterName(target)) {
        var objChildren = $(obj).children('div');

        if (optionsChecked > 0) {
          $(objChildren).children('p').text(optionsChecked);
          $(objChildren).children('p').addClass('show');
        } else {
          $(objChildren).children('p').text('');
          $(objChildren).children('p').removeClass('show');
        }

        var mq = window.matchMedia('(max-width: 1025px)');
        if (mq.matches) {
          addFiltersToQuery(false);
        }
      }
    });
  }

  function addFiltersToQuery(submitForm) {
    //Option counter
    $('.js-filter-btn').each(function (i, obj) {
      var j = 0;
      var optionsChecked = 0;
      var filterName = obj.getAttribute('data-filterName').split('|')[0];
      var listOfFiltered = [];

      //Iterate each option of look for a matching filterName in dropdown parent and dropdown item
      $('.js-filter-btn-option :input').each(function (ix, optObj) {
        if ($(optObj.parentElement).attr('data-filterName')) {
          $parentFilterName = $(optObj.parentElement).attr('data-filterName').split('|')[0];

          if (filterName === $parentFilterName) {
            $checked = $(optObj).attr('aria-checked');

            if ($checked === 'true') {
              listOfFiltered.push(optObj);
              optionsChecked++;
            }
          }
        }
      });

      //Add filter id's to query string
      var $inputQuery = $('input[name=' + filterName + ']');
      var queryString = '';
      for (var i = 0; i < listOfFiltered.length; i++) {
        if (i === listOfFiltered.length - 1) {
          queryString += listOfFiltered[i].parentElement.id;
        } else {
          queryString += listOfFiltered[i].parentElement.id + ', ';
        }
      }
      $inputQuery.val(queryString);
    });
    if (submitForm) submitSearchForm();
  }

  $('.js-filter-btn-option').click(function (e) {
    handleOnClickFilterOption(e.target);
  });

  $('.js-filter-btn-option').keydown(function (e) {
    if (e.keyCode === 13 || e.keyCode === 32) {
      handleOnClickFilterOption(e.target.parentElement);
    }
  });

  function closeSpecificTab(e) {
    var catToClear = $(e.target.parentElement).attr('id').replace('-filterbtns', '');
    clearCounterFilterOptionsSpecific(catToClear);

    $('.js-filter-btn-option').each(function (i, obj) {
      var cat = $(obj).attr('data-filtername').split('|')[0];
      if (cat === catToClear) {
        $(obj).removeClass('filter-btn-option-active');
        $(obj).children('input').attr('aria-checked', 'false');
        $(obj).children('input').attr('checked', false);
        $(obj).children('span').attr('aria-checked', 'false');
        $(obj).children('span').removeClass('filter-btn-option-checkmark-show');
      }
    });
  }

  $('.js-filter-btn-search-reset').click(function (e) {
    closeSpecificTab(e);
  });
  $('.js-filter-btn-search-reset').keydown(function (e) {
    if (e.keyCode === 13 || e.keyCode === 32) {
      closeSpecificTab(e);
    }
  });

  function handleOnClickFilterOption(target) {
    var $target = $('#' + target.id + ' :input');
    //Checkbox option
    var $ariaChecked = $target.attr('aria-checked');
    var $newAriaChecked = $ariaChecked === 'true' ? 'false' : 'true';
    $target.attr('aria-checked', $newAriaChecked);
    $target.prop('checked', !$target.prop('checked'));

    //Set counter
    setCounterFilteredOptions(target);
    setActiveOptions(target, target.id, $newAriaChecked);
  }

  $('.js-filter-show-btn').click(function (e) {
    //Make main-class unscrollable
    $('#main').addClass('unscrollable');
    $('.filter-btn-wrapper').addClass('scrollable');

    var $target = $(e.target);

    var $ariaClicked = $target.attr('aria-pressed');
    var $newAriaChecked = $ariaClicked === 'true' ? 'false' : 'true';
    $target.attr('aria-pressed', $newAriaChecked);
    var $t = $('.filter-btn-wrapper');
    var $shouldClose = $($t).hasClass('filter-btn-wrapper-show');
    $shouldClose === false ? $('.filter-btn-wrapper').addClass('filter-btn-wrapper-show') : $('.filter-btn-wrapper').removeClass('filter-btn-wrapper-show');
  });

  $('.js-filter-hide-btn').click(function (e) {
    //Make main-class scrollable
    $('#main').addClass('scrollable');
    $('.filter-btn-wrapper').addClass('unscrollable');

    var $target = $(e.target);
    var $ariaClicked = $target.attr('aria-pressed');
    var $newAriaChecked = $ariaClicked === 'true' ? 'false' : 'true';
    $target.attr('aria-pressed', $newAriaChecked);
    var $t = $('.filter-btn-wrapper');

    var $shouldClose = $($t).hasClass('filter-btn-wrapper-show');
    $shouldClose === false ? $('.filter-btn-wrapper').addClass('filter-btn-wrapper-show') : $('.filter-btn-wrapper').removeClass('filter-btn-wrapper-show');
  });

  $('.js-filter-btn-clear').click(function (e) {
    $('.js-filter-btn-option').each(function (i, obj) {
      setActiveOptions(obj, obj.id, 'false');
    });
    clearCounterFilterOptions();
    submitSearchForm();
  });

  //Settings the options on load
  $(document).ready(function (e) {
    $('.js-filter-btn-option').each(function (i, obj) {
      setCounterFilteredOptions(obj);
    });
    addFiltersToQuery(false);
  });

  $('#filter-pageNext').click(function (e) {
    var nextPageValue = $('#filter-pageNext-input').val();
    var $form = $('#filterSearchId');
    $form.children('div').children('input[name=page]').val(nextPageValue);
    $form.submit();
  });

  $('#filter-pagePrev').click(function (e) {
    var nextPageValue = $('#filter-pagePrev-input').val();
    var $form = $('#filterSearchId');
    $form.children('div').children('input[name=page]').val(nextPageValue);
    $form.submit();
  });

  $(document).mouseup(function (e) {
    var container = $('.js-filter-btn');
    var container2 = $('.js-filter-content');
    var container3 = $('.filter-btn-search-wrapper');

    var clickOnContainer = true;
    var clickOnContainer2 = true;
    var clickOnContainer3 = true;

    if (!container.is(e.target) && container.has(e.target).length === 0) clickOnContainer = false;
    if (!container2.is(e.target) && container2.has(e.target).length === 0) clickOnContainer2 = false;

    if (!container3.is(e.target) && container3.has(e.target).length === 0) clickOnContainer3 = false;

    // If the target of the click isn't the container
    if (!clickOnContainer && !clickOnContainer2 && !clickOnContainer3) {
      closeAllFilterDropdowns();
    }
  });

  $('#filter-btn-mobile').click(function (e) {
    submitSearchForm();
  });

  $('.js-filter-btn-search').click(function (e) {
    addFiltersToQuery(true);
  });

  function submitSearchForm() {
    var $form = $('#filterSearchId');
    $form.children('div').children('input[name=page]').val(1);
    $form.submit();
  }
});
;
$(function () {
  function blurLongPreamble() {
    var $bodyText = $('.js-readMore-body p');

    $($bodyText).each(function (i, obj) {
      var objText = $(obj).text();
    });

    const heightLimit = 99;

    var $body = $('.js-readMore-body p');

    $($body).each(function (i, obj) {
      var objHeight = $(obj).outerHeight();

      if (objHeight > heightLimit) {
        var pChild = $(obj);
        pChild.parent().addClass('max-height-body');
        var readMoreChild = $(obj).parent().children('div');
        var id = obj.id.replace('-p', '');

        var body = pChild.parent();
        var checked = $(pChild).attr('aria-clicked') === 'true' ? true : false;

        if (!checked) {
          $(id + '-w').addClass('hide-buttons');
          pChild.addClass('educationList-body-read-more-text');
          $('#' + id + '-body').addClass('max-height-readmore');
          $('.documentList-thumbnail').hide();
          // // $('.documentList-body-links-item-wrapper').hide();
          readMoreChild.addClass('show-block');

          $('#readMore').addClass('show-block');
        }
      }
    });
  }

  $(document).ready(function () {
    blurLongPreamble();
  });

  $('.js-readMore-btn').click(function (e) {
    var pParent = $(e.target).parent();
    var listBody = $(pParent).parent();
    var pChild = listBody.children('p');
    var id = $(pChild).attr('id');
    var formattedId = id.replace('-p', '');
    $(pChild).attr('aria-clicked', 'true');
    $('#' + formattedId + '-body').removeClass('max-height-readmore');
    pChild.removeClass('educationList-body-read-more-text');
    $('#readMore-edu').removeClass('show-block-education');
    pParent.removeClass('show-block');

    $('.documentList-body-links-item-wrapper').removeClass('hide-buttons');

    listBody.parent().addClass('educationList-body-fullHeight');
  });

  $('.js-show-extra-education-items').click(function (e) {
    $('.js-extra-item').each(function (index, obj) {
      $(obj).removeClass('hide-extra-items');
    });
    blurLongPreamble();
    $(e.target).addClass('hide-extra-items');
  });

  $('.js-readMore-btn').keydown(function (e) {
    if (e.keyCode === 13) {
      var pParent = $(e.target).parent();
      var listBody = $(pParent).parent();
      var pChild = listBody.children('p');
      $(pChild).attr('aria-clicked', 'true');
      pChild.removeClass('educationList-body-read-more-text');
      pParent.removeClass('show-block');
      $('#readMore-edu').removeClass('show-block-education');
      $('.documentList-body-links-item-wrapper').removeClass('hide-buttons');
      listBody.parent().addClass('educationList-body-fullHeight');
    }
  });
});
;
$(function () {
  $(document).ready(function () {
    var $downloadLinkItem = $('.js-documentList-meta-item-link');
    var dlChild = $downloadLinkItem.children('a');
    $(dlChild).hide();
  });

  function closeAllFilterDropdowns() {
    $filterOptions = $('.js-sort-btn');
    var mq = window.matchMedia('(min-width: 1025px)');
    if (mq.matches) {
      $filterOptions.each(function (i, obj) {
        $(obj).attr('aria-pressed', 'false');
        var $btnContent = $('#content-' + obj.id);
        $('.js-sort-content').removeClass('filter-btn-content-show');
        $btnContent.removeClass('filter-btn-content-show');
      });
    }
  }

  $('.js-sort-btn-item').click(function (e) {
    e.stopPropagation();

    if ($(e.target).hasClass('step-sort-btn-item')) {
      toggleDropdown($(e.target).closest('div').children());
    }
  });

  $('.js-sort-btn').on('click', '*', function (e) {
    e.stopPropagation();

    if (!$(e.target).hasClass('filter-btn-option')) {
      e.target.type != null ? toggleDropdown(e.target) : toggleDropdown(e.target.parentElement);
    }
  });

  $('.js-sort-btn').keydown(function (e) {
    if (e.keyCode === 13) {
      e.stopPropagation();

      if ($(e.target).hasClass('step-btn-option')) {
        toggleDropdown(e.target);
      } else {
        var er = e.target;

        toggleDropdown(e.target);
      }
      // if (!$(e.target).hasClass('filter-btn-option')) {
      //   e.target.type != null ? toggleDropdown(e.target) : toggleDropdown(e.target.parentElement);
      // }
    }
  });

  $('.js-sort-btn').on('keydown', '*', function (e) {
    if (e.keyCode === 13) {
      e.stopPropagation();
      if (!$(e.target).hasClass('filter-btn-option')) {
        e.target.type != null ? toggleDropdown(e.target) : toggleDropdown(e.target.parentElement);
      }
    }
  });

  $('.sort-btn-text-span').on('click', function (e) {
    e.stopPropagation();

    toggleDropdown(e.target.parentElement.parentElement);
    // if (!$(e.target).hasClass('filter-btn-option')) {
    //   e.target.type != null ? toggleDropdown(e.target) : ;
    // }
  });

  $('.js-sort-btn-option').click(function (e) {
    var $form = $('#documentSortSearchId');

    $form.children('input[name=sortOrder]').val(e.target.id);
    submitSearchForm();
  });

  function submitSearchForm() {
    var $form = $('#documentSortSearchId');
    $form.children('input[name=page]').val(1);
    $form.submit();
  }

  function toggleDropdown(target) {
    var _id = target.id === undefined ? target[0].id : target.id;

    var $target = $('#' + _id);
    var $ariaPressed = $target.attr('aria-pressed');
    var $newAriaPressed = $ariaPressed === 'true' ? 'false' : 'true';
    $target.attr('aria-pressed', $newAriaPressed);
    var $btnContent = $('#content-' + _id);

    var mq = window.matchMedia('(min-width: 1025px)');
    if (mq.matches) {
      $('.js-sort-content').removeClass('filter-btn-content-show');

      $('.js-sort-btn').each(function (i, obj) {
        if (obj.id !== _id) {
          $(obj).attr('aria-pressed', 'false');
        } else {
          $(obj).attr('aria-pressed', $newAriaPressed);
        }
      });
    }

    $newAriaPressed === 'true' ? $btnContent.addClass('filter-btn-content-show') : $btnContent.removeClass('filter-btn-content-show');
  }

  $(document).mouseup(function (e) {
    var container = $('.js-sort-btn');
    var container2 = $('.js-sort-content');

    var clickOnContainer = true;
    var clickOnContainer2 = true;

    if (!container.is(e.target) && container.has(e.target).length === 0) clickOnContainer = false;
    if (!container2.is(e.target) && container2.has(e.target).length === 0) clickOnContainer2 = false;

    // If the target of the click isn't the container
    if (!clickOnContainer && !clickOnContainer2) {
      closeAllFilterDropdowns();
    }
  });

  $('.js-sort-btn-option').keydown(function (e) {
    if (e.keyCode === 13) {
      var $form = $('#documentSortSearchId');

      $form.children('input[name=sortOrder]').val(e.target.id);
      submitSearchForm();
    }
  });

  $('.js-add-cart').click(function (e) {
    var id = e.target.getAttribute('data');

    let value = $('#cartAssistant').val();
    let newValue = JSON.parse(value);
    newValue.push(id);
    $('#cartAssistant').val(JSON.stringify(newValue));
  });

  $('.js-add-cart').on(
    'click',
    _.debounce(addItemToCartcookie, 800, {
      trailing: true,
    })
  );

  function addItemToCartcookie(id) {
    $('.cart').removeClass('flashit');
    const ids = $('#cartAssistant').val();
    $('#cartAssistant').val('[]');

    $.ajax({
      contentType: 'application/json',
      dataType: 'json',
      data: ids,
      type: 'POST',
      url: '/DocumentOrder/AddToBasket',
      success: function (response) {
        getItemFromCartcookie(function (result) {
          const cartCookies = result;
          if (cartCookies) {
            $('.cart').css('display', 'flex');
            $('.js-cart-items').empty();

            for (i = 0; i < cartCookies.length; i++) {
              const cName = cartCookies[i].name;
              const cId = cartCookies[i].id;

              //Check double entries and append amounts

              const cAmount = cartCookies[i].amount + 'x';

              const pName = document.createElement('p');
              pName.innerHTML = cName;

              const pAmount = document.createElement('p');
              pAmount.innerHTML = cAmount;

              //Create a div and set id to prevent double entries
              const div = document.createElement('div');
              div.setAttribute('id', window.btoa(cId));
              const id = window.btoa(cId);

              if (document.getElementById(id) === null) {
                div.appendChild(pAmount);
                div.appendChild(pName);
                div.classList.add('cart-body-item');
                $('.js-cart-items').append(div);
                $('.cart').addClass('flashit');
              }
            }
          }
        });
      },
    });
  }

  function msieversion() {
    var ua = window.navigator.userAgent;
    var msie = ua.indexOf('MSIE ');

    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) return true;

    return false;
  }

  function blurLongPreamble() {
    var $bodyText = $('.js-readMore-body-doc p');

    $($bodyText).each(function (i, obj) {
      var objText = $(obj).text();
    });

    const heightLimit = 99;

    var $body = $('.js-readMore-body-doc p');

    $($body).each(function (i, obj) {
      var objHeight = $(obj).outerHeight();

      if (objHeight > heightLimit) {
        var pChild = $(obj);
        pChild.addClass('educationList-body-read-more-text');

        var readMoreChild = $(obj).parent().children('div');
        var id = obj.id.replace('-p', '');

        $(id + '-w').addClass('hide-buttons');

        $('#' + id + '-body').addClass('max-height-readmore');

        readMoreChild.addClass('show-block');
      }
    });
  }

  $(document).ready(function () {
    blurLongPreamble();
  });

  function getItemFromCartcookie(callback) {
    $.ajax({
      accepts: 'application/json',
      type: 'GET',
      url: '/DocumentOrder/GetBasket',
      success: function (response) {
        callback(response.documentOrderBasket.products);
      },
    });
  }

  $(document).ready(function () {
    getItemFromCartcookie(function (result) {
      const cartCookies = result;

      if (cartCookies) {
        if (cartCookies.length > 0) $('.cart').css('display', 'flex');
        for (i = 0; i < cartCookies.length; i++) {
          const cName = cartCookies[i].name;
          const cId = cartCookies[i].id;
          const cAmount = cartCookies[i].amount + 'x';

          const pName = document.createElement('p');
          pName.innerHTML = cName;

          const pAmount = document.createElement('p');
          pAmount.innerHTML = cAmount;

          //Create a div and set id to prevent double entries
          const div = document.createElement('div');
          div.setAttribute('id', window.btoa(cId));
          const id = window.btoa(cId);

          if (document.getElementById(id) === null) {
            div.appendChild(pAmount);
            div.appendChild(pName);
            div.classList.add('cart-body-item');
            $('.js-cart-items').append(div);
          }
        }
      }
    });
  });

  $('.js-readMore-btn').click(function (e) {
    var pParent = $(e.target).parent();
    var listBody = $(pParent).parent();
    var pChild = listBody.children('p');
    var id = $(pChild).attr('id');
    var formattedId = id.replace('-p', '');
    $('#' + formattedId + '-body').removeClass('max-height-readmore');
    pChild.removeClass('educationList-body-read-more-text');
    pParent.removeClass('show-block');

    $('.documentList-body-links-item-wrapper').removeClass('hide-buttons');
    listBody.addClass('educationList-body-fullHeight');

    $('#' + formattedId + '-body').addClass('educationList-body-fullHeight');
    $('#' + formattedId + '-t').show();
    $('#' + formattedId + '-w').show();
  });

  $('.js-readMore-btn').keydown(function (e) {
    if (e.keyCode === 13) {
      var pParent = $(e.target).parent();
      var listBody = $(pParent).parent();
      var pChild = listBody.children('p');

      pChild.removeClass('educationList-body-read-more-text');
      pParent.removeClass('show-block');
      $('.documentList-body-links-item-wrapper').removeClass('hide-buttons');
      listBody.addClass('educationList-body-fullHeight');

      $('#' + formattedId + '-body').addClass('educationList-body-fullHeight');
      $('#' + formattedId + '-t').show();
      $('#' + formattedId + '-w').show();
    }
  });

  //Might use later. Cart window follows scroll

  // // When the user scrolls the page, execute myFunction
  // window.onscroll = function () {
  //   myFunction();
  // };

  // // Get the header
  // var header = document.getElementById('documentCart');

  // // Get the offset position of the navbar

  // // Add the sticky class to the header when you reach its scroll position. Remove "sticky" when you leave the scroll position
  // function myFunction() {
  //   var sticky = header.offsetTop;
  //   console.log('header', sticky);
  //   console.log(window.pageYOffset);

  //   if (window.pageYOffset > 550) {
  //     header.classList.add('sticky');
  //   } else {
  //     header.classList.remove('sticky');
  //   }
  // }
});
;
$(function (e) {
  $('.order-cms-tab').on('click', function (e) {
    $('.order-cms-tab').each(function (i, _e) {
      $(_e).attr('aria-checked', 'false');
    });

    $('.order-cms-tableBody').each(function (i, _e) {
      $(_e).hide();
    });

    var pageNr = $(this).attr('data-PageNr');

    $('.js-pagination-btn-next').each(function (i, obj) {
      $(obj).removeClass('hidden');
      $(obj).addClass('hidden');
    });

    $('.js-pagination-btn-prev').each(function (i, obj) {
      $(obj).removeClass('hidden');
      $(obj).addClass('hidden');
    });
    $('.js-totalResult').each(function (i, obj) {
      $(obj).removeClass('hidden');
      $(obj).addClass('hidden');
    });

    $('#filter-pageNext-' + pageNr).removeClass('hidden');
    $('#filter-pagePrev-' + pageNr).removeClass('hidden');
    $('#totalResult-' + pageNr).removeClass('hidden');

    var dateText = document.getElementById('tableHeadDate');

    if (e.target.nodeName === 'P') {
      $(e.target).parent().attr('aria-checked', 'true');
      const id = $(e.target).parent().attr('id');
      dateText.innerText = setDateText(id);
      $('#' + id + '-table').css('display', 'table-row-group');
    } else {
      $(e.target).attr('aria-checked', 'true');
      const id = e.target.id;
      dateText.innerText = setDateText(id);
      $('#' + id + '-table').css('display', 'table-row-group');
    }
  });

  function setDateText(id) {
    if (id === 'order-closed') {
      return 'Datum (avslutad)';
    } else if (id === 'order-invoiced') {
      return 'Datum (fakturerad)';
    } else {
      return 'Datum (inkommen)';
    }
  }

  $('#orderInvoiceBtn').click(function (e) {
    //$('#updateOrderFormId').submit();
  });

  $('.js-order-confirmation').click(function (e) {
    var triggerEvent = $(this).attr('data-trigger');
    const statusTarget = $(this).attr('data-status');
    if (triggerEvent == 'true') {
      HandleOnClickActionButton(statusTarget);
    } else {
      $('.js-order-confirmation-modal').hide();
    }
  });

  $('.js-order-btn').click(function (e) {
    const statusTarget = e.target.getAttribute('data-status');

    if (statusTarget == 'delete') {
      $('.js-order-confirmation').attr('data-status', statusTarget);
      $('.js-order-confirmation-modal').css('display', 'flex');
    } else {
      HandleOnClickActionButton(statusTarget);
    }
  });

  function HandleOnClickActionButton(statusTarget) {
    $('.js-order-confirmation-modal').hide();
    $('.order-cms-tab').each(function (index, obj) {
      if (obj.getAttribute('aria-checked') === 'true') {
        var form = $('#updateOrderFormId');
        var inputField = form.find(':input[name=ids]');
        inputField.val('[]');
        $('input', $('#' + obj.id + '-table')).each(function (index, obj) {
          if (obj.checked) {
            var form = $('#updateOrderFormId');
            var inputField = form.find(':input[name=ids]');
            var prevVal = inputField.val();
            let newValue = JSON.parse(prevVal);
            newValue.push(obj.value);
            inputField.val(JSON.stringify(newValue));
          }
        });
      }
    });
    var form = $('#updateOrderFormId');
    var inputField = form.find(':input[name=status]');
    inputField.val(statusTarget);
    $('#loadingSpinner').show();
    $('#updateOrderFormId').submit();
  }
  $('.js-pagination-btn-next').click(function (e) {
    var tabNr = $(this).attr('data-pageNr');
    var nextValue = $('#filter-pageNext-input-' + tabNr).val();

    $form = $('#orderCmsPage');
    $form.children('input[name=page' + tabNr + ']').val(nextValue);
    $form.children('input[name=currentTab]').val(parseInt(tabNr));
    $form.submit();
  });

  $('.js-pagination-btn-prev').click(function (e) {
    var tabNr = $(this).attr('data-pageNr');
    var nextValue = $('#filter-pagePrev-input-' + tabNr).val();

    $form = $('#orderCmsPage');
    $form.children('input[name=page' + tabNr + ']').val(nextValue);

    $form.children('input[name=currentTab]').val(parseInt(tabNr));
    $form.submit();
  });
});
;
var $componentServices = $('.component-services');
var $servicesList = $componentServices.find('.component-services_list');
var $servicesItems = $componentServices.find('.component-services_list .accordion');
var $containerDesktop = $componentServices.find('.container-desktop');
var $servicesFirstItem = $componentServices.find('.container-desktop .first-item');
var $servicesSecondItem = $componentServices.find('.accordion.second-item');
//var $servicesclickItem = $componentServices.find('.click-item');
var $contentContainerDesktop = $componentServices.find('.container-desktop_content');
var $openItem = $componentServices.find('.container-desktop .accordion-open');
var $subMenu = $('nav.submenu');
var $subMenuItem = $subMenu.find('li.submenu_item');

var mediaQueryTabletUp = window.matchMedia("(min-width: 768px)");
var lastClickedItem = undefined;
var hashList = [];
var dontNavigate = true;

// Polyfill for endsWith in IE
if (!String.prototype.endsWith) {
    String.prototype.endsWith = function (search, this_len) {
        if (this_len === undefined || this_len > this.length) {
            this_len = this.length;
        }
        return this.substring(this_len - search.length, this_len) === search;
    };
}

if (!String.prototype.startsWith) {
    String.prototype.startsWith = function (search, this_len) {
        if (this_len === undefined || this_len > this.length) {
            this_len = this.length;
        }
    };
}

function handleHashChange() {

    //get current item from hash
    var hashParts = window.location.hash.replace('#!', '').split('/');

    if (hashParts.length > 0) {
        //mobil
        if (!mediaQueryTabletUp.matches) {

            if (hashParts[0] === '') {
                $('.accordion').removeClass('accordion-open');
                $('.accordion').addClass('accordion-close');
                $('.container').hide();
                $('.first-item-mobile').removeClass('accordion-close');
                $('.first-item-mobile').addClass('accordion-open');
                $('.first-item-mobile').next().show();
                return;
            }

            var accordionToOpen = $('.accordion-close[data-name="' + hashParts[0] + '"]');
            if (accordionToOpen.length === 1) {
                $('.accordion').removeClass('accordion-open');
                $('.accordion').addClass('accordion-close');
                $('.container').hide();
                accordionToOpen.removeClass('accordion-close');
                accordionToOpen.addClass('accordion-open');
                accordionToOpen.next().show();

                var filter = accordionToOpen.next().find('.content .content_filter li:first');
                if (filter.length === 1) {
                    accordionToOpen.next().find('.content .content_filter li').removeClass('active');
                    filter.addClass('active');
                }

                scrollAmount = 0;
                offset = 10;

                $('html, body').animate({
                    scrollTop: $('.accordion-open').offset().top - offset
                }, scrollAmount);
            }
            else {
                if (hashParts.length === 2) {
                    var activeFilter = $('.accordion-open').next().find('.content .content_filter li[data-filter="' + hashParts[1] + '"]');
                    $('.content_filter li').removeClass('active');
                    activeFilter.addClass('active');
                }
            }
        }
        else {
            //om vi går tillbaka till en url utan hashbang
            if (hashParts[0] === '') {
                $currentItem = $servicesFirstItem;
                $currentItem.removeClass('accordion-close');
                $currentItem.addClass('accordion-open');

                $contentContainerDesktop.empty();
                setItemHeadline($currentItem);
                setItemContent($currentItem);
                $('.accordion.second-item').removeClass('accordion-open');
                activateExpanderWithSelector('.container-desktop_content .news-text');
            }
            else { //standardfall
                var $currentItem = $('[data-name="' + hashParts[0] + '"].click-item:visible').not('.accordion-open');

                if ($currentItem.length === 1) {

                    $('.accordion.click-item').show();
                    $contentContainerDesktop.empty();
                    $contentContainerDesktop.find('a').focus();

                    $servicesItems.removeClass('accordion-open');
                    $servicesFirstItem.removeClass('accordion-open');

                    setItemHeadline($currentItem);
                    setItemContent($currentItem);
                    setClickedItem($currentItem);
                }

                var $employee = $componentServices.find('.employee');
                var $reception = $componentServices.find('.reception');
                var $filterItem = $componentServices.find('.content_filter li');
                //hantera filter
                if (hashParts.length === 1) { //är inget filter satt i hashbangen så ska första markeras
                    var $firstFilterItem = $openItem.parent().find('.container-desktop_content .content_filter li:first');
                    if ($firstFilterItem.length > 0) {
                        var selectedDataFilter = $firstFilterItem.data('filter');
                        $filterItem.removeClass('active');
                        $firstFilterItem.addClass('active');

                        $employee.removeClass('visible');

                        $employee.each(function () {
                            var $currentItem = $(this);
                            filterEmployees(selectedDataFilter, $currentItem);
                        });

                        $reception.removeClass('visible');

                        $reception.each(function () {
                            $('[data-filter="' + selectedDataFilter + '"]').addClass('visible');
                        });
                    }
                }
                else if (hashParts.length === 2) { //annars markerar vi det filter som är satt
                    var $activeFilterItem = $openItem.parent().find('.container-desktop_content .content_filter li[data-filter="' + hashParts[1] + '"]');
                    if ($activeFilterItem.length > 0) {


                        var selectedActiveDataFilter = $activeFilterItem.data('filter');
                        $filterItem.removeClass('active');
                        $activeFilterItem.addClass('active');

                        $employee.removeClass('visible');

                        $employee.each(function () {
                            var $currentItem = $(this);
                            filterEmployees(selectedActiveDataFilter, $currentItem);
                        });

                        $reception.removeClass('visible');

                        $reception.each(function () {
                            $('[data-filter="' + selectedActiveDataFilter + '"]').addClass('visible');
                        });
                    }
                }
            }
        }
    }
}

// Set id on items
function setItemsId() {
    var id = 2;

    $servicesItems.each(function () {
        $(this).attr('data-order-id', id);

        id++;
    });
}

// Set items in default order
function setItemsOrder() {
    $servicesItems.each(function () {
        var $currentItem = $(this);
        var currentItemId = $currentItem.attr('data-order-id');

        $currentItem.css('order', currentItemId);
    });
}

// If property "Rubrik på länkat block" in Epi has a value that matches a service block headline, set submenu attribute data-link to be the id of that service block
function setSubMenuDataLinks() {
    var $servicesItemsVisible = $componentServices.find('.accordion:visible');

    $subMenuItem.each(function () {
        var $currentMenuItem = $(this);
        var subMenuItemDataLinkText = $currentMenuItem.attr('data-link');

        if (subMenuItemDataLinkText !== null && subMenuItemDataLinkText !== undefined) {
            var firstPart = subMenuItemDataLinkText.trim().split('/')[0].toLowerCase();
            $servicesItemsVisible.each(function () {
                var $currentBlockItem = $(this);
                var currentBlockItemId = $currentBlockItem.attr('data-order-id');
                var currentItemHeadline = $currentBlockItem.find('.title').text().toLowerCase();

                if (firstPart === currentItemHeadline) {
                    $currentMenuItem.find('a').attr('data-linkid', currentBlockItemId);
                }
            });
        }
    });
}

function setBannerDataLink() {
    var $serviceLink = $('.top-banner_text_heading.service-link');
    if ($serviceLink.length > 0) {
        var $servicesItemsVisible = $componentServices.find('.accordion:visible');
        var dataLinkText = $serviceLink.attr('data-link');
        var firstPart = dataLinkText.trim().split('/')[0].toLowerCase();
        $servicesItemsVisible.each(function () {
            var $currentBlockItem = $(this);
            var currentBlockItemId = $currentBlockItem.attr('data-order-id');
            var currentItemHeadline = $currentBlockItem.find('.title').text().toLowerCase();

            if (firstPart === currentItemHeadline) {
                $serviceLink.parent('a').attr('data-linkid', currentBlockItemId);                
            }
        });
    }
}

// Click on submenu item
$('body').on('click', 'nav.submenu li.submenu_item a, a:has(.service-link)', function () {
    var $currentItem = $(this);
    var currentItemId = $currentItem.attr('data-linkid');
    if (currentItemId) {
        var scrollAmount = 600;
        var offset = 15;
        var currentAccordion = $('.accordion[data-order-id="'+ currentItemId + '"]');

        //trigga bara klick om accordionen inte redan är öppen
        if (!currentAccordion.hasClass('accordion-open')) {
            $('.accordion[data-order-id="' + currentItemId + '"]').trigger('click');
        }
        else {
            if (mediaQueryTabletUp.matches) {
                $('html, body').animate({
                    scrollTop: $('.container-desktop').offset().top - offset
                }, scrollAmount);
            }
        }

        var segments;
        if ($currentItem.parents('li.submenu_item').length > 0) {
            segments = $currentItem.parents('li.submenu_item').attr('data-link').trim().split('/');
        }
        else {
            segments = $currentItem.children('.service-link').attr('data-link').trim().split('/');
        }
        if (segments.length > 1) {
            var tabName = segments[1];
            $('.content_filter:visible > li > a').each(function () {
                if (tabName.toLowerCase() === $(this).text().toLowerCase()) {
                    $(this).trigger('click');
                    return false;
                }
            });
        }

        // If mobile
        if (!mediaQueryTabletUp.matches) {
            scrollAmount = 600;
            offset = 10;

            $('html, body').animate({
                scrollTop: $('.accordion-open').offset().top - offset
            }, scrollAmount);
        }

    }
});

// Click on service item - scroll to right position (only for mobile)
$('body').on('click', '.component-services_list .accordion', function () {
    // If mobile
    if (!mediaQueryTabletUp.matches) {
        var $currentItem = $(this);

        $('html, body').animate({
            scrollTop: $($currentItem).offset().top - 10
        }, 600);
    }
    else {
        $('html, body').animate({
            scrollTop: $('.container-desktop').offset().top - 15
        }, 600);
    }
});

// Set first item content
function setFirstItemContent() {
    var $firstItem = $componentServices.find('.first-item[data-order-id="1"]');
    var $firstItemContent = $firstItem.next().find('.content').clone();

    $contentContainerDesktop.append($firstItemContent);
    activateExpanderWithSelector('.container-desktop_content .news-text');
}

// Set second item in the left column after first item (before content container)
function setSecondItem() {
    var $componentServices = $('.component-services');
    var $secondItem = $componentServices.find('.component-services_list .accordion[data-order-id="3"]');
    var $secondItemClone = $secondItem.clone();
    var $secondItemContent = $componentServices.find('.component-services_list .accordion[data-order-id="3"]').next();
    var $secondItemContentClone = $secondItemContent.clone();

    $secondItemClone.addClass('second-item');
    $('.container-desktop .accordion.second-item').replaceWith($secondItemClone);
    $secondItemContentClone.insertAfter('.container-desktop .accordion.second-item');
    $secondItem.hide();

    lastClickedItem = $secondItem;
}

// Set current items headline in left content container
function setItemHeadline($currentItem) {
    var $headline = $currentItem.find('.active-item').clone();
    $openItem.append($headline);
}

// Set current items content in left content container
function setItemContent($currentItem) {
    var $itemContent = $currentItem.next().find('.content').first().clone();
    $contentContainerDesktop.append($itemContent);
}

// Set clicked item to be active
function setClickedItem($currentItem) {
    var $clone = $currentItem.clone();
    var $cloneContent = $currentItem.next().clone();

    $clone.addClass('accordion-open');
    $clone.addClass('second-item');
    $clone.removeClass('accordion-close');
    $('.container-desktop .accordion.second-item').replaceWith($clone);
    $cloneContent.insertAfter('.container-desktop .accordion.second-item');
    $currentItem.hide();
    filter();
}

$('body').on('click', '.container-show-more a', function () {
    var link = $(this);
    var container = $(this).parents('.content');
    var skip = container.children('.news-content').size();
    var currentPath = window.location.pathname;
    if (!currentPath.endsWith("/"))
        currentPath += "/";

    $.get(currentPath + 'LoadNews', { skip: skip }, function (data) {
        link.parent().remove();
        container.append(data);
        activateExpanderWithSelector('.container-desktop_content .news-text');
        activateExpanderMobileWithSelector('.news-text');
    });
});

// Add hashbang as href on all links
function setHrefOnLinks() {
    $componentServices.find('li[data-filter]').each(function () {
        var rawUrl = $(this).attr('data-currentUrl');
        var parentHash = $(this).attr('data-parent');
        var filterHash = $(this).attr('data-filter');

        $(this).find('a').attr('href', rawUrl + '\\#!' + parentHash + '/' + filterHash);
    });


    $('.component-services_list .accordion:not(.first-item-mobile)').each(function () {
        var rawUrl = $(this).attr('data-currentUrl');
        var hash = $(this).attr('data-name');

        $(this).attr('href', rawUrl + '\\#!' + hash);
    });
}

// Add a hashbang to the window.location.hash based on the selected items / path.
function addHash(key, root) {

    if (root) {
        hashList = [];
        hashList[0] = key;
    } else {
        if (hashList[hashList.length - 1] !== key) {
            if (hashList.length - 1 !== 0) {
                hashList.splice(hashList.length - 1, hashList.length);
            }
            hashList.push(key);
        }
    }

    var urlHashParam = "";
    var counter = 0;

    hashList.forEach(function (value) {
        if (counter === 0) {
            urlHashParam = "!" + value;
        } else {
            urlHashParam += "/" + value;
        }
        counter++;

    });

    window.location.hash = urlHashParam;
}

function loadNavigationStateBasedOnHash() {
    if (window.location.hash) {
        var loadedHashValues = [];
        var currentUrlHash = decodeURIComponent(window.location.hash).replace("#!", '');
        loadedHashValues = currentUrlHash.split('/');
        executeUINavigation(loadedHashValues);
    }
}

function executeUINavigation(loadedHashValues) {
    var counter = 0;
    loadedHashValues.forEach(function (value) {
        if (counter === 0) {
            var rootElement = $(".click-item").filter('[data-name="' + value + '"]');

            rootElement.click();

        } else {
            $componentServices.find('.content_filter .visible ul ');

            var $subNavigation = $componentServices.find("li").filter('[data-filter="' + value + '"]');
            $subNavigation.click();
            $subNavigation.addClass('active');
        }
        counter++;
    });
}
// Only first item
$servicesFirstItem.on('click', function (e) {
    e.preventDefault();
    var $currentItem = $(this);

    $currentItem.removeClass('accordion-close');
    $currentItem.addClass('accordion-open');

    $contentContainerDesktop.empty();
    setItemHeadline($currentItem);
    setItemContent($currentItem);    

    $('.accordion.second-item').removeClass('accordion-open');
    $('.accordion.second-item').addClass('accordion-close');
    activateExpanderWithSelector('.container-desktop_content .news-text');
    addHash('', true);
});

$('body').on('click', '.click-item', function (e) {
    e.preventDefault();
    var $currentItem = $(this);
    
    // If tablet up
    if (mediaQueryTabletUp.matches) {
        //var $currentItemContent = $currentItem.next();

        if ($currentItem.hasClass('second-item') && window.location.hash.startsWith('#!' + $currentItem.data('name'))) {
            e.preventDefault();
            return false;            
        }

        // If second item
        //if (!$currentItem.hasClass('second-item')) {
            if (lastClickedItem) {
                $(lastClickedItem).css('order', $(lastClickedItem).attr('data-order-id')).show();
            }
            lastClickedItem = $currentItem;
        //}

        $contentContainerDesktop.find('a').focus();
        $servicesItems.removeClass('accordion-open');
        $servicesFirstItem.removeClass('accordion-open');
        $contentContainerDesktop.empty();
        setItemHeadline($currentItem);
        setItemContent($currentItem);
        setClickedItem($currentItem);

        addHash($currentItem.data("name"), true);
        // Tablet up - Trigger click on first fiter item
        $openItem.parent().find('.container-desktop_content .content_filter li:first').trigger('click');

    } else {
        addHash($currentItem.data("name"), true);
        // Mobile - Trigger click on first filter item
        $currentItem.next().find('.content .content_filter li:first').trigger('click');
    }
});

// Filter employees and receptions based on data-filter attribute
function filter() {

    var $componentServices = $('.component-services');
    var $filterItem = $componentServices.find('.content_filter li');
    var $employee = $componentServices.find('.employee');
    var $reception = $componentServices.find('.reception');

    $filterItem.on('click', function (e) {
        e.preventDefault();

        var selectedDataFilter = $(this).attr('data-filter');

        addHash(selectedDataFilter);

        $filterItem.removeClass('active');
        $(this).addClass('active');

        $employee.removeClass('visible');

        $employee.each(function () {
            var $currentItem = $(this);
            filterEmployees(selectedDataFilter, $currentItem);
        });

        $reception.removeClass('visible');

        $reception.each(function () {
            var $currentItem = $(this);
            $('[data-filter="' + selectedDataFilter + '"]').addClass('visible');
        });
    });
}

// Tablet up
function activateExpanderWithSelector(selector) {
    $(selector).expander({
        slicePoint: 200,
        expandEffect: 'fadeIn',
        userCollapseText: '',
        expandText: 'Läs mer',
        expandPrefix: ' ... ',
        expandSpeed: 250,
        collapseEffect: 'slideUp',
        collapseSpeed: 200,
        beforeExpand: function () {
            $(this).find('.print-container').show();
        }
    });

    $('.more-link').addClass('icon_right');
    //$('.less-link').addClass('icon_right');
}

// Mobile
function activateExpanderMobileWithSelector(selector) {
    $(selector).expander({
        slicePoint: 105,
        expandEffect: 'fadeIn',
        userCollapseText: '',
        expandText: 'Läs mer',
        expandPrefix: ' ... ',
        expandSpeed: 250,
        collapseEffect: 'slideUp',
        collapseSpeed: 200
    });

    $('.more-link').addClass('icon_right');
    //$('.less-link').addClass('icon_right');
}



$(document).ready(function () {
    var defaultOpenValue = '2';

    filter();
    setItemsId();
    setHrefOnLinks();
    setSubMenuDataLinks();
    setBannerDataLink();

    // If tablet up
    if (mediaQueryTabletUp.matches) {
        defaultOpenValue = '';
        setItemsOrder();
        setFirstItemContent();
        setSecondItem();

    } else {
        activateExpanderMobileWithSelector('.news-text');
    }

    $('.accordion').accordion({
        defaultOpen: defaultOpenValue,
        cssClose: 'accordion-close',
        cssOpen: 'accordion-open',
        speed: 'medium',
        bind: 'click',
        animateOpen: function (elem, opts) {
            // If tablet up
            if (!mediaQueryTabletUp.matches) {
                elem.next().show();
            }
        },
        animateClose: function (elem, opts) {
            elem.next().hide();
        }
    });

    // If tablet up
    if (mediaQueryTabletUp.matches) {
        $contentContainerDesktop.show();
    }

    // Replace all SVG images with inline SVG
    jQuery('img.svg').each(function () {
        var $img = jQuery(this);
        var imgID = $img.attr('id');
        var imgClass = $img.attr('class');
        var imgURL = $img.attr('src');
        var imgAlt = $img.attr('alt');

        jQuery.get(imgURL, function (data) {
            var $svg = jQuery(data).find('svg');

            if (typeof imgID !== 'undefined') {
                $svg = $svg.attr('id', imgID);
            }

            if (typeof imgClass !== 'undefined') {
                $svg = $svg.attr('class', imgClass + ' replaced-svg');
            }

            if (typeof imgAlt !== 'undefined') {
                $svg = $svg.attr('alt', imgAlt);
            }

            // Remove any invalid XML tags as per http://validator.w3.org
            $svg = $svg.removeAttr('xmlns:a');

            // Replace image with new SVG
            $img.replaceWith($svg);

        }, 'xml');
    });
    $(window).on('hashchange', handleHashChange);

    loadNavigationStateBasedOnHash();
});

function filterEmployees(selectedFilter, currentEmployee) {
    var currentItem = currentEmployee;
    var selectedDataFilter = selectedFilter;

    var dataFilter = currentItem.children("div").attr("data-filter");
    if (dataFilter !== null) {
        var dataFilterSplit = dataFilter.split(',');
        for (var i = 0; i < dataFilterSplit.length; i++) {
            if (dataFilterSplit[i] === selectedDataFilter) {
                currentItem.addClass('visible');
            }
        }
    }
};
var $vardcentralListPage = $('.vardcentral-list-page');
var $letterFilterItem = $vardcentralListPage.find('.vardcentral-list-page_letter-filter li a');
var $listItem = $vardcentralListPage.find('.vardcentral-list-page_list-container .list li');
var $listItemName = $vardcentralListPage.find('.vardcentral-list-page_list-container .list li .list_name a');

// Sets the first letter of the name to be data letter attribute on li element
function setDataLetterOnListItems() {
    $listItem.each(function () {
        var name = $(this).find('.list_name a').text();
        var firstLetterOfName = name.slice(0, 1);

        $(this).attr('data-letter', firstLetterOfName);
    });
}

// Filter items 
function filterItems(selectedLetter) {
    $listItem.removeClass('visible');

    $listItem.each(function () {
        var $currentItem = $(this);

        $('[data-letter="' + selectedLetter + '"]').addClass('visible');
    });
}

$letterFilterItem.on('click', function () {
    var selectedLetter = $(this).attr('data-letter');
    $letterFilterItem.removeClass('active');
    $(this).addClass('active');

    filterItems(selectedLetter);
});

$(document).ready(function () {
    setDataLetterOnListItems();
});;
var $printContainer = $('.vardcentral-page .show-in-print');

// Clone news info to print container when print icon is clicked
$('body').on('click', '.component-services .news-content .print-link', function () {
    var $currentItem = $(this);    
    var newsContent = $currentItem.closest('div.news-content').clone();

    $printContainer.empty();
    $printContainer.append(newsContent);
    $printContainer.find('.details').css('opacity', '1');
    $printContainer.find('.read-less').css('display', 'none');
    $('iframe').css('display', 'none !important');
});

// Clone reception info to print container when print icon is clicked
$('body').on('click', '.component-services .reception .print-link', function () {
    var $currentItem = $(this);
    var newsContent = $currentItem.closest('div.reception.visible').clone();

    $printContainer.empty();
    $printContainer.append(newsContent);
    $printContainer.find('.details').css('opacity', '1');
    $('iframe').css('display', 'none !important');
});;
let $campaignListPage = $('.campaignlistpage');
let $filterBtnAll = $campaignListPage.find('.filter_item_all');

if ($campaignListPage.length > 0) {

    // Add active on filter all btn if no filter is selected
    if (window.location.href.indexOf('filter') < 0) {
        $filterBtnAll.addClass('active');
    }

    // Accessible dropdown on event list page
    const SPACEBAR_KEY_CODE = [0, 32];
    const ENTER_KEY_CODE = 13;
    const DOWN_ARROW_KEY_CODE = 40;
    const UP_ARROW_KEY_CODE = 38;
    const ESCAPE_KEY_CODE = 27;

    // Accessible dropdown event time
    const list = document.querySelector(".mobile_filter .dropdown__list");
    const listContainer = document.querySelector(".mobile_filter .dropdown__list-container");
    const dropdownArrow = document.querySelector(".mobile_filter .dropdown__arrow");
    const listItems = document.querySelectorAll(".mobile_filter .dropdown__list-item");
    const dropdownSelectedNode = document.querySelector(".mobile_filter #dropdown-campaign_filter");
    const timeListItemIds = [];

    dropdownSelectedNode.addEventListener("click", function (e) {
        toggleListVisibility(e)
    });
    dropdownSelectedNode.addEventListener("keydown", function (e) {
        toggleListVisibility(e)
    });
    dropdownArrow.addEventListener("click", function (e) {
        toggleListVisibility(e)
    });

    listItems.forEach(function (item) {
        timeListItemIds.push(item.id)
    });

    //plocka ut befintligt filter
    let currentFilter = getCurrentFilter('filter');

    listItems.forEach(function (item) {

        item.addEventListener("click", function (e) {
            setSelectedListItem(e);
            closeList();
        });

        item.addEventListener("keydown", function (e) {
            switch (e.keyCode) {
                case ENTER_KEY_CODE:
                    setSelectedListItem(e);
                    closeList();
                    return;

                case DOWN_ARROW_KEY_CODE:
                    focusNextListItem(DOWN_ARROW_KEY_CODE);
                    return;

                case UP_ARROW_KEY_CODE:
                    focusNextListItem(UP_ARROW_KEY_CODE);
                    return;

                case ESCAPE_KEY_CODE:
                    closeList();
                    return;

                default:
                    return;
            }
        });

        if (item.firstChild.href.substr(-(currentFilter.length)) === currentFilter) {
            item.click();
        }
    });

    function getCurrentFilter(filtername) {
        let returnValue = '';
        let queryString = window.location.search;
        let queries = queryString.split('&');
        let filterQuery = queries.filter(function (query) {
            return query.indexOf(filtername) > -1;
        });
        if (filterQuery.length > 0) {
            let queryParts = filterQuery[0].split('=');
            returnValue = queryParts[1];
        }

        return returnValue;
    }

    function setSelectedListItem(e) {
        let selectedTextToAppend = document.createTextNode(e.target.innerText);
        dropdownSelectedNode.innerHTML = null;
        dropdownSelectedNode.appendChild(selectedTextToAppend);
    }

    function closeList() {
        list.classList.remove("open");
        dropdownArrow.classList.remove("expanded");
        listContainer.setAttribute("aria-expanded", false);
    }

    function toggleListVisibility(e) {
        let openDropDown =
            SPACEBAR_KEY_CODE.includes(e.keyCode) || e.keyCode === ENTER_KEY_CODE;

        if (e.keyCode === ESCAPE_KEY_CODE) {
            closeList();
        }

        if (e.type === "click" || openDropDown) {
            list.classList.toggle("open");
            dropdownArrow.classList.toggle("expanded");
            listContainer.setAttribute(
                "aria-expanded",
                list.classList.contains("open")
            );
        }

        if (e.keyCode === DOWN_ARROW_KEY_CODE) {
            focusNextListItem(DOWN_ARROW_KEY_CODE);
        }

        if (e.keyCode === UP_ARROW_KEY_CODE) {
            focusNextListItem(UP_ARROW_KEY_CODE);
        }
    }

    function focusNextListItem(direction) {
        const activeElementId = document.activeElement.id;
        if (activeElementId === "dropdown__selected") {
            document.querySelector("#" + filterListItemIds[0]).focus();
        } else {
            const currentActiveElementIndex = timeListItemIds.indexOf(
                activeElementId
            );
            if (direction === DOWN_ARROW_KEY_CODE) {
                const currentActiveElementIsNotLastItem =
                    currentActiveElementIndex < timeListItemIds.length - 1;
                if (currentActiveElementIsNotLastItem) {
                    const nextListItemId = timeListItemIds[currentActiveElementIndex + 1];
                    document.querySelector("#" + nextListItemId).focus();
                }
            } else if (direction === UP_ARROW_KEY_CODE) {
                const currentActiveElementIsNotFirstItem =
                    currentActiveElementIndex > 0;
                if (currentActiveElementIsNotFirstItem) {
                    const nextListItemId = timeListItemIds[currentActiveElementIndex - 1];
                    document.querySelector("#" + nextListItemId).focus();
                }
            }
        }
    }
};
let $campaignInfoPageClass = $('.campaigninfopage');

if ($campaignInfoPageClass.length > 0) {
    let $bottomSection = $('.bottom_section');
    let bottomSectionTop = $bottomSection.offset().top;
    let $btnTopContainer = $('.button-top-container');
    let $btnBottomContainer = $('.button-bottom-container');
    let $btnTopUl = $btnTopContainer.find('.prev_next');

    // Clone prev and next buttons on scroll down and insert at the bottom
    $(window).scroll(function () {
        let currentScrollPos = $(this).scrollTop();

        if (currentScrollPos >= bottomSectionTop) {
            if ($btnBottomContainer.find('.prev_next').length === 0) {
                $btnTopUl.clone().appendTo($btnBottomContainer);
            }
        } else {
            $btnBottomContainer.find('.prev_next').remove();
        }
    });
};
let $eventListPage = $('.eventlistpage');

if ($eventListPage.length > 0) {

    // Desktop: Clear all checked filters
    $eventListPage.find('.clear_all_container a').on('click', function (e) {
        e.preventDefault();

        $('.event_sorters ul:not(.dropdown)').each(function () {
            $(this).find('li:first a').trigger('click');
        });
    });

    // Accessible dropdown on event list page
    const SPACEBAR_KEY_CODE = [0, 32];
    const ENTER_KEY_CODE = 13;
    const DOWN_ARROW_KEY_CODE = 40;
    const UP_ARROW_KEY_CODE = 38;
    const ESCAPE_KEY_CODE = 27;

    // Accessible dropdown event time
    const list = document.querySelector(".time_container .dropdown__list");
    const listContainer = document.querySelector(".time_container .dropdown__list-container");
    const dropdownArrow = document.querySelector(".time_container .dropdown__arrow");
    const listItems = document.querySelectorAll(".time_container .dropdown__list-item");
    const dropdownSelectedNode = document.querySelector(".time_container #dropdown-time__selected");
    const timeListItemIds = [];

    dropdownSelectedNode.addEventListener("click", function (e) {
        toggleListVisibility(e)
    });
    dropdownSelectedNode.addEventListener("keydown", function (e) {
        toggleListVisibility(e)
    });
    dropdownArrow.addEventListener("click", function (e) {
        toggleListVisibility(e)
    });

    listItems.forEach(function (item) {
        timeListItemIds.push(item.id)
    });

    listItems.forEach(function (item) {
        item.addEventListener("click", function (e) {
            setSelectedListItem(e);
            closeList();
        });

        item.addEventListener("keydown", function (e) {
            switch (e.keyCode) {
                case ENTER_KEY_CODE:
                    setSelectedListItem(e);
                    closeList();
                    return;

                case DOWN_ARROW_KEY_CODE:
                    focusNextListItem(DOWN_ARROW_KEY_CODE);
                    return;

                case UP_ARROW_KEY_CODE:
                    focusNextListItem(UP_ARROW_KEY_CODE);
                    return;

                case ESCAPE_KEY_CODE:
                    closeList();
                    return;

                default:
                    return;
            }
        });
    });

    function setSelectedListItem(e) {
        let selectedTextToAppend = document.createTextNode(e.target.innerText);
        dropdownSelectedNode.innerHTML = null;
        dropdownSelectedNode.appendChild(selectedTextToAppend);
    }

    function closeList() {
        list.classList.remove("open");
        dropdownArrow.classList.remove("expanded");
        listContainer.setAttribute("aria-expanded", false);
    }

    function toggleListVisibility(e) {
        let openDropDown =
            SPACEBAR_KEY_CODE.includes(e.keyCode) || e.keyCode === ENTER_KEY_CODE;

        if (e.keyCode === ESCAPE_KEY_CODE) {
            closeList();
        }

        if (e.type === "click" || openDropDown) {
            list.classList.toggle("open");
            dropdownArrow.classList.toggle("expanded");
            listContainer.setAttribute(
                "aria-expanded",
                list.classList.contains("open")
            );
        }

        if (e.keyCode === DOWN_ARROW_KEY_CODE) {
            focusNextListItem(DOWN_ARROW_KEY_CODE);
        }

        if (e.keyCode === UP_ARROW_KEY_CODE) {
            focusNextListItem(UP_ARROW_KEY_CODE);
        }
    }

    function focusNextListItem(direction) {
        const activeElementId = document.activeElement.id;
        if (activeElementId === "dropdown__selected") {
            document.querySelector("#" + filterListItemIds[0]).focus();
        } else {
            const currentActiveElementIndex = timeListItemIds.indexOf(
                activeElementId
            );
            if (direction === DOWN_ARROW_KEY_CODE) {
                const currentActiveElementIsNotLastItem =
                    currentActiveElementIndex < timeListItemIds.length - 1;
                if (currentActiveElementIsNotLastItem) {
                    const nextListItemId = timeListItemIds[currentActiveElementIndex + 1];
                    document.querySelector("#" + nextListItemId).focus();
                }
            } else if (direction === UP_ARROW_KEY_CODE) {
                const currentActiveElementIsNotFirstItem =
                    currentActiveElementIndex > 0;
                if (currentActiveElementIsNotFirstItem) {
                    const nextListItemId = timeListItemIds[currentActiveElementIndex - 1];
                    document.querySelector("#" + nextListItemId).focus();
                }
            }
        }
    }

    // Dropdown Event Time Show/Hide
    const optionAll = document.querySelector("#option-all");
    const optionDays = document.querySelector("#option-days");
    const optionMonths = document.querySelector("#option-months");
    let $eventListItemsAll = $(".event_list li.event");
    let $eventListItemDays = $(".event_list li.event.week");
    let $eventListItemMonths = $(".event_list li.event.month");

    optionAll.addEventListener("click", function (e) {
        toggleShowEvents(e)
    });
    optionAll.addEventListener("keydown", function (e) {
        toggleShowEvents(e)
    });
    optionDays.addEventListener("click", function (e) {
        toggleShowEvents(e)
    });
    optionDays.addEventListener("keydown", function (e) {
        toggleShowEvents(e)
    });
    optionMonths.addEventListener("click", function (e) {
        toggleShowEvents(e)
    });
    optionMonths.addEventListener("keydown", function (e) {
        toggleShowEvents(e)
    });

    function toggleShowEvents(e) {
        if (e.target.id === "option-days") {
            $eventListItemsAll.attr('aria-hidden', 'true');
            $eventListItemDays.attr('aria-hidden', 'false');
        }
        else if (e.target.id === "option-months") {
            $eventListItemsAll.attr('aria-hidden', 'true');
            $eventListItemMonths.attr('aria-hidden', 'false');
        }
        else {
            //Show all
            $eventListItemsAll.attr('aria-hidden', 'false');
        }
    }

    // Accessible dropdown event categories
    const catList = document.querySelector(".categories_container .dropdown__list");
    const catListContainer = document.querySelector(".categories_container .dropdown__list-container");
    const catDropdownArrow = document.querySelector(".categories_container .dropdown__arrow");
    const catListItems = document.querySelectorAll(".categories_container .dropdown__list-item");
    const catDropdownSelectedNode = document.querySelector(".categories_container #dropdown-cat__selected");
    const catListItemIds = [];

    catDropdownSelectedNode.addEventListener("click", function (e) {
        toggleListVisibilityCat(e)
    });
    catDropdownSelectedNode.addEventListener("keydown", function (e) {
        toggleListVisibilityCat(e)
    });
    catDropdownArrow.addEventListener("click", function (e) {
        toggleListVisibilityCat(e)
    });

    catListItems.forEach(function (item) {
        catListItemIds.push(item.id)
    });

    catListItems.forEach(function (item) {
        item.addEventListener("click", function (e) {
            setSelectedListItemCat(e);
            closeListCat();
        });

        item.addEventListener("keydown", function (e) {
            switch (e.keyCode) {
                case ENTER_KEY_CODE:
                    setSelectedListItemCat(e);
                    closeListCat();
                    return;

                case DOWN_ARROW_KEY_CODE:
                    focusNextListItemCat(DOWN_ARROW_KEY_CODE);
                    return;

                case UP_ARROW_KEY_CODE:
                    focusNextListItemCat(UP_ARROW_KEY_CODE);
                    return;

                case ESCAPE_KEY_CODE:
                    closeListCat();
                    return;

                default:
                    return;
            }
        });
    });

    function setSelectedListItemCat(e) {
        let selectedTextToAppend = document.createTextNode(e.target.innerText);
        catDropdownSelectedNode.innerHTML = null;
        catDropdownSelectedNode.appendChild(selectedTextToAppend);
    }

    function closeListCat() {
        catList.classList.remove("open");
        catDropdownArrow.classList.remove("expanded");
        catListContainer.setAttribute("aria-expanded", false);
    }

    function toggleListVisibilityCat(e) {
        let openDropDown =
            SPACEBAR_KEY_CODE.includes(e.keyCode) || e.keyCode === ENTER_KEY_CODE;

        if (e.keyCode === ESCAPE_KEY_CODE) {
            closeList();
        }

        if (e.type === "click" || openDropDown) {
            catList.classList.toggle("open");
            catDropdownArrow.classList.toggle("expanded");
            catListContainer.setAttribute(
                "aria-expanded",
                catList.classList.contains("open")
            );
        }

        if (e.keyCode === DOWN_ARROW_KEY_CODE) {
            focusNextListItemCat(DOWN_ARROW_KEY_CODE);
        }

        if (e.keyCode === UP_ARROW_KEY_CODE) {
            focusNextListItemCat(UP_ARROW_KEY_CODE);
        }
    }

    function focusNextListItemCat(direction) {
        const activeElementId = document.activeElement.id;
        if (activeElementId === "dropdown__selected") {
            document.querySelector("#" + catListItemIds[0]).focus();
        } else {
            const currentActiveElementIndex = catListItemIds.indexOf(
                activeElementId
            );
            if (direction === DOWN_ARROW_KEY_CODE) {
                const currentActiveElementIsNotLastItem =
                    currentActiveElementIndex < catListItemIds.length - 1;
                if (currentActiveElementIsNotLastItem) {
                    const nextListItemId = catListItemIds[currentActiveElementIndex + 1];
                    document.querySelector("#" + nextListItemId).focus();
                }
            } else if (direction === UP_ARROW_KEY_CODE) {
                const currentActiveElementIsNotFirstItem =
                    currentActiveElementIndex > 0;
                if (currentActiveElementIsNotFirstItem) {
                    const nextListItemId = catListItemIds[currentActiveElementIndex - 1];
                    document.querySelector("#" + nextListItemId).focus();
                }
            }
        }
    }

    // Dropdown Event Categories Show/Hide
    const dropdownCatOptions = document.querySelectorAll(".categories_container .dropdown__list-item");
    let eventCatListItemsAll = document.querySelectorAll("li.event");

    dropdownCatOptions.forEach(function (element) {
        element.addEventListener("click", function (e) {
            toggleShowEventsCat(e)
        });
        element.addEventListener("keydown", function (e) {
            toggleShowEventsCat(e)
        });
    });

    function toggleShowEventsCat(e) {
        let targetCatId = e.target.getAttribute("data-cat");

        eventCatListItemsAll.forEach(function (element) {
            if (element.classList.contains(targetCatId)) {
                element.setAttribute("aria-hidden", "false");
            }
            else if (targetCatId === "all") {
                element.setAttribute("aria-hidden", "false");
            }
            else {
                element.setAttribute("aria-hidden", "true");
            }
        });
    }

    // Desktop: Add correct aria hidden attr on events
    $('.event_sorters .event_sorter').on('click', function () {
        $('.event_list li.event').each(function () {
            if ($(this).is(':visible')) {
                $(this).attr('aria-hidden', 'false');
            } else {
                $(this).attr('aria-hidden', 'true');
            }
        });
    });
}

$('.event_sorter').click(function () {
    var self = $(this);
    if (self.hasClass('event_time')) {
        $('.event_time').removeClass('active');
    }
    if (self.hasClass('event_category')) {
        $('.event_category').removeClass('active');
    }

    self.addClass('active');
    var date = $('.event_time.active').data("date");
    var category = $('.event_category.active').data("tag");
    var events = $('li.event');
    events.hide();
    if (typeof date != 'undefined') {
        events = events.filter('.' + date);
    }
    if (typeof category != 'undefined') {
        events = events.filter('.' + category);
    }
    events.show();
});;
let epiForm = $(".op-epi-form");
let addUrl = "/DocumentOrder/AddToBasket";
let removeUrl = "/DocumentOrder/RemoveFromBasket";
let deleteUrl = "/DocumentOrder/RemoveAllFromBasket";
let productList = $("#op-basket");
let submitButton = $(".op-epi-form .FormSubmitButton");

if (epiForm.length >= 1) {
	if (typeof $$epiforms !== "undefined") {
		$$epiforms(document).ready(function myfunction() {
			$$epiforms(".EPiServerForms").on("formsNavigationNextStep", function (
				event,
				param1,
				param2
			) {
				updateFirstForm();
				$(".op-submit-button").toggle();
				$(".order-button").toggle();
				let epi = $(".op-epi-form").find("#__field_");
				epi.children(":not(button)").toggleClass("page2");
				let form2 = $('.FormStep[data-f-stepindex="1"]');
				form2.prepend('<div class="op-secondSlide"></div>');
				$(".page2 input:not(:checkbox)")
					.map(function (i) {
						if ($(this).val().length > 0) {
							if ($(this).prev().text().length > 0) {
								$(".op-secondSlide").append(
									"<li class='op-order-list-item'><b>" +
										$(this).prev().text() +
										"</b></li>"
								);
							}
							$(".op-secondSlide").append(
								"<li class='op-order-list-item'>" + $(this).val() + "</li>"
							);
						}
					})
					.get();
			});

			$$epiforms(".EPiServerForms").on("formsSubmitted", function (event) {
				if (event.isFinalizedSubmission) {
					$(window).scrollTop(0);
					$(".op-main-content").toggle();
					$(".op-submitted-form").toggle();
				}
			});
		});
	}

	getOrderBasket(function (basket) {
		if (basket.products.length > 0) {
			$(".op-form").toggle();
		} else {
			$(".message.hidden").toggleClass("hidden");
		}
	});

	var nav = $(".Form__NavigationBar");

	$('<div class="js-scroll-form op-submit-button"></div>').appendTo(nav);
	submitButton.appendTo(".op-submit-button");
	let epi = $(".op-epi-form").find("#__field_");
	setColumnsToAdressFormFields();
	setRadioButtonEventHandlers();
	$("#op-forms").hide();

	function getOrderBasket(callback) {
		return $.ajax({
			url: "/DocumentOrder/GetBasket",
			type: "GET",
			dataType: "json",
			success: function (result) {
				callback(result.documentOrderBasket);
			},
			error: function (result) {},
		});
	}
	function getTotalPrice() {
		$.ajax({
			url: "/DocumentOrder/CalculateTotalOrderPrice",
			type: "GET",
			dataType: "json",
			success: function (result) {
				$(".order-sum").html(
					"<b>Totalt:</b> " + result.documentOrderBasket.totalOrderPrice + " kr"
				);
			},
		});
	}
	function populateBasket() {
		var orderType = $("input[name=OrderType]:checked").val();
		var city = $("input[name=IsInStockholmRegion]:checked").val();
		if (orderType != null && city != null) {
			let isInStockholmRegion = city == "True";
			$.ajax({
				url: "/DocumentOrder/UpdateOrderInfo",
				type: "POST",
				dataType: "json",
				data: { orderType: orderType, isInStockholmRegion: isInStockholmRegion },
				success: function (result) {
					if (!$(".op-product").length > 0) {
						getOrderBasket(function (basket) {
							if (basket.products.length > 0) {
								$.each(basket.products, function (i, product) {
									$("#op-forms").slideDown();
									productList.prepend(
										"<li product-id=" +
											product.id +
											" class='op-order-list-item op-product'>" +
											'<div class="op-order-list-left">' +
											"<span>" +
											"<button product-id=" +
											product.id +
											" class='order-button add'><i class='icon-plus'></i></button>" +
											"<span product-id=" +
											product.id +
											" class='order-count'>" +
											product.amount +
											"</span>" +
											"<button product-id=" +
											product.id +
											" class='order-button remove'><i class='icon-minus'></i></button>" +
											"</span > " +
											"<p class='order-name'>" +
											product.name +
											"</p>" +
											"</div>" +
											'<div class="op-order-list-right">' +
											"<p class='order-price'>" +
											product.price +
											" kr</p>" +
											"<button product-id=" +
											product.id +
											" class='order-button delete'>" +
											'<img class="documentList-icon" src="/Static/img/slso-icon-trash.svg">' +
											"</button>" +
											"</div>" +
											"</li>" +
											'<li class="op-order-list-item op-item-seperator"></li>'
									);
								});
							} else {
								$("#op-forms").hide();
							}
						}).done(function () {
							setButtonEventHandlers();
						});
					}
					getTotalPrice();
				},
				error: function (result) {},
			});
		}
	}
	function updateOrderCount(update, id) {
		let productToUpdate = $(".order-count[product-id='" + id + "']");
		let number = parseInt(productToUpdate.html());

		if (update == addUrl) {
			productToUpdate.text(number + 1);
		} else {
			productToUpdate.text(number - 1);
		}
	}
	function postUpdatedCookie(clickedButton, url, deleteProduct) {
		let id = parseInt(clickedButton.getAttribute("product-id"));
		var ids = JSON.stringify([id]);
		$.ajax({
			contentType: "application/json",
			dataType: "json",
			data: ids,
			type: "POST",
			url: url,
			success: function (response) {
				if (deleteProduct) {
					removeProductFromList(id);
				} else {
					updateOrderCount(url, id);
					getTotalPrice();
				}
			},
			error: function (response) {},
		});
	}
	function setRadioButtonEventHandlers() {
		$("input[name='OrderType']").change(function () {
			populateBasket();
		});
		$("input[name='IsInStockholmRegion']").change(function () {
			populateBasket();
		});
	}

	$(".btnPrev").click(function (e) {
		updateFirstForm(e);
		$(window).scrollTop(0);
		$(".op-submit-button").toggle();
		$(".order-button").toggle();
		$(".op-secondSlide").remove();
		submitButton.show();

		epi.children(":not(button)").toggleClass("page2");
	});

	function updateFirstForm() {
		$("#op-radiobuttons")
			.find("p")
			.each(function (i) {
				if (!$(this).children("input").is(":checked") && !$(this).hasClass("bold")) {
					$(this).toggle();
				} else {
					$(this).children("input").toggle();
				}
			});
	}
	function setButtonEventHandlers() {
		$(".order-button.add").click(function (e) {
			postUpdatedCookie(this, addUrl);
		});
		$(".order-button.remove").click(function (e) {
			let id = this.getAttribute("product-id");
			let count = parseInt($(".order-count[product-id=" + id + "]").text());
			if (count > 1) {
				postUpdatedCookie(this, removeUrl);
			}
		});
		$(".order-button.delete").click(function (e) {
			postUpdatedCookie(this, deleteUrl, true);
		});
	}
	function clearOrders() {
		$(".op-order-list-item").slideUp();
	}
	function removeProductFromList(id) {
		$.when($(".op-product[product-id =" + id + "]").fadeOut("slow")).done(function () {
			$(".op-product[product-id =" + id + "]")
				.next(".op-item-seperator")
				.remove();
			getOrderBasket(function (basket) {
				if (basket.products.length > 0) {
					//                    $(".op-form").toggle();
				} else {
					$(".op-form").slideUp();
					$(".message.hidden").toggleClass("hidden");
				}
			});
		});

		getTotalPrice();
	}

	function setColumnsToAdressFormFields() {
		var formFields = $(".op-epi-form")
			.find("#__field_")
			.find('input[placeholder="Adress"], input[placeholder="Fakturaadress"]')
			.parent();

		$.each(formFields, function () {
			$(this).next().andSelf().wrapAll("<div class='op-form-columns' />");
		});
	}
}
;
(function () {
	if ("-ms-user-select" in document.documentElement.style && navigator.userAgent.match(/IEMobile\/10\.0/)) {
		var fileref = document.createElement("link");
		fileref.setAttribute("rel", "stylesheet");
		fileref.setAttribute("type", "text/css");
		fileref.setAttribute("href", "/Static/css/nokia.css");
		document.getElementsByTagName("head")[0].appendChild(fileref);
		$(".js .site_search").hide();
	}
})();


/**
* Utility to wrap the different behaviors between W3C-compliant browsers
* and IE when adding event handlers.
*
* param {Object} element Object on which to attach the event listener.
* param {string} type A string representing the event type to listen for
*     (e.g. load, click, etc.).
* param {function()} callback The function that receives the notification.
*/

function addListener(element, type, callback) {
	if (element.addEventListener) {
		element.addEventListener(type, callback);
	} else if (element.attachEvent) {
		element.attachEvent('on' + type, callback);
	}
}

$('a[href$=".pdf"]').each(function () {
	addListener(this, 'click', function () {
		ga('send', 'event', 'link', 'click', window.location.pathname + ' -> ' + $(this).attr('href'));
	});
});

// Moved from main.js line: 380
$('a[href^="http://"]').each(function () {
    if (typeof $(this).parent().attr('class') != 'undefined') {
        if ($(this).parent().attr('class').indexOf("leave_page_button") < 0)
            $(this).attr('target', '_blank');
	    addListener(this, 'click', function () {
		    ga('send', 'event', 'link', 'click', window.location.pathname + ' -> ' + $(this).attr('href'));
	    });
    }
});

$('.earthIcon').each(function () {
	addListener(this, 'blur', function () {
		if (!$('ul.ui-autocomplete').is(":focus") && !$('.language_dropdown').is(":focus") && !$('.earthIcon').is(":focus")) {
			$('.language_dropdown').autocomplete('close');
		}
	});
});;
