/* Minification failed. Returning unminified contents.
(395,15-16): run-time error JS1010: Expected identifier: .
(395,15-16): run-time error JS1195: Expected expression: .
 */
/*!
 * Accordion v2.8.0
 * Simple accordion created in pure Javascript.
 * https://github.com/michu2k/Accordion
 *
 * Copyright 2017-2019 Michał Strumpf
 * Published under MIT License
 */

(function (window) {

    'use strict';

    let uniqueId = 0;

    /**
     * Core
     * @param {string} selector = container in which the script will be initialized
     * @param {object} userOptions = options defined by user
     */
    const Accordion = function (selector, userOptions) {
        const _this = this;

        const ac = {
            /**
             * Init accordion
             */
            init: function () {
                // Defaults 
                const defaults = {
                    duration: 600, // animation duration in ms {number}
                    itemNumber: 0, // item number which will be shown {number}
                    aria: true, // add ARIA elements to the HTML structure {boolean}
                    closeOthers: false, // show only one element at the same time {boolean}
                    showItem: false, // always show element that has itemNumber number {boolean}
                    elementClass: 'ac', // element class {string}
                    questionClass: 'ac-q', // question class {string}
                    answerClass: 'ac-a', // answer class {string}
                    targetClass: 'ac-target', // target class {string}
                    onToggle: function () { }, // calls when toggling an item {function}
                    delay: 200 //Delay before start in ms {number}
                };

                // Break the array with the selectors
                if (Array.isArray(selector)) {
                    if (selector.length) {
                        selector.map(function (single) { new Accordion(single, userOptions) });
                    }

                    return false;
                }

                this.options = extendDefaults(defaults, userOptions);
                this.container = document.querySelector(selector);
                this.elements = this.container.querySelectorAll('.' + this.options.elementClass);
                const aria = this.options.aria;
                const showItem = this.options.showItem;
                const itemNumber = this.options.itemNumber;

                // Set ARIA
                if (aria) {
                    this.container.setAttribute('role', 'tablist');
                }

                // For each element
                for (let i = 0; i < this.elements.length; i++) {
                    const element = this.elements[i];

                    // When JS is enabled, add the class to the elements
                    element.classList.add('js-enabled');

                    this.hideElement(element);
                    this.setTransition(element);
                    this.generateID(element);

                    // Set ARIA
                    if (aria) {
                        this.setARIA(element);
                    }
                }

                // Show accordion element when script is loaded
                if (showItem) {
                    let el = this.elements[0]; // Default value
                    if (typeof itemNumber === 'number' && itemNumber < this.elements.length) {
                        el = this.elements[itemNumber];
                    }

                    this.toggleElement(el, false);
                }

                _this.attachEvents();
            },

            /**
             * Set transition 
             * @param {object} element = current element
             */
            setTransition: function (element) {
                const duration = this.options.duration;
                const answerClass = this.options.answerClass;
                const el = element.querySelector('.' + answerClass);
                const transition = isWebkit('transition');

                el.style[transition] = duration + 'ms';
            },

            /**
             * Generate unique ID for each element
             * @param {object} element = list item
             */
            generateID: function (element) {
                element.setAttribute('id', "ac-" + uniqueId);
                uniqueId++;
            },

            /**
             * Create ARIA
             * @param {object} element = list item
             */
            setARIA: function (element) {
                const questionClass = this.options.questionClass;
                const answerClass = this.options.answerClass;
                const question = element.querySelector('.' + questionClass);
                const answer = element.querySelector('.' + answerClass);

                question.setAttribute('role', 'tab');
                question.setAttribute('aria-expanded', 'false');
                answer.setAttribute('role', 'tabpanel');
            },

            /**
             * Update ARIA
             * @param {object} element = list item
             * @param {boolean} value = value of the attribute
             */
            updateARIA: function (element, value) {
                const questionClass = this.options.questionClass;
                const question = element.querySelector('.' + questionClass);
                question.setAttribute('aria-expanded', value);
            },

            /**
             * Show specific accordion element
             * @param {object} e = event
             */
            callSpecificElement: function (e) {
                const target = e.target;
                const questionClass = this.options.questionClass;
                const targetClass = this.options.targetClass;
                const closeOthers = this.options.closeOthers;
                for (let i = 0; i < this.elements.length; i++) {
                    if (this.elements[i].contains(target)) {

                        // Check if target has one of the classes
                        if (target.className.match(questionClass) || target.className.match(targetClass)) {
                            e.preventDefault();

                            if (closeOthers) {
                                this.closeAllElements(i);
                            }

                            this.toggleElement(this.elements[i], true);
                        }

                        break;
                    }
                }
            },

            /**
             * Hide element
             * @param {object} element = list item
             */
            hideElement: function (element) {
                const answerClass = this.options.answerClass;
                const answer = element.querySelector('.' + answerClass);
                answer.style.height = 0;
            },

            /** 
             * Toggle current element
             * @param {object} element = current element
             * @param {boolean} animation = turn on animation
             */
            toggleElement: function (element, animation) {
                const answerClass = this.options.answerClass;
                const aria = this.options.aria;
                const onToggle = this.options.onToggle;
                const answer = element.querySelector('.' + answerClass);
                let height;
                if (!element.classList.contains('is-active')) {
                    let currentHeight = answer.style.height;
                    answer.style.height = 'auto';
                    height = Math.max(answer.scrollHeight, answer.offsetHeight);
                    answer.style.height = currentHeight;
                } else {
                    height = Math.max(answer.scrollHeight, answer.offsetHeight);
                }
                let ariaValue;

                // Toggle class
                element.classList.toggle('is-active');

                // Open element without animation
                if (!animation) {
                    answer.style.height = 'auto';
                }

                // Set height
                if (parseInt(answer.style.height) > 0) {
                    ariaValue = false;

                    requestAnimationFrame(function () {
                        answer.style.height = 0;
                    });
                } else {
                    ariaValue = true;

                    requestAnimationFrame(function () {
                        answer.style.height = height + 'px';
                    });

                }

                // Update ARIA
                if (aria) {
                    this.updateARIA(element, ariaValue);
                }

                // Call onToggle function
                if (animation) {
                    onToggle(element, this.elements);
                }
            },

            /**
             * Close all elements without the current element
             * @param {number} current = current element
             */
            closeAllElements: function (current) {
                const aria = this.options.aria;
                const length = this.elements.length;

                for (let i = 0; i < length; i++) {
                    if (i != current) {
                        const element = this.elements[i];

                        // Remove active class
                        if (element.classList.contains('is-active')) {
                            element.classList.remove('is-active');
                        }

                        // Update ARIA
                        if (aria) {
                            this.updateARIA(element, false);
                        }

                        this.hideElement(element);
                    }
                }
            },

            /**
             * Resize handler
             */
            resizeHandler: function () {
                let height, answer;
                const elementClass = this.options.elementClass;
                const answerClass = this.options.answerClass;
                const activeElement = this.container.querySelectorAll('.' + elementClass + '.is-active');

                // Change element height, when window is resized and when element is active
                for (let i = 0; i < activeElement.length; i++) {
                    answer = activeElement[i].querySelector('.' + answerClass);

                    // Set to auto and get new height
                    requestAnimationFrame(function () {
                        answer.style.height = 'auto';
                        height = Math.max(answer.scrollHeight, answer.offsetHeight);

                        requestAnimationFrame(function () {
                            answer.style.height = height + 'px';
                        });
                    });
                }
            },

            /**
             * Click handler
             * @param {object} e = event
             */
            clickHandler: function (e) {
                const delay = this.options.delay;
                var self = this; //bind instance of this due to setTimeout(function) set to window(default)
                setTimeout(function () {
                    self.callSpecificElement(e)
                }, delay);
            },

            /**
             * Keydown handler
             * @param {object} e = event
             */
            keydownHandler: function (e) {
                const ENTER = 13;
                if (e.keyCode === ENTER) {
                    const delay = this.options.delay;
                    var self = this;
                    setTimeout(function () {
                        self.callSpecificElement(e)
                    }, delay);
                }
            }
        };

        /**
         * Attach events
         */
        this.attachEvents = function () {
            const _this = ac;

            _this.clickHandler = _this.clickHandler.bind(_this);
            _this.keydownHandler = _this.keydownHandler.bind(_this);
            _this.resizeHandler = _this.resizeHandler.bind(_this);

            _this.container.addEventListener('click', _this.clickHandler);
            _this.container.addEventListener('keydown', _this.keydownHandler);
            window.addEventListener('resize', _this.resizeHandler);
        };

        /**
         * Detach events
         */
        this.detachEvents = function () {
            const _this = ac;

            _this.container.removeEventListener('click', _this.clickHandler);
            _this.container.removeEventListener('keydown', _this.keydownHandler);
            window.removeEventListener('resize', _this.resizeHandler);
        };

        /**
         * Get supported property and add webkit prefix if needed
         * @param {string} property = property name
         * @return {string} property = property with optional webkit prefix
         */
        const isWebkit = function (property) {
            if (typeof document.documentElement.style[property] === 'string') {
                return property;
            }

            property = capitalizeFirstLetter(property);
            property = "webkit" + property;

            return property;
        }

        /**
         * Capitalize the first letter in the string
         * @param {string} string = string
         * return {string} string = changed string
         */
        const capitalizeFirstLetter = function (string) { string.charAt(0).toUpperCase() + string.slice(1); };

        /** 
         * Extend defaults
         * @param {object} defaults = defaults options defined in script
         * @param {object} properties = options defined by user
         * @return {object} defaults = modified options
         */
        const extendDefaults = function (defaults, properties) {
            for (let property in properties) {
                defaults[property] = properties[property];
            }

            return defaults;
        }

        /**
         * RequestAnimationFrame support
         */
        window.requestAnimationFrame = (function () {
            return window.requestAnimationFrame ||
                window.webkitRequestAnimationFrame ||
                function (callback) {
                    window.setTimeout(callback, 1000 / 60);
                };
        })();

        ac.init();
    }

    if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
        module.exports = Accordion;
    } else {
        window.Accordion = Accordion;
    }

})(window);;
$(function() {
	var $typeFilter = $('#analysis-type-filter');

	if($typeFilter.length <= 0)
		return;

	var $quarterFilter = $('#analysis-quarter-filter');
    var $yearFilter = $('#analysis-year-filter');
    var $form = $('#analysis-search-form');

    var useTags = $form.data('useTags') == true;
    var filters = [];

	var sortByName = function (a, b) {
		if (a.Name < b.Name) return -1;
		if (a.Name > b.Name) return 1;
		return 0;
	};

	var sortByNameDescending = function (a, b) {
		if (a.Name < b.Name) return 1;
		if (a.Name > b.Name) return -1;
		return 0;
    };

    var updateFilters = function (facet, value) {
        for (var i = 0, length = filters.length; i < length; ++i) {
            if (filters[i].Name == facet) {
                for (var j = 0, jLength = filters[i].Values.length; j < jLength; ++j) {
                    if (filters[i].Values[j].Value == value) {
                        filters[i].Values[j].Selected = !filters[i].Values[j].Selected;
                    } else {
                        filters[i].Values[j].Selected = false;
                    }
                }

                break;
            }
        }
    };

	var handleSelectFilter = function(facetList, $filterContainer, ascending) {
        $filterContainer.empty();
		
		facetList.Values = facetList.Values.sort(ascending ? sortByName : sortByNameDescending);

		for (var i = 0, length = facetList.Values.length; i < length; ++i) {
            var value = facetList.Values[i];

            var text = facetList.Name === 'Quarter' && value.Name === 'year' ? 'Hel&aring;rs' : value.Name + (facetList.Name === 'Quarter' ? '. kvartal' : '');
			
			$filterContainer.append('<option value="' + value.Value + '"' + (value.Selected ? ' selected' : '') + '>' + text + '</option>');
		}
    };

    var removeOldResults = function () {
        sibling = $form.next();

        while (sibling.length > 0) {
            sibling.remove();

            sibling = $form.next();
        }
    };

    var appendHit = function (hit) {
        $('<div class="analysis">' +
            '<div class="card card--border card--analysis card--statistics card--columns">' +
                '<div class="card__column">' +
                    '<h2 class="text--left">' + hit.Title + '</h2>' +
                    '<p>' + hit.Manchet + '</p>' +
                    '<a href="' + hit.Link + '">L&aelig;s mere om ' + hit.Title + '</a>' +
                '</div>' +
                (hit.ImageUrl ? '<div class="card__column">' +
                    '<figure>' +
                        '<img src="' + hit.ImageUrl + '" alt="' + hit.Title + '">' +
                    '</figure>' +
                '</div>' : '') +
            '</div>' +
        '</div>').insertAfter($form);
    };
    
    var handleSearchResult = function (data, firstSearch) {
        removeOldResults();

       var firstSearchResult = data.Hits[0];

        for (var i = 0, length = data.Hits.length; i < length; ++i) {
            if (firstSearch && (firstSearchResult.Quarter !== data.Hits[i].Quarter || firstSearchResult.Year !== data.Hits[i].Year))
                continue;

            appendHit(data.Hits[i]);
        }

        //Insert help message if there weren't any search results
        if (length <= 0) {
            $('<div class="analysis">' +
                '<div class="card card--columns">' +
                    '<div class="card__column">' +
                        '<h2 class="text--left">Der er ingen artikler med de valgte s&oslash;gekriterier</h2>' +
                        '<p>V&aelig;lg venligst en anden kombination</p>' +
                    '</div>' +
                '</div>' +
            '</div>').insertAfter($form);
        }

        if (data.Facets) {
            for (var j = 0, jLength = data.Facets.length; j < jLength; ++j) {
                var facet = data.Facets[j];

                if (firstSearch) {
                    for (var k = 0, kLength = facet.Values.length; k < kLength; ++k) {
                        switch (facet.Name) {
                            case 'Year':
                                if (firstSearchResult.Year === facet.Values[k].Name)
                                    facet.Values[k].Selected = true;
                                break;
                            case 'Quarter':
                                if (firstSearchResult.Quarter === facet.Values[k].Name)
                                    facet.Values[k].Selected = true;
                                break;
                            case 'DocumentType':
                                if (useTags)
                                    break;
                                if (firstSearchResult.DocumentType === facet.Values[k].Name)
                                    facet.Values[k].Selected = true;
                                break;
                            case 'SearchTags':
                                if (!useTags)
                                    break;
                                if (firstSearchResult.SearchTags.indexOf(facet.Values[k].Name) >= 0)
                                    facet.Values[k].Selected = true;
                                break;
                        }
                    }

                    switch (facet.Name) {
                        case 'Year':
                            handleSelectFilter(facet, $yearFilter, false);
                            break;
                        case 'Quarter':
                            handleSelectFilter(facet, $quarterFilter, true);
                            break;
                        case 'DocumentType':
                            if (useTags)
                                break;
                            handleSelectFilter(facet, $typeFilter, true);
                            break;
                        case 'SearchTags':
                            if (!useTags)
                                break;
                            handleSelectFilter(facet, $typeFilter, true);
                            break;
                    }
                }
            }
        }

        if (firstSearch)
            filters = data.Facets;
    };

    var handleSearch = function (data) {
        handleSearchResult(data, false);
    };

    var handleFirstSearch = function (data) {
        handleSearchResult(data, true);
    };

    var performSearch = function () {
        SearchHelper.performStatisticsPageSearch(null, 1, 10, null, useTags ? $typeFilter.val() : null, filters, false, 'Date', 'Descending', handleSearch);
    };

    var firstSearch = function () {
        SearchHelper.performStatisticsPageSearch(null, 1, 10, null, null, null, true, 'Date', 'Descending', handleFirstSearch);
    };

    firstSearch();

    $yearFilter.on('change', function () {
        updateFilters('Year', $yearFilter.val());

        performSearch();
    });

    $typeFilter.on('change', function () {
        if (!useTags)
            updateFilters('DocumentType', $typeFilter.val());
        else
            updateFilters('SearchTags', $typeFilter.val());

        performSearch();
    });

    $quarterFilter.on('change', function () {
        updateFilters('Quarter', $quarterFilter.val());

        performSearch();
    });
});;
$(function() {
    var $typeFilter = $('#document-type-2-filter');

	if($typeFilter.length <= 0)
		return;

    var $yearFilter = $('#document-year-2-filter');
    var $queryInput = $('#document-query-2');
    var $form = $('#document-search-2-form');

    var filters = [];

	var sortByName = function (a, b) {
		if (a.Name < b.Name) return -1;
		if (a.Name > b.Name) return 1;
		return 0;
	};

	var sortByNameDescending = function (a, b) {
		if (a.Name < b.Name) return 1;
		if (a.Name > b.Name) return -1;
		return 0;
    };

    var updateFilters = function (facet, value) {
        for (var i = 0, length = filters.length; i < length; ++i) {
            if (filters[i].Name == facet) {
                for (var j = 0, jLength = filters[i].Values.length; j < jLength; ++j) {
                    if (filters[i].Values[j].Value == value) {
                        filters[i].Values[j].Selected = !filters[i].Values[j].Selected;
                    } else {
                        filters[i].Values[j].Selected = false;
                    }
                }

                break;
            }
        }
    };

	var handleSelectFilter = function(facetList, $filterContainer, ascending) {
        $filterContainer.empty();
		
        facetList.Values = facetList.Values.sort(ascending ? sortByName : sortByNameDescending);
        
        $filterContainer.append('<option value="">' + (facetList.Name === 'YearHistogram' ? '&Aring;r' : 'Type') + '</option>');

		for (var i = 0, length = facetList.Values.length; i < length; ++i) {
            var value = facetList.Values[i];
			
			$filterContainer.append('<option value="' + value.Value + '"' + (value.Selected ? ' selected' : '') + '>' + value.Name + '</option>');
		}
    };

    var removeOldResults = function () {
        sibling = $form.next();

        while (sibling.length > 0) {
            sibling.remove();

            sibling = $form.next();
        }
    };

    var appendHit = function (hit) {
        $('<div class="analysis">' +
            '<div class="card card--columns">' +
                '<div class="card__column">' +
                    '<h2 class="text--left">' + hit.Title + '</h2>' +
                    '<p>' + hit.Manchet + '</p>' +
                    '<a href="' + hit.Link + '">L&aelig;s mere om ' + hit.Title + '</a>' +
                '</div>' +
                (hit.ImageUrl ? '<div class="card__column">' +
                    '<figure>' +
                        '<img src="' + hit.ImageUrl + '" alt="' + hit.Title + '">' +
                    '</figure>' +
                '</div>' : '') +
            '</div>' +
        '</div>').insertAfter($form);
    };
    
    var handleSearchResult = function (data, firstSearch) {
        removeOldResults();

        var firstSearchResult = data.Hits[0];
        
        for (var i = 0, length = data.Hits.length; i < length; ++i) {
            if (firstSearch && (firstSearchResult.Quarter !== data.Hits[i].Quarter || firstSearchResult.Year !== data.Hits[i].Year))
                continue;

            appendHit(data.Hits[i]);
        }

        //Insert help message if there weren't any search results
        if (length <= 0) {
            $('<div class="analysis">' +
                '<div class="card card--columns">' +
                    '<div class="card__column">' +
                        '<h2 class="text--left">Der er ingen artikler med de valgte s&oslash;gekriterier</h2>' +
                        '<p>V&aelig;lg venligst en anden kombination</p>' +
                    '</div>' +
                '</div>' +
            '</div>').insertAfter($form);
        }

        if (!firstSearch)
            return;

		for (var j = 0, jLength = data.Facets.length; j < jLength; ++j) {
            var facet = data.Facets[j];

            switch (facet.Name) {
                case 'YearHistogram':
                    handleSelectFilter(facet, $yearFilter, false);
                    break;
                case 'SearchTags':
                    handleSelectFilter(facet, $typeFilter, true);
                    break;
            }
		}

        filters = data.Facets;
    };

    var handleSearch = function (data) {
        handleSearchResult(data, false);
    };

    var handleFirstSearch = function (data) {
        handleSearchResult(data, true);
    };

    var performSearch = function () {
        SearchHelper.performAnalysisSearch($queryInput.val(), $typeFilter.val(), $yearFilter.val(), handleSearch);
    };

    var firstSearch = function () {
        SearchHelper.performAnalysisSearch($queryInput.val(), $typeFilter.val(), $yearFilter.val(), handleFirstSearch);
    };

    firstSearch();

    $yearFilter.on('change', function () {
        updateFilters('YearHistogram', $yearFilter.val());

        performSearch();
    });

    $typeFilter.on('change', function () {
        updateFilters('DocumentType', $typeFilter.val());

        performSearch();
    });

    var queryTimeout;

    $queryInput.on('keyup touchend', function () {
        clearTimeout(queryTimeout);

        queryTimeout = setTimeout(performSearch, 300);
    });
});;
$(function () {
    var $documentTypeFilter = $('#area-page-filter-document-type');

    if ($documentTypeFilter.length <= 0)
        return;

    var $searchForm = $('#area-page-search');
    var $loadMoreButton = $('#area-page-load-more-button');
    var $searchResults = $('#area-page-search--results');

    var filters = [];
    var page = 1;
    var pageSize = 4;
    var pathId = $searchForm.data('pageId');

    var updateFilter = function (value) {
        for (var i = 0, length = filters.length; i < length; ++i) {
            if (filters[i].Name == 'DocumentType') {
                for (var j = 0, jLength = filters[i].Values.length; j < jLength; ++j) {
                    if (filters[i].Values[j].Value == value) {
                        filters[i].Values[j].Selected = !filters[i].Values[j].Selected;
                    } else {
                        filters[i].Values[j].Selected = false;
                    }
                }

                break;
            }
        }
    };

    var handleFacets = function (facets) {
        if ($documentTypeFilter.children().length > 0)
            return;

        filters = facets;

        for (var i = 0, length = facets.length; i < length; ++i) {
            var facet = facets[i];

            if (facet.Name !== 'DocumentType')
                continue;

            $documentTypeFilter.empty();

            if (facet.Values.length <= 1) {
                $documentTypeFilter.hide();
                return;
            } else {
                $documentTypeFilter.show();
            }

            $documentTypeFilter.append('<option value="">Type</option>');

            for (var j = 0, jLength = facet.Values.length; j < jLength; ++j) {
                var value = facet.Values[j];

                $documentTypeFilter.append('<option value="' + value.Value + '"' + (value.Selected ? ' selected' : '') + '>' + value.Name + ' (' + value.Count + ')</option>');
            }
        }
    };

    var removeSearchResults = function () {
        $searchResults.empty();
    };

    var handleResults = function (hits) {
        for (var i = 0, length = hits.length; i < length; ++i) {
            var hit = hits[i];

            $searchResults.append(
                '<li class="grid__loading" style="opacity: 1;">' +
                '<a href="' + hit.Link + '">' +
                '<div class="search--results__right">' +
                (hit.ImageUrl ? '<img src="' + hit.ImageUrl + '" />' : '') +
                '</div>' +
                '<div class="search--results__left">' +
                '<p class="preheader">' + hit.Category + '</p>' +
                '<h2>' + hit.Title + '</h2>' +
                '<div class="postheader">' +
                '<p class="postheader__date">' + hit.CreatedDate + '</p>' +
                (hit.DocumentType ? '<p class="postheader--type">' + hit.DocumentType + '</p>' : '') +
                '</div>' +
                '</div>' +
                '</a>' +
                '</li> ');
        }
    };

    var handleResponse = function (data) {
        handleFacets(data.Facets);

        handleResults(data.Hits);

        if (data.TotalHits > page * pageSize)
            $loadMoreButton.show();
        else
            $loadMoreButton.hide();
    };

    var performSearch = function () {
        SearchHelper.performDetailedPageSearch(null, page, pageSize, null, null, pathId, null, filters, 'Date', 'Descending', true, true, true, handleResponse);
    };

    $documentTypeFilter.on('change', function () {
        updateFilter($documentTypeFilter.val());

        removeSearchResults();

        page = 1;

        performSearch();
    });

    $loadMoreButton.on('click', function (e) {
        ++page;

        performSearch();

        e.preventDefault();
        return false;
    });


    //Do initial search
    performSearch();
});;
$(function () {
    var $searchTable = $('#document-search-table');

    if ($searchTable.length <= 0)
        return;

    var $searchQuery = $('#document-search-query');
    var $productNameFacets = $('#document-search-headline-before-product-filters');
    var $topicFilter = $('#document-search-topic-filter');
    var $yearFilter = $('#document-search-year-filter');
    var $monthFilter = $('#document-search-month-filter');
    var $loadMoreButton = $('#document-search-load-more-button');

    var query = $searchQuery.val();
    var filters = null;
    var page = 1;
    var pageSize = 4;
    var orderBy = 'Relevance';
    var orderByDirection = 'Ascending';

    var dontUpdateYearFilters = false;
    var dontUpdateMonthFilters = false;

    var updateFilters = function (facet, value) {
        for (var i = 0, length = filters.length; i < length; ++i) {
            if (filters[i].Name == facet) {
                for (var j = 0, jLength = filters[i].Values.length; j < jLength; ++j) {
                    if (filters[i].Values[j].Value == value) {
                        filters[i].Values[j].Selected = !filters[i].Values[j].Selected;
                    } else {
                        filters[i].Values[j].Selected = false;
                    }
                }

                break;
            }
        }
    };

    var handleProductNameFacet = function (facetList) {
        $('[id^=product-name-]').off('change');

        $('input[type="radio"]', $productNameFacets.parent()).remove();
        $('label', $productNameFacets.parent()).remove();

        var noSelected = true;

        //Going the other direction as the others because it inserts the last entry first
        for (var i = facetList.Values.length - 1; i >= 0; --i) {
            var value = facetList.Values[i];

            $('<input type="radio" name="productName" id="product-name-' + value.Value.replace(' ', '-') + '" value="' + value.Value + '"' + (value.Selected ? ' checked' : '') + ' />' +
                '<label for="product-name-' + value.Value.replace(' ', '-') + '">' + value.Name + '</label>').insertAfter($productNameFacets);

            if (value.Selected)
                noSelected = false;
        }

        $('<input type="radio" name="productName" id="product-name-all" value=""' + (noSelected ? ' checked' : '') + ' />' +
            '<label for="product-name-all">Alle</label>').insertAfter($productNameFacets);

        $('[id^=product-name-]').on('change', function (e) {
            updateFilters('ProductName', $(e.target).val());

            page = 1;
            clearResults();

            performSearch();
        });
    };

    var handleTopicFacet = function (facetList) {
        $topicFilter.empty();

        facetList.Values = facetList.Values.sort(function (a, b) {
            if (a.Name < b.Name) return -1;
            if (a.Name > b.Name) return 1;
            return 0;
        });

        $topicFilter.append('<option>Emne</option>');

        for (var i = 0, length = facetList.Values.length; i < length; ++i) {
            var value = facetList.Values[i];

            $topicFilter.append('<option value="' + value.Value + '"' + (value.Selected ? ' selected' : '') + '>' + value.Name + '</option>');
        }
    };

    var handleYearFacet = function (facetList) {
        if (!dontUpdateYearFilters) {
            $yearFilter.empty();
            $yearFilter.append('<option value="">År</option>');
        }

        var noSelected = true;

        for (var i = 0, length = facetList.Values.length; i < length; ++i) {
            var value = facetList.Values[i];

            if (!dontUpdateYearFilters)
                $yearFilter.append('<option value="' + value.Value + '"' + (value.Selected ? ' selected' : '') + '>' + value.Name + '</option>');

            if (value.Selected)
                noSelected = false;
        }

        if (noSelected)
            $monthFilter.attr('disabled', 'true');
        else
            $monthFilter.removeAttr('disabled');

        dontUpdateYearFilters = false;
    };

    var handleMonthFacet = function (facetList) {
        if (dontUpdateMonthFilters) {
            dontUpdateMonthFilters = false;
            return;
        }

        $monthFilter.empty();
        $monthFilter.append('<option value="">Måned</option>');

        for (var i = 0, length = facetList.Values.length; i < length; ++i) {
            var value = facetList.Values[i];

            $monthFilter.append('<option value="' + value.Value + '"' + (value.Selected ? ' selected' : '') + '>' + value.Name + '</option>');
        }
    };

    var handleResponse = function (data) {
        for (var i = 0, length = data.Hits.length; i < length; ++i) {
            var hit = data.Hits[i];

            $searchTable.append(
                '<tbody>' +
                    '<tr>' +
                        '<td class="fold"></td>' +
                        '<td>' + hit.Title + '</td>' +
                        '<td>' + hit.ProductName + '</td>' +
                        '<td>' + hit.Topic + '</td>' +
                        '<td>' + hit.CreatedDate + '</td>' +
                        '<td><img src="/Static/img/icon__' + hit.FileType + '.svg" /></td>' +
                        '<td><a href="' + hit.Link + '" class="btn" download="' + hit.FileName + '">Download</a></td>' +
                    '</tr>' +
                    '<tr class="foldable">' +
                        '<td colspan="3">' + hit.Description + '</td>' +
                    '</tr>' +
                '</tbody>'
            );
        }

        for (var j = 0, jLength = data.Facets.length; j < jLength; ++j) {
            var facet = data.Facets[j];

            switch (facet.Name) {
                case 'ProductName':
                    handleProductNameFacet(facet);
                    break;
                case 'Topic':
                    handleTopicFacet(facet);
                    break;
                case 'Year':
                    handleYearFacet(facet);
                    break;
                case 'Month':
                    handleMonthFacet(facet);
                    break;
            }
        }

        filters = data.Facets;

        $('table .fold').off('click');

        $('table .fold').on('click', function (e) {
            e.preventDefault();

            $(this).closest('tbody').toggleClass('open');
            $(this).closest('tbody').find('.foldable').slideToggle('fast');
        });

        if (page * pageSize < data.TotalHits)
            $loadMoreButton.show();
        else
            $loadMoreButton.hide();
    };

    var clearResults = function () {
        $('tbody', $searchTable).remove();
    };

    var changeTimeout;

    $searchQuery.on('keyup', function () {
        clearTimeout(changeTimeout);
        changeTimeout = setTimeout(function () {
            page = 1;
            query = $searchQuery.val();
            clearResults();

            performSearch();
        }, 300);
    });

    var performSearch = function () {
        var year = $yearFilter.val();
        var month = $monthFilter.val();

        SearchHelper.performDocumentSearch(query, filters, page, pageSize, year, month, orderBy, orderByDirection, handleResponse);
    };

    $topicFilter.on('change', function () {
        updateFilters('Topic', $topicFilter.val());
        page = 1;
        clearResults();

        performSearch();
    });

    $yearFilter.on('change', function () {
        dontUpdateYearFilters = true;
        page = 1;
        $monthFilter.val('');
        clearResults();

        performSearch();
    });

    $monthFilter.on('change', function () {
        dontUpdateMonthFilters = true;
        dontUpdateYearFilters = true;
        page = 1;
        clearResults();

        performSearch();
    });

    $('thead .sortable', $searchTable).on('click', function (e) {
        var $target = $(e.target);
        var year = $yearFilter.val();
        var month = $monthFilter.val();

        orderByDirection = $target.hasClass('sorttable_sorted_reverse') ? 'Descending' : 'Ascending';
        orderBy = $target.data('sortBy');

        clearResults();

        SearchHelper.performDocumentSearch(query, filters, 1, pageSize * page, year, month, orderBy, orderByDirection, handleResponse);
    });

    $('thead:not(.sortable)', $searchTable).on('click', function (e) {
        var $target = $(e.target);

        $('span', $target).remove();

        $target.removeClass('sorttable_sorted_reverse').removeClass('sorttable_sorted');

        if (orderBy !== 'Relevance') {
            var $td = $('thead td[data-sort-by="' + orderBy + '"]', $searchTable);

            var spanId = orderByDirection === 'Ascending' ? 'sorttable_sortfwdind' : 'sorttable_sortrevind';
            var spanContent = orderByDirection === 'Ascending' ? '▾' : '▴';

            $td.addClass(orderByDirection === 'Ascending' ? 'sorttable_sorted' : 'sorttable_sorted_reverse');
            $td.append('<span id="' + spanId + '">&nbsp;' + spanContent + '</span>');
        }
    });

    $loadMoreButton.on('click', function (e) {
        ++page;
        performSearch();

        e.preventDefault();
        return false;
    });

    clearResults();
    performSearch();
});;
$(function () {
    var $mainTabsContainer = $('#group-page-tabs');

    if ($mainTabsContainer.length <= 0)
        return;

    var $mainTabs = $('#group-page-tabs > .tabs__list > .tabs__header');
    var $subTabs = $('.subgroups > .tabs__list > .tabs__header', $mainTabsContainer);
    var $ieContainers = $('.ie-img-middle');
    var $ieImg = $('img', $ieContainers);

    var $singleGroups = $('div:has(>.tabs--subgroup):only-child');

    $('.tabs--subgroup', $singleGroups).removeClass('tabs__item').removeAttr('aria-expanded');

    var updateHeights = function () {
        $.fn.matchHeight._update();

        if (isIE()) {
            $ieImg.css('position', '');
            $ieImg.css('top', '');
            $ieImg.css('transform', '');

            var $visibleImg = $('.ie-img-middle img:visible');

            if ($visibleImg.length > 1) {
                setTimeout(function () {
                    $visibleImg.css('position', 'relative');
                    $visibleImg.css('top', '50%');
                    $visibleImg.css('transform', 'translateY(-50%)');
                });
            } else {
                $ieContainers.css('height', '');
            }
        }
    };

    //Make the cards match height when opened
    $subTabs.on('click', updateHeights);

    //Opens the first subtab when a main tab has been opened
    $mainTabs.on('click', function (e) {
        var $header = $('a', e.currentTarget);

        var $target = $($header.attr('href'));

        var $firstSubTab = $('.subgroups .tabs__header:first-child a', $target);

        if ($firstSubTab.length > 0)
            $firstSubTab.trigger('click');
        else
            updateHeights();
    });

    if (isIE()) {
        $ieContainers.matchHeight({ byRow: false });
    }

    if ($mainTabs.length > 0) {
        //Open the first main tab on load
        $('a', $mainTabs[0]).trigger('click');
    }
});;
var isIE = function () {
    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE ");

    return msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./);
};;
$(function () {
    var fixTabImages = function () {
        var $pictures = $('#molounge .card__inner picture');

        if (!$pictures)
            return;

        var maxImageHeight = 0;
        var i, length;

        for (i = 0, length = $pictures.length; i < length; ++i) {
            maxImageHeight = Math.max(maxImageHeight, $('img', $pictures[i]).height());
        }

        for (i = 0, length = $pictures.length; i < length; ++i) {
            $($pictures[i]).css('height', (maxImageHeight + 32) + 'px');
        }
    };

    if (isIE()) {
        //Put stuff in here when finished testing
        fixTabImages();
    }
});;
$(function () {
    //Removes the hardcoded sizes inserted by EPiServer rich text editor
    $('img[width]').removeAttr('width');
    $('img[height]').removeAttr('height');
});;
$(function () {
    var $itemGrid = $('#latest-item-block-grid');
    var $latestItemBlockDiv = $('#latest-item-block-grid')
    var rootId = $latestItemBlockDiv.data("root-id")
    //This is a check to see if we're on the search page. Don't do anything if not
    if ($itemGrid.length <= 0)
        return;

    var $loadMoreButton = $('#latest-items-block-load-more-button');

    //variables needed for search
    var page = 1;
    var pageSize = 4;
    var orderBy = 'Date';
    var orderByDirection = 'Descending';

    var documentType = null;
    var typeInput = $("#LastItemsDocumentType");
    if (typeInput) {
        documentType = typeInput.val() === "0" ? null : typeInput.val();
    }
    
    var handleSearchResponse = function (response) {
        //Don't show the button, if there are no more search results to fetch
        if (page * pageSize >= response.TotalHits)
            $loadMoreButton.hide();
        else
            $loadMoreButton.show();
        
        let time1 = 0;
        let easeIn = function (el, time) {
            setTimeout(function () {
                el.css('opacity', 1);
            }, time);
        }
        let elements = [];
        for (var i = 0, length = response.Hits.length; i < length; ++i) {
            var hit = response.Hits[i];
            var element = $(GenerateCardsHtml(hit));
            $itemGrid.append(element);
            elements.push(element);
        };
        $itemGrid.imagesLoaded(function () {
            elements.forEach(function(el) {
                 $itemGrid.packery('appended', el)
            });
            elements.forEach(function (el) {
                easeIn(el, time1);
                time1 += 500;
            } 
              
            );
        });       
    };

    var performSearch = function () {
        SearchHelper.performArticleSearch("", page, pageSize, documentType, null, rootId, null, null, orderBy, orderByDirection, false, false, false, handleSearchResponse);
    };

    var GenerateCardsHtml = function (response) {
        var preheaderAction1 = "";
        var preheaderAction2 = "";        
        var prestat = response.PreStat;
        if (response.Category != null && response.Category == "Agenda") {
            preheaderAction1 = " card--border card--agenda";
            preheaderAction2 = " dot";
        }
        else if (response.DocumentTypeNumber && response.DocumentTypeNumber == 35) {
            preheaderAction1 = " card--border card--analysis card--statistics card--prestat"
        }
        var preStatHtml = '';
        if (response.PreStat !== null && response.PreStat.length > 0) {
            preStatHtml += '<p class="card__prestat">' + prestat + '</p>';
        }

        var ret =
            '<div class="grid__item grid__loading">' +
            '<div class="card' + preheaderAction1 + ' card--link">' + preStatHtml +
                '<a href="' + response.Link + '" class="card__clicklayer"></a>';

        if (response.ImageUrl) {
            ret += '<img src="' + response.ImageUrl + '" alt = "' + response.Title + '" >';
        }        

        ret +=            
            '<div class="card__inner">' +
            '<p class="card__preheader' + preheaderAction2 + '">' + response.Category + '</p > ' +
            '<h1 class="card__header">' + response.Title + '</h1>' +
            '<div class="card__content">' +
            '<p>' +
            response.Manchet +
            '</p >' +
                '</div>' +
                '<div class="card__footer card__footer--flex">' +
                    '<p class="card__footer card__footer--flex--left">' +
                        response.DocumentType +
                    '</p>' +
                    '<p class="card__date">' +
                        response.CreatedDate +
                    '</p>' +
                '</div>' +
            '</div>' +
            '</div>' +
            '</div>';
        return ret;
    };

    $('#latest-items-block-load-more-button').on('click', function (e) {
        ++page;
        performSearch();
        e.preventDefault();
        return false;
    });

    //load the initial elements
    performSearch();

});;
$(function () {
    var $form = $('#newsletter-form');

    if ($form.length <= 0)
        return;

    var $submitButton = $('#newsletter-form-submit');

    $form.on('submit', function () {
        $submitButton.addClass('disabled');
        $submitButton.attr('disabled', 'disabled');        
    });
});


function enableNewsletterFormSubmit() {
    const btn = $(document.getElementById("newsletter-form-submit"));
    btn.removeClass('disabled');
    btn.removeAttr('disabled');

    const validation = $(document.getElementById("recaptcha-validation"));
    validation.removeClass("recaptcha-error");
}

function resetNewsletterFormSubmit() {
    grecaptcha.reset();
    const btn = $(document.getElementById("newsletter-form-submit"));
    btn.addClass('disabled');
    btn.attr('disabled', 'disabled');

    const validation = $(document.getElementById("recaptcha-validation"));
    validation.addClass("recaptcha-error");
};
$(document).ready(function () {
    var dictionary;

    var $resultList = $('.search__results > ul');
    var $latestSearches = $('#search-bar-previous-searches');
    var $latestSearchesHeadline = $('#search-bar-previous-searches-headline');

    var getLatestSearchesFromLocalStorage = function () {
        var latestSearchesString = localStorage.getItem('latestSearches');
        var latestSearches;

        //Ensure that the storage has been initialised
        if (!latestSearchesString)
            latestSearches = [];
        else
            latestSearches = JSON.parse(latestSearchesString);

        return latestSearches;
    };

    var addToLocalStorage = function (searchResult) {
        var latestSearches = getLatestSearchesFromLocalStorage();

        //If the current link is present in the list, move it to the top
        for (var i = 0, length = latestSearches.length; i < length; ++i) {
            if (latestSearches[i].Link === searchResult.Link) {
                latestSearches.splice(i, 1);

                break;
            }
        }

        //Remove first entry if the list is already full
        //While is used in case the list is bigger than anticipated
        while (latestSearches.length > 2) {
            latestSearches.shift();
        }

        latestSearches.push(searchResult);

        localStorage.setItem('latestSearches', JSON.stringify(latestSearches));
    };

    var generateListMarkup = function (element) {
        if (!element.Link)
            return null;

        var id = 'search-bar-link-' + element.Link.split('/').join('-');

        dictionary[id] = element;

        return '<li><a id="' + id + '" href="' + element.Link + '"' + (element.DocumentType === 'Fil' ? ' target="_blank"' : '')
            + '><span class="category">' + element.Category + '</span>'
            + (element.DocumentType !== null ? '<span class="type">' + element.DocumentType + '</span>' : '')
            + '<span class="title">' + element.Title + '</span></a>';
    };

    var updateSearchResults = function (results) {
        $('a[id^=search-bar-link-]').off('click');

        dictionary = {};
        $resultList.empty();

        var length = results.length;
        if (length <= 0) {
            $resultList.append('<li>Der er ingen søgeresultater på din søgning</li>');
        } else {
            for (var i = 0; i < length; ++i) {
                var markup = generateListMarkup(results[i]);

                if(markup)
                    $resultList.append(markup);
            }
        }

        $('a[id^=search-bar-link-').on('click', function (e) {
            var $target = $(e.target).parent('a');

            addToLocalStorage(dictionary[$target.attr('id')]);
        });
    };

    var performSearch = function () {
        var searchString = $('#head-search-bar-text').val();

        if (searchString.length <= 0)
            return;

        SearchHelper.performPageSearch(searchString, function (data) {
            updateSearchResults(data);
        });
    };

    var changeTimeout;

    $('#head-search-bar-text').on('keyup', function () {
        $resultList.empty();
        clearTimeout(changeTimeout);
        changeTimeout = setTimeout(performSearch, 300);
    });

    //Populate latest searches
    var ls = getLatestSearchesFromLocalStorage();

    if (ls && ls.length > 0) {
        $latestSearches.show();
        $latestSearchesHeadline.show();

        for (var i = ls.length - 1; i >= 0; --i) {
            $latestSearches.append('<li><a href="" class="removesearch"></a><a href="' + ls[i].Link + '"' + (ls[i].DocumentType === 'Fil' ? ' target="_blank"' : '') + '>' + ls[i].Title + ' - ' + ls[i].DocumentType + '</a></li>');
        }
    }

    $('.removesearch', $latestSearches).on('click', function (e) {
        var hrefToRemove = $(e.target).next().attr('href');

        var latestSearches = getLatestSearchesFromLocalStorage();

        for (var i = 0, length = latestSearches.length; i < length; ++i) {
            if (latestSearches[i].Link === hrefToRemove) {
                latestSearches.splice(i, 1);

                break;
            }
        }

        localStorage.setItem('latestSearches', JSON.stringify(latestSearches));

        $(e.target).parent('li').remove();

        e.preventDefault();
        return false;
    });
});;
var SearchHelper = {
    baseUrl: '/api/search/',
    buildUrl: function (path) {
        return this.baseUrl + (path || "") + '?culture='+_currentCulture//culture is set on the layout page
    },
    performPageSearch: function (query, callback) {
        var url = this.buildUrl() + '&q=' + encodeURIComponent(query);

        $.ajax({
            method: 'GET',
            url: url,
            success: callback
        });
    },
    performDetailedPageSearch: function (query, page, pageSize, documentType, searchTag, pathId, filePathId, filters, orderBy, orderByDirection, returnFacets, onlyPages, onlyArticles, callback) {
        $.ajax({
            method: 'POST',
            url: this.buildUrl(),
            success: callback,
            contentType: 'application/json',
            data: JSON.stringify({
                "Query": query,
                "Filters": filters,
                "SortBy": orderBy,
                "SortDirection": orderByDirection,
                "DocumentType": documentType,
                "ArticleTag": searchTag,
                "PathId": pathId,
                "FilePathId": filePathId,
                "Page": page,
                "PageSize": pageSize,
                "OnlyPages": onlyPages,
                "OnlyArticles": onlyArticles,
                "ReturnFacets": returnFacets
            })
        });
    },
    performStatisticsPageSearch: function (query, page, pageSize, documentType, searchTag, filters, returnFacets, orderBy, orderByDirection, callback) {
        $.ajax({
            method: 'POST',
            url: this.buildUrl('statistics'),
            success: callback,
            contentType: 'application/json',
            data: JSON.stringify({
                "Query": query,
                "Filters": filters,
                "SortBy": orderBy,
                "SortDirection": orderByDirection,
                "DocumentType": documentType,
                "ArticleTag": searchTag,
                "Page": page,
                "PageSize": pageSize,
                "ReturnFacets": returnFacets,
                "StartPageSearch": true
            })
        });
    },
    performAnalysisSearch: function (query, searchTag, year, callback) {
        $.ajax({
            method: 'POST',
            url: this.buildUrl('analysis'),
            success: callback,
            contentType: 'application/json',
            data: JSON.stringify({
                "Query": query,
                "Year": year,
                "Tag": searchTag,
                "PageSize": (!query && !searchTag && !year) ? 1 : 2
            })
        });
    },
    performDocumentSearch: function (query, filters, page, pageSize, year, month, orderBy, orderByDirection, callback) {
        $.ajax({
            method: 'POST',
            url: this.buildUrl('documents'),
            success: callback,
            contentType: 'application/json',
            data: JSON.stringify({
                "Query": query,
                "Filters": filters,
                "Page": page,
                "PageSize": pageSize,
                "Year": year,
                "Month": month,
                "SortBy": orderBy,
                "SortDirection": orderByDirection,
                "ReturnFacets": true
            })
        });
    },
    performArticleSearch: function (query, page, pageSize, documentType, searchTag, pathId, filePathId, filters, orderBy, orderByDirection, returnFacets, onlyPages, onlyArticles, callback) {
        $.ajax({
            method: 'POST',
            url: this.buildUrl("articles"),
            success: callback,
            contentType: 'application/json',
            data: JSON.stringify({
                "Query": query,
                "Filters": filters,
                "SortBy": orderBy,
                "SortDirection": orderByDirection,
                "DocumentType": documentType,
                "ArticleTag": searchTag,
                "PathId": pathId,
                "FilePathId": filePathId,
                "Page": page,
                "PageSize": pageSize,
                "OnlyPages": onlyPages,
                "OnlyArticles": onlyArticles,
                "ReturnFacets": returnFacets
            })
        });
    }
};;
$(function () {
    var $searchResults = $('#search-page-search--results');

    //This is a check to see if we're on the search page. Don't do anything if not
    if ($searchResults.length <= 0)
        return;

    var $loadMoreButton = $('#search-page-load-more-button');
    var $sortBySelect = $('#search-page-sort-by-select');
    var $facetContainer = $('.search__filters--desktop');
    var $facetMobileContainer = $('.search__filters--mobile');

    //variables needed for search
    var page = 1;
    var pageSize = 10;
    var query = $('#head-search-bar-text').val();
    var filters = null;
    var orderBy = $sortBySelect.val();
    var orderByDirection = orderBy === 'Name' ? 'Ascending' : 'Descending';
    var documentType = UrlHelper.getUrlParameter('type');
    var searchTag = UrlHelper.getUrlParameter('tag');

    var handleSearchResponse = function (response) {
        //Don't show the button, if there are no more search results to fetch
        if (page * pageSize >= response.TotalHits)
            $loadMoreButton.hide();
        else
            $loadMoreButton.show();

        for (var i = 0, length = response.Hits.length; i < length; ++i) {
            var hit = response.Hits[i];

            $searchResults.append(
                '<li class="grid__loading" style="opacity: 1;">' +
                '<a href="' + hit.Link + '"' + (hit.DocumentType === 'Fil' ? ' target="_blank"' : '') + '>' +
                '<div class="search--results__right">' +
                (hit.ImageUrl ? '<img src="' + hit.ImageUrl + '" />' : '') +
                '</div>' +
                '<div class="search--results__left">' +
                '<p class="preheader">' + hit.Category + '</p>' +
                '<h2>' + hit.Title + '</h2>' +
                '<div class="postheader">' +
                '<p class="postheader__date">' + hit.CreatedDate + '</p>' +
                (hit.DocumentType ? '<p class="postheader--type">' + hit.DocumentType + '</p>' : '') +
                '</div>' +
                '</div>' +
                '</a>' +
                '</li> ');
        }

        filters = response.Facets;

        $facetContainer.empty();
        $facetMobileContainer.empty();

        //Only show the filters, if there's more than one option
        if (filters.length > 1 || (filters.length === 1 && filters[0].Values.length > 1)) {
            $facetMobileContainer.append('<option value="">Ingen</option>');

            for (var j = 0, jLength = filters.length; j < jLength; ++j) {
                var facet = filters[j];

                for (var k = 0, kLength = facet.Values.length; k < kLength; ++k) {
                    var value = facet.Values[k];

                    $facetContainer.append('<li><a' + (value.Selected ? ' class="active"' : '') + ' href="" data-facet-name="' + facet.Name + '" data-value="' + value.Value + '">' + value.Name + ' (' + value.Count + ')</a></li>');
                    $facetMobileContainer.append('<option value="' + facet.Name + '-' + value.Value + '"' + (value.Selected ? ' selected' : '') + '>' + value.Name + ' (' + value.Count + ')</option>');
                }
            }
        }
    };

    var performSearch = function () {
        SearchHelper.performDetailedPageSearch(query, page, pageSize, documentType, searchTag, null, null, filters, orderBy, orderByDirection, true, false, false, handleSearchResponse);
    };

    $('#search-page-load-more-button').on('click', function (e) {
        ++page;

        performSearch();

        e.preventDefault();
        return false;
    });

    var updateFilters = function (facet, value) {
        for (var i = 0, length = filters.length; i < length; ++i) {
            if (filters[i].Name == facet) {
                for (var j = 0, jLength = filters[i].Values.length; j < jLength; ++j) {
                    if (filters[i].Values[j].Value == value) {
                        filters[i].Values[j].Selected = !filters[i].Values[j].Selected;
                    } else {
                        filters[i].Values[j].Selected = false;
                    }
                }

                break;
            }
        }
    };

    $facetContainer.on('click', function (e) {
        var $target = $(e.target);

        var facet = $target.data('facetName');
        var value = $target.data('value');

        if (facet && value) {
            updateFilters(facet, value);

            $searchResults.empty();
            page = 1;

            performSearch();
        }

        e.preventDefault();
        return false;
    });

    $facetMobileContainer.on('change', function (e) {
        var value = $facetMobileContainer.val();

        if (value === '')
            filters = null;
        else {
            var splitValue = value.split('-');

            updateFilters(splitValue[0], splitValue[1]);
        }

        $searchResults.empty();
        page = 1;

        performSearch();
    });

    $sortBySelect.on('change', function () {
        orderBy = $sortBySelect.val();
        orderByDirection = orderBy === 'Name' ? 'Ascending' : 'Descending';

        $searchResults.empty();

        SearchHelper.performDetailedPageSearch(query, 1, pageSize * page, documentType, searchTag, null, null, filters, orderBy, orderByDirection, true, false, false, handleSearchResponse);
    });

   
    performSearch();
});;
$(function () {
    $('.responsive').slick({
        dots: true,
        infinite: true,
        speed: 300,
        slidesToShow: 3,
        slidesToScroll: 1,
        adaptiveHeight: true,
        responsive: [
            {
                breakpoint: 1024,
                settings: {
                    slidesToShow: 2,
                    slidesToScroll: 1,
                    infinite: true,
                    dots: true
                }
            },
            {
                breakpoint: 600,
                settings: {
                    slidesToShow: 1,
                    slidesToScroll: 1
                }
            },
            {
                breakpoint: 480,
                settings: {
                    slidesToShow: 1,
                    slidesToScroll: 1
                }
            }
            // You can unslick at a given breakpoint now by adding:
            // settings: "unslick"
            // instead of a settings object
        ]
    });
});;
$(function () {
    var $form = $('#statistics-lounge-search');

    if ($form.length <= 0)
        return;

    var $searchResults = $('#statistics-lounge-search--results');
    var $loadMoreButton = $('#statistics-lounge-load-more-button');

    var pagePathId = $form.data('page-id');
    var filePathId = $form.data('file-id');

    var page = 1;
    var pageSize = 5;

    var printHit = function (hit) {
        $searchResults.append(
            '<li class="grid__loading" style="opacity: 1;">' +
            '<a href="' + hit.Link + '">' +
            '<div class="search--results__right">' +
            (hit.ImageUrl ? '<img src="' + hit.ImageUrl + '" />' : '') +
            '</div>' +
            '<div class="search--results__left">' +
            '<p class="preheader">' + hit.Category + '</p>' +
            '<h2>' + hit.Title + '</h2>' +
            '<div class="postheader">' +
            '<p class="postheader__date">' + hit.CreatedDate + '</p>' +
            (hit.DocumentType ? '<p class="postheader--type">' + hit.DocumentType + '</p>' : '') +
            '</div>' +
            '</div>' +
            '</a>' +
            '</li> ');
    };

    var handleResponse = function (data) {
        for (var i = 0, length = data.Hits.length; i < length; ++i) {
            printHit(data.Hits[i]);
        }

        if (page * pageSize < data.TotalHits)
            $loadMoreButton.show();
        else
            $loadMoreButton.hide();
    };

    var performSearch = function () {
        SearchHelper.performDetailedPageSearch(null, page, pageSize, null, null, pagePathId, filePathId, null, 'Date', 'Descending', false, true, false, handleResponse);
    };

    $loadMoreButton.on('click', function () {
        ++page;

        performSearch();
    });

    performSearch();
});;
var UrlHelper = {
    getUrlParameter: function (sParam) {
        var sPageURL = decodeURIComponent(window.location.search.substring(1)),
            sURLVariables = sPageURL.split('&'),
            sParameterName,
            i;

        for (i = 0; i < sURLVariables.length; i++) {
            sParameterName = sURLVariables[i].split('=');

            if (sParameterName[0] === sParam) {
                return sParameterName[1] === undefined ? true : sParameterName[1];
            }
        }
    }
};;
$(function () {
    var $productsList = $('#webshop-modal-products');

    $('.open-webshop-accordion').on('click', function (e) {
        var $target = $(e.target);

        var $accordionHeader = $('a[href="#' + $target.data('accordion') + '"]');

        var $parents = $accordionHeader.parents('.accordion__item:not(.accordion__item--active)');

        for (var i = 0, length = $parents.length; i < length; ++i) {
            var $accordion = $($parents[i]);

            $('> .accordion__header > a', $accordion).trigger('click');
        }
    });

    $('.webshop-product-checkbox').on('change', function (e) {
        var $checkbox = $(e.target);
        var addProduct = $checkbox.is(':checked');

        var category = $checkbox.data('category').toString();
        var name = $checkbox.data('name').toString();
        var product = $checkbox.data('product').toString();

        var id = 'webshop-product-' + category.replace(/^[^a-z0-9]+|[^\w:.-]+/gi, "") + '-' + name.replace(/^[^a-z0-9]+|[^\w:.-]+/gi, "") + '-' + product.replace(/^[^a-z0-9]+|[^\w:.-]+/gi, "");

        if (addProduct) {
            var price = $checkbox.data('price');

            $productsList.append('<tr id="' + id + '">' +
                    '<td name="'+ name + " - " + product +'">[' + category + '] ' + name + ' - ' + product + '</td>' +
                    '<td>' + price + ',-</td>' +
                '</tr>');
        } else {
            $('#' + id).remove();
        }
    });

    //Override the default behaviour to ensure proper form validation
    $('#order').off('click');

    var $customerTypePrivateRadio = $('#customer-type-private');
    var $customerTypeBusinessRadio = $('#customer-type-business');
    var $privateFields = $('#personal-info');
    var $businessFields = $('#business-info');
    var $orderForm = $('#webshop-order-form');

    //private fields
    var $privateFirstName = $('#webshop-private-first-name');
    var $privateLastName = $('#webshop-private-last-name');
    var $privateEmail = $('#webshop-private-email');
    var $privatePhoneNumber = $('#webshop-private-phone-number');
    var $privateStreet = $('#webshop-private-street');
    var $privateZipCode = $('#webshop-private-zip-code');
    var $privateCity = $('#webshop-private-city');
    var $privateCountry = $('#webshop-private-country');

    var requiredPrivateFields = [$privateFirstName, $privateLastName, $privateEmail, $privatePhoneNumber];

    //business fields
    var $businessFirstName = $('#webshop-business-first-name');
    var $businessLastName = $('#webshop-business-last-name');
    var $businessPrivateEmail = $('#webshop-business-private-email');
    var $businessPhoneNumber = $('#webshop-business-phone-number');
    var $businessEan = $('#webshop-business-ean');
    var $businessEmail = $('#webshop-business-email');
    var $businessCompanyName = $('#webshop-business-company-name');
    var $businessCompanyStreet = $('#webshop-business-company-street');
    var $businessCompanyZipCode = $('#webshop-business-company-zip-code');
    var $businessCompanyCity = $('#webshop-business-company-city');
    var $businessCompanyCountry = $('#webshop-business-company-country');
    var $businessCompanyCVR = $('#webshop-business-company-cvr-number');

    var requiredBusinessFields = [$businessFirstName, $businessLastName, $businessPrivateEmail, $businessPhoneNumber, $businessCompanyName, $businessCompanyStreet
        , $businessCompanyZipCode, $businessCompanyCity, $businessCompanyCountry];

    $customerTypePrivateRadio.on('click', function () {
        $privateFields.show();
        $businessFields.hide();

        for (var i = 0, length = requiredPrivateFields.length; i < length; ++i) {
            requiredPrivateFields[i].attr('required', true);
        }

        for (i = 0, length = requiredBusinessFields.length; i < length; ++i) {
            requiredBusinessFields[i].removeAttr('required');
        }

        $businessEan.removeAttr('required');
        $businessEmail.removeAttr('required');
        $businessCompanyCVR.removeAttr('required');
    });

    $customerTypeBusinessRadio.on('click', function () {
        $privateFields.hide();
        $businessFields.show();

        for (var i = 0, length = requiredPrivateFields.length; i < length; ++i) {
            requiredPrivateFields[i].removeAttr('required');
        }

        for (i = 0, length = requiredBusinessFields.length; i < length; ++i) {
            requiredBusinessFields[i].attr('required', true);
        }

        if (!$businessEan.val())
            $businessEmail.attr('required', true);
        if (!$businessEmail.val())
            $businessEan.attr('required', true);
    });

    $businessEan.on('change', function () {
        if ($businessEan.val()) {
            $businessEmail.removeAttr('required');
            $businessEmail.attr('placeholder', 'eller fakturerings-e-mail');
        }
        else {
            $businessEmail.attr('required', true);
            $businessEmail.attr('placeholder', 'eller fakturerings-e-mail*');
        }
    });

    $businessEmail.on('change', function () {
        if ($businessEmail.val()) {
            $businessEan.removeAttr('required');
            $businessEan.attr('placeholder', 'EAN');
        }
        else {
            $businessEan.attr('required', true);
            $businessEan.attr('placeholder', 'EAN*');
        }
    });

    $('.webshop-order-button').on('click', function (e) {
        if (!$orderForm[0].checkValidity()) {
            e.preventDefault();
            return false;
        }
        
        var $selectedProductList = $('td:first-child', $productsList);

        var productsBought = [];

        for (var i = 0, length = $selectedProductList.length; i < length; ++i) {
            productsBought.push($selectedProductList[i].getAttribute("name"));
        }

        //If the customer type is private, send private information otherwise send business information
        if ($customerTypePrivateRadio.is(':checked')) {
            $.ajax({
                method: 'POST',
                url: '/api/webshop/buy',
                contentType: 'application/json',
                data: JSON.stringify({
                    CustomerType: 'Private',
                    Products: productsBought,
                    PrivateCustomer: {
                        FirstName: $privateFirstName.val(),
                        LastName: $privateLastName.val(),
                        Email: $privateEmail.val(),
                        PhoneNumber: $privatePhoneNumber.val(),
                        Street: $privateStreet.val(),
                        ZipCode: $privateZipCode.val(),
                        City: $privateCity.val(),
                        Country: $privateCountry.val()
                    }
                })
            });
        } else {
            $.ajax({
                method: 'POST',
                url: '/api/webshop/buy',
                contentType: 'application/json',
                data: JSON.stringify({
                    CustomerType: 'Business',
                    Products: productsBought,
                    BusinessCustomer: {
                        FirstName: $businessFirstName.val(),
                        LastName: $businessLastName.val(),
                        PrivateEmail: $businessPrivateEmail.val(),
                        PhoneNumber: $businessPhoneNumber.val(),
                        Ean: $businessEan.val(),
                        Email: $businessEmail.val(),
                        CompanyName: $businessCompanyName.val(),
                        CompanyStreet: $businessCompanyStreet.val(),
                        CompanyZipCode: $businessCompanyZipCode.val(),
                        CompanyCity: $businessCompanyCity.val(),
                        CompanyCountry: $businessCompanyCountry.val(),
                        CVRNumber: $businessCompanyCVR.val()                    }
                })
            });
        }
        

        $('#salgafstatistik1').hide();
        $('#salgafstatistik3').show();

        e.preventDefault();
        return false;
    });
});;
$(function () {
    var $videos = $('iframe[src*="youtube"]');

    if ($videos.length <= 0)
        return;

    var $wrapper = '<div class="video-container"></div>';
    $videos.wrap($wrapper);
});;
