(function (Drupal, navigator, window, $) {
  'use strict';

  // Feature detection for SW
  if (!('serviceWorker' in navigator)) {
    return;
  }

  /**
   * Helper function to register Service Worker. Registration occurrs during
   * different events according to admin configuration.
   */
  function pwaServiceWorkerRegister() {
    navigator.serviceWorker
    .register(Drupal.settings.pwa.path, {scope: Drupal.settings.basePath})
    .then(function () {
      // Everything ok!
    })
    .catch(function (error) {
      // Something went wrong.
    });
  }

  // Read Drupal.settings and register SW during the desired event.
  if (Drupal.settings.pwa.registrationEvent === 'immediate') {
    pwaServiceWorkerRegister();
  }
  else if (Drupal.settings.pwa.registrationEvent === 'documentready') {
    $(document).ready(pwaServiceWorkerRegister);
  }
  else {
    window.addEventListener('load', pwaServiceWorkerRegister);
  }

  // Reload page when user is back online on a fallback offline page.
  document.body.addEventListener('online', function () {
    var loc = window.location;
    // If the page serve is the offline fallback, try a refresh when user
    // get back online.
    if (loc.pathname !== Drupal.settings.basePath + 'offline' && document.querySelector('[data-drupal-pwa-offline]')) {
      loc.reload();
    }
  });

  /*
  // In case you want to unregister the SW during testing:
  navigator.serviceWorker.getRegistration()
    .then(function(registration) {
      registration.unregister();
    });
  /**/

}(Drupal, navigator, window, jQuery));
;/*})'"*/;/*})'"*/
/**
 * @file
 * Cookie Compliance Javascript.
 *
 * Statuses:
 *  null: not yet agreed (or withdrawn), show popup
 *  0: Disagreed
 *  1: Agreed, show thank you banner
 *  2: Agreed.
 */

(function ($) {

  'use strict';
  var euCookieComplianceBlockCookies;
  var cookieValueDisagreed = (typeof Drupal.settings.eu_cookie_compliance.cookie_value_disagreed === 'undefined' || Drupal.settings.eu_cookie_compliance.cookie_value_disagreed === '') ? '0' : Drupal.settings.eu_cookie_compliance.cookie_value_disagreed;
  var cookieValueAgreedShowThankYou = (typeof Drupal.settings.eu_cookie_compliance.cookie_value_agreed_show_thank_you === 'undefined' || Drupal.settings.eu_cookie_compliance.cookie_value_agreed_show_thank_you === '') ? '1' : Drupal.settings.eu_cookie_compliance.cookie_value_agreed_show_thank_you;
  var cookieValueAgreed = (typeof Drupal.settings.eu_cookie_compliance.cookie_value_agreed === 'undefined' || Drupal.settings.eu_cookie_compliance.cookie_value_agreed === '') ? '2' : Drupal.settings.eu_cookie_compliance.cookie_value_agreed;

  Drupal.behaviors.eu_cookie_compliance_popup = {
    attach: function (context, settings) {
      $(Drupal.settings.eu_cookie_compliance.containing_element, context).once('eu-cookie-compliance', function () {

        // Initialize internal variables.
        _euccCurrentStatus = self.getCurrentStatus();
        _euccSelectedCategories = self.getAcceptedCategories();

        // If configured, check JSON callback to determine if in EU.
        if (Drupal.settings.eu_cookie_compliance.popup_eu_only_js) {
          if (Drupal.eu_cookie_compliance.showBanner()) {
            var url = Drupal.settings.basePath + Drupal.settings.pathPrefix + 'eu-cookie-compliance-check';
            var data = {};
            $.getJSON(url, data, function (data) {
              // If in the EU, show the compliance banner.
              if (data.in_eu) {
                Drupal.eu_cookie_compliance.execute();
              }

              // If not in EU, set an agreed cookie automatically.
              else {
                Drupal.eu_cookie_compliance.setStatus(cookieValueAgreed);
              }
            });
          }
        }

        // Otherwise, fallback to standard behavior which is to render the banner.
        else {
          Drupal.eu_cookie_compliance.execute();
        }
      }).addClass('eu-cookie-compliance-status-' + Drupal.eu_cookie_compliance.getCurrentStatus());
    }
  };

  // Sep up the namespace as a function to store list of arguments in a queue.
  Drupal.eu_cookie_compliance = Drupal.eu_cookie_compliance || function () {
    (Drupal.eu_cookie_compliance.queue = Drupal.eu_cookie_compliance.queue || []).push(arguments)
  };
  // Initialize the object with some data.
  Drupal.eu_cookie_compliance.a = +new Date;
  // A shorter name to use when accessing the namespace.
  var self = Drupal.eu_cookie_compliance;
  // Save our cookie preferences locally only.
  // Used by external scripts to modify data before it is used.
  var _euccSelectedCategories = [];
  var _euccCurrentStatus = null;
  self.updateSelectedCategories = function (categories) {
    _euccSelectedCategories = categories;
  }
  self.updateCurrentStatus = function (status) {
    _euccCurrentStatus = status;
  }

  Drupal.eu_cookie_compliance.execute = function () {
    try {
      if (!Drupal.settings.eu_cookie_compliance.popup_enabled) {
        return;
      }

      if (!Drupal.eu_cookie_compliance.cookiesEnabled()) {
        return;
      }

      if (typeof Drupal.eu_cookie_compliance.getVersion() === 'undefined') {
        // If version doesn't exist as a cookie, set it to the current one.
        // For modules that update to this, it prevents needless retriggering
        // For first time runs, it makes no difference as the other IF statements
        // below will still cause the popup to trigger
        // For incrementing the version, it also makes no difference as either it's
        // a returning user and will have a version set, or it's a new user and
        // the other checks will trigger it.
        Drupal.eu_cookie_compliance.setVersion();
      }

      Drupal.eu_cookie_compliance.updateCheck();
      var versionChanged = Drupal.eu_cookie_compliance.getVersion() !== Drupal.settings.eu_cookie_compliance.cookie_policy_version;
      // Closed if status has a value and the version hasn't changed.
      var closed = _euccCurrentStatus !== null && !versionChanged;
      if ((_euccCurrentStatus === 0 && Drupal.settings.eu_cookie_compliance.method === 'default') || _euccCurrentStatus === null || (Drupal.settings.eu_cookie_compliance.withdraw_enabled && Drupal.settings.eu_cookie_compliance.withdraw_button_on_info_popup) || versionChanged) {
        if (Drupal.settings.eu_cookie_compliance.withdraw_enabled || !Drupal.settings.eu_cookie_compliance.disagree_do_not_show_popup || _euccCurrentStatus === null || versionChanged) {
          // Detect mobile here and use mobile_popup_html_info, if we have a mobile device.
          if (window.matchMedia('(max-width: ' + Drupal.settings.eu_cookie_compliance.mobile_breakpoint + 'px)').matches && Drupal.settings.eu_cookie_compliance.use_mobile_message) {
            Drupal.eu_cookie_compliance.createPopup(Drupal.settings.eu_cookie_compliance.mobile_popup_html_info, closed);
          }
          else {
            Drupal.eu_cookie_compliance.createPopup(Drupal.settings.eu_cookie_compliance.popup_html_info, closed);
          }

          Drupal.eu_cookie_compliance.initPopup();
          Drupal.eu_cookie_compliance.resizeListener();
        }
      }
      if (_euccCurrentStatus === 1 && Drupal.settings.eu_cookie_compliance.popup_agreed_enabled) {
        // Thank you banner.
        Drupal.eu_cookie_compliance.createPopup(Drupal.settings.eu_cookie_compliance.popup_html_agreed);
        Drupal.eu_cookie_compliance.attachHideEvents();
      }
      else if (_euccCurrentStatus === 2 && Drupal.settings.eu_cookie_compliance.withdraw_enabled) {
        if (!Drupal.settings.eu_cookie_compliance.withdraw_button_on_info_popup) {
          Drupal.eu_cookie_compliance.createWithdrawBanner(Drupal.settings.eu_cookie_compliance.withdraw_markup);
          Drupal.eu_cookie_compliance.resizeListener();
        }
        Drupal.eu_cookie_compliance.attachWithdrawEvents();
      }
    }
    catch (e) {
    }
  };

  Drupal.eu_cookie_compliance.initPopup = function () {
    Drupal.eu_cookie_compliance.attachAgreeEvents();

    if (Drupal.settings.eu_cookie_compliance.method === 'categories') {
      Drupal.eu_cookie_compliance.setPreferenceCheckboxes(_euccSelectedCategories);
      Drupal.eu_cookie_compliance.attachSavePreferencesEvents();
    }

    if (Drupal.settings.eu_cookie_compliance.withdraw_enabled && Drupal.settings.eu_cookie_compliance.withdraw_button_on_info_popup) {
      Drupal.eu_cookie_compliance.attachWithdrawEvents();
      if (_euccCurrentStatus === 1 || _euccCurrentStatus === 2) {
        $('.eu-cookie-withdraw-button').removeClass('eu-cookie-compliance-hidden');
      }
    }
  }

  Drupal.eu_cookie_compliance.positionTab = function () {
    if (Drupal.settings.eu_cookie_compliance.popup_position) {
      var totalHeight = $('.eu-cookie-withdraw-tab').outerHeight() + $('.eu-cookie-compliance-banner').outerHeight();
      $('.eu-cookie-withdraw-tab').css('margin-top', totalHeight + 'px');
    }
  };

  Drupal.eu_cookie_compliance.createWithdrawBanner = function (html) {
    var $html = $('<div></div>').html(html);
    var $banner = $('.eu-cookie-withdraw-banner', $html);
    $html.attr('id', 'sliding-popup');
    $html.addClass('eu-cookie-withdraw-wrapper');

    if (!Drupal.settings.eu_cookie_compliance.popup_use_bare_css) {
      $banner.height(Drupal.settings.eu_cookie_compliance.popup_height)
          .width(Drupal.settings.eu_cookie_compliance.popup_width);
    }
    $html.hide();
    var height = 0;
    if (Drupal.settings.eu_cookie_compliance.popup_position) {
      $html.prependTo(Drupal.settings.eu_cookie_compliance.containing_element);
      height = $html.outerHeight();

      $html.show()
          .addClass('sliding-popup-top')
          .addClass('clearfix')
          .css({ top: !Drupal.settings.eu_cookie_compliance.fixed_top_position ? -(parseInt($(Drupal.settings.eu_cookie_compliance.containing_element).css('padding-top')) + parseInt($(Drupal.settings.eu_cookie_compliance.containing_element).css('margin-top')) + height) : -1 * height });
      // For some reason, the tab outerHeight is -10 if we don't use a timeout
      // function to reveal the tab.
      setTimeout(function () {
        $html.animate({ top: !Drupal.settings.eu_cookie_compliance.fixed_top_position ? -(parseInt($(Drupal.settings.eu_cookie_compliance.containing_element).css('padding-top')) + parseInt($(Drupal.settings.eu_cookie_compliance.containing_element).css('margin-top')) + height) : -1 * height }, Drupal.settings.eu_cookie_compliance.popup_delay, null, function () {
          $html.trigger('eu_cookie_compliance_popup_open');
          $('body').addClass('eu-cookie-compliance-popup-open');
          Drupal.eu_cookie_compliance.positionTab();
        });
      }.bind($html, height), 0);
    }
    else {
      if (Drupal.settings.eu_cookie_compliance.better_support_for_screen_readers) {
        $html.prependTo(Drupal.settings.eu_cookie_compliance.containing_element);
      }
      else {
        $html.appendTo(Drupal.settings.eu_cookie_compliance.containing_element);
      }
      height = $html.outerHeight();
      $html.show()
          .addClass('sliding-popup-bottom')
          .css({ bottom: -1 * height });
      // For some reason, the tab outerHeight is -10 if we don't use a timeout
      // function to reveal the tab.
      setTimeout(function () {
        $html.animate({ bottom: -1 * height }, Drupal.settings.eu_cookie_compliance.popup_delay, null, function () {
          $html.trigger('eu_cookie_compliance_popup_open');
          $('body').addClass('eu-cookie-compliance-popup-open');
        });
      }.bind($html, height), 0);
    }
  };

  Drupal.eu_cookie_compliance.toggleWithdrawBanner = function () {
    var $wrapper = $('#sliding-popup');
    var height = $wrapper.outerHeight();
    var $bannerIsShowing = ($wrapper.find('.eu-cookie-compliance-banner, .eu-cookie-withdraw-banner').is(':visible'));
    if ($bannerIsShowing) {
      $bannerIsShowing = Drupal.settings.eu_cookie_compliance.popup_position ? parseInt($wrapper.css('top')) === (!Drupal.settings.eu_cookie_compliance.fixed_top_position ? -(parseInt($(Drupal.settings.eu_cookie_compliance.containing_element).css('padding-top')) + parseInt($(Drupal.settings.eu_cookie_compliance.containing_element).css('margin-top'))) : 0) : parseInt($wrapper.css('bottom')) === 0;
    }
    if (Drupal.settings.eu_cookie_compliance.popup_position) {
      if ($bannerIsShowing) {
        $wrapper.animate({ top: !Drupal.settings.eu_cookie_compliance.fixed_top_position ? -(parseInt($(Drupal.settings.eu_cookie_compliance.containing_element).css('padding-top')) + parseInt($(Drupal.settings.eu_cookie_compliance.containing_element).css('margin-top')) + height) : -1 * height }, Drupal.settings.eu_cookie_compliance.popup_delay).trigger('eu_cookie_compliance_popup_close');
        $('body').removeClass('eu-cookie-compliance-popup-open');
      }
      else {
        // If "Do not show cookie policy when the user clicks the Cookie policy button." is
        // selected, the inner banner may be hidden.
        $wrapper.find('.eu-cookie-compliance-banner').show();
        $wrapper.animate({ top: !Drupal.settings.eu_cookie_compliance.fixed_top_position ? -(parseInt($(Drupal.settings.eu_cookie_compliance.containing_element).css('padding-top')) + parseInt($(Drupal.settings.eu_cookie_compliance.containing_element).css('margin-top'))) : 0 }, Drupal.settings.eu_cookie_compliance.popup_delay).trigger('eu_cookie_compliance_popup_open');
        $('body').addClass('eu-cookie-compliance-popup-open');
      }
    }
    else {
      if ($bannerIsShowing) {
        $wrapper.animate({ 'bottom': -1 * height }, Drupal.settings.eu_cookie_compliance.popup_delay).trigger('eu_cookie_compliance_popup_close');
        $('body').removeClass('eu-cookie-compliance-popup-open');
      }
      else {
        // If "Do not show cookie policy when the user clicks the Cookie policy button." is
        // selected, the inner banner may be hidden.
        $wrapper.find('.eu-cookie-compliance-banner').show();
        $wrapper.animate({ 'bottom': 0 }, Drupal.settings.eu_cookie_compliance.popup_delay).trigger('eu_cookie_compliance_popup_open');
        $('body').addClass('eu-cookie-compliance-popup-open');
      }
    }
  };

  Drupal.eu_cookie_compliance.resizeListener = function () {
    var $wrapper = $('#sliding-popup');

    const debounce = function (func, wait ) {
      var timeout;

      return function executedFunction() {
        var later = function () {
          clearTimeout(timeout);
          func();
        };

        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
      };
    };

    var checkIfPopupIsClosed = debounce(function () {
      var wrapperHeight = $wrapper.outerHeight();
      if (Drupal.settings.eu_cookie_compliance.popup_position) {
        var wrapperTopProperty = parseFloat($wrapper.css('bottom'));
        if (wrapperTopProperty !== 0) {
          $wrapper.css('top', wrapperHeight * -1);
        }
      }
      else {
        var wrapperBottomProperty = parseFloat($wrapper.css('bottom'));
        if (wrapperBottomProperty !== 0) {
          $wrapper.css('bottom', wrapperHeight * -1);
        }
      }
    }, 50);

    setTimeout(function () {
      checkIfPopupIsClosed();
    });

    window.addEventListener('resize', checkIfPopupIsClosed);

  };

  Drupal.eu_cookie_compliance.createPopup = function (html, closed) {
    // This fixes a problem with jQuery 1.9.
    var $popup = $('<div></div>').html(html);
    $popup.attr('id', 'sliding-popup');
    if (!Drupal.settings.eu_cookie_compliance.popup_use_bare_css) {
      $popup.height(Drupal.settings.eu_cookie_compliance.popup_height)
          .width(Drupal.settings.eu_cookie_compliance.popup_width);
    }

    $popup.hide();
    var height = 0;
    if (Drupal.settings.eu_cookie_compliance.popup_position) {
      $popup.prependTo(Drupal.settings.eu_cookie_compliance.containing_element);
      height = $popup.outerHeight();
      $popup.show()
        .attr({ 'class': 'sliding-popup-top clearfix' })
        .css({ top: !Drupal.settings.eu_cookie_compliance.fixed_top_position ? -(parseInt($(Drupal.settings.eu_cookie_compliance.containing_element).css('padding-top')) + parseInt($(Drupal.settings.eu_cookie_compliance.containing_element).css('margin-top')) + height) : -1 * height });
      if (closed !== true) {
        $popup.animate({ top: !Drupal.settings.eu_cookie_compliance.fixed_top_position ? -(parseInt($(Drupal.settings.eu_cookie_compliance.containing_element).css('padding-top')) + parseInt($(Drupal.settings.eu_cookie_compliance.containing_element).css('margin-top'))) : 0 }, Drupal.settings.eu_cookie_compliance.popup_delay, null, function () {
          $popup.trigger('eu_cookie_compliance_popup_open');
          $('body').addClass('eu-cookie-compliance-popup-open');
          Drupal.eu_cookie_compliance.positionTab();
        });
      }
      else {
        setTimeout(function () {
          Drupal.eu_cookie_compliance.positionTab();
        }, 0);
      }
    }
    else {
      if (Drupal.settings.eu_cookie_compliance.better_support_for_screen_readers) {
        $popup.prependTo(Drupal.settings.eu_cookie_compliance.containing_element);
      }
      else {
        $popup.appendTo(Drupal.settings.eu_cookie_compliance.containing_element);
      }

      height = $popup.outerHeight();
      $popup.show()
        .attr({ 'class': 'sliding-popup-bottom' })
        .css({ bottom: -1 * height });
      if (closed !== true) {
        $popup.animate({bottom: 0}, Drupal.settings.eu_cookie_compliance.popup_delay, null, function () {
          $popup.trigger('eu_cookie_compliance_popup_open');
          $('body').addClass('eu-cookie-compliance-popup-open');
        });
      }
    }
  };

  Drupal.eu_cookie_compliance.attachAgreeEvents = function () {
    var clickingConfirms = Drupal.settings.eu_cookie_compliance.popup_clicking_confirmation;
    var scrollConfirms = Drupal.settings.eu_cookie_compliance.popup_scrolling_confirmation;

    if (Drupal.settings.eu_cookie_compliance.method === 'categories' && Drupal.settings.eu_cookie_compliance.enable_save_preferences_button) {
      // The agree button becomes an agree to all categories button when the 'save preferences' button is present.
      $('.agree-button').click(Drupal.eu_cookie_compliance.acceptAllAction);
    }
    else {
      $('.agree-button').click(Drupal.eu_cookie_compliance.acceptAction);
    }
    $('.decline-button').click(Drupal.eu_cookie_compliance.declineAction);

    if (clickingConfirms) {
      $('a, input[type=submit], button[type=submit]').not('.popup-content *').bind('click.euCookieCompliance', Drupal.eu_cookie_compliance.acceptAction);
    }

    if (scrollConfirms) {
      var alreadyScrolled = false;
      var scrollHandler = function () {
        if (alreadyScrolled) {
          Drupal.eu_cookie_compliance.acceptAction();
          $(window).off('scroll', scrollHandler);
        }
        else {
          alreadyScrolled = true;
        }
      };

      $(window).bind('scroll', scrollHandler);
    }

    $('.find-more-button').not('.find-more-button-processed').addClass('find-more-button-processed').click(Drupal.eu_cookie_compliance.moreInfoAction);
  };

  Drupal.eu_cookie_compliance.attachSavePreferencesEvents = function () {
    $('.eu-cookie-compliance-save-preferences-button').click(Drupal.eu_cookie_compliance.savePreferencesAction);
  };

  Drupal.eu_cookie_compliance.attachHideEvents = function () {
    var popupHideAgreed = Drupal.settings.eu_cookie_compliance.popup_hide_agreed;
    var clickingConfirms = Drupal.settings.eu_cookie_compliance.popup_clicking_confirmation;
    $('.hide-popup-button').click(function () {
      Drupal.eu_cookie_compliance.changeStatus(cookieValueAgreed);
    }
    );
    if (clickingConfirms) {
      $('a, input[type=submit], button[type=submit]').unbind('click.euCookieCompliance');
    }

    if (popupHideAgreed) {
      $('a, input[type=submit], button[type=submit]').bind('click.euCookieComplianceHideAgreed', function () {
        Drupal.eu_cookie_compliance.changeStatus(cookieValueAgreed);
      });
    }

    $('.find-more-button').not('.find-more-button-processed').addClass('find-more-button-processed').click(Drupal.eu_cookie_compliance.moreInfoAction);
  };

  Drupal.eu_cookie_compliance.attachWithdrawEvents = function () {
    $('.eu-cookie-withdraw-button').click(Drupal.eu_cookie_compliance.withdrawAction);
    $('.eu-cookie-withdraw-tab').click(Drupal.eu_cookie_compliance.toggleWithdrawBanner);
  };

  Drupal.eu_cookie_compliance.acceptAction = function () {
    var agreedEnabled = Drupal.settings.eu_cookie_compliance.popup_agreed_enabled;
    var nextStatus = cookieValueAgreedShowThankYou;
    if (!agreedEnabled) {
      Drupal.eu_cookie_compliance.setStatus(cookieValueAgreedShowThankYou);
      nextStatus = cookieValueAgreed;
    }

    if (!euCookieComplianceHasLoadedScripts && typeof euCookieComplianceLoadScripts === "function") {
      euCookieComplianceLoadScripts();
    }

    if (typeof euCookieComplianceBlockCookies !== 'undefined') {
      clearInterval(euCookieComplianceBlockCookies);
    }

    if (Drupal.settings.eu_cookie_compliance.method === 'categories') {
      // Select Checked categories.
      var categories = $("#eu-cookie-compliance-categories input:checkbox:checked").map(function () {
        return $(this).val();
      }).get();
      Drupal.eu_cookie_compliance.setAcceptedCategories(categories);
      // Load scripts for all categories. If no categories selected, none
      // will be loaded.
      Drupal.eu_cookie_compliance.loadCategoryScripts(categories);
      if (!categories.length) {
        // No categories selected is the same as declining all cookies.
        nextStatus = cookieValueDisagreed;
      }
    }

    Drupal.eu_cookie_compliance.changeStatus(nextStatus);

    if (Drupal.settings.eu_cookie_compliance.withdraw_enabled && Drupal.settings.eu_cookie_compliance.withdraw_button_on_info_popup) {
      Drupal.eu_cookie_compliance.attachWithdrawEvents();
      if (_euccCurrentStatus === 1 || _euccCurrentStatus === 2) {
        $('.eu-cookie-withdraw-button').removeClass('eu-cookie-compliance-hidden');
      }
    }
  };

  Drupal.eu_cookie_compliance.acceptAllAction = function () {
    var allCategories = Drupal.settings.eu_cookie_compliance.cookie_categories;
    Drupal.eu_cookie_compliance.setPreferenceCheckboxes(allCategories);
    Drupal.eu_cookie_compliance.acceptAction();
  }

  Drupal.eu_cookie_compliance.savePreferencesAction = function () {
    var categories = $("#eu-cookie-compliance-categories input:checkbox:checked").map(function () {
      return $(this).val();
    }).get();
    var agreedEnabled = Drupal.settings.eu_cookie_compliance.popup_agreed_enabled;
    var nextStatus = cookieValueAgreedShowThankYou;
    if (!agreedEnabled) {
      Drupal.eu_cookie_compliance.setStatus(cookieValueAgreedShowThankYou);
      nextStatus = cookieValueAgreed;
    }

    Drupal.eu_cookie_compliance.setAcceptedCategories(categories);
    // Load scripts for all categories. If no categories selected, none
    // will be loaded.
    Drupal.eu_cookie_compliance.loadCategoryScripts(categories);
    if (!categories.length) {
      // No categories selected is the same as declining all cookies.
      nextStatus = cookieValueDisagreed;
    }
    Drupal.eu_cookie_compliance.changeStatus(nextStatus);
  };

  Drupal.eu_cookie_compliance.loadCategoryScripts = function (categories) {
    for (var cat in categories) {
      if (euCookieComplianceHasLoadedScriptsForCategory[cat] !== true && typeof euCookieComplianceLoadScripts === "function") {
        euCookieComplianceLoadScripts(categories[cat]);
        euCookieComplianceHasLoadedScriptsForCategory[cat] = true;
      }
    }
  }

  Drupal.eu_cookie_compliance.declineAction = function () {
    Drupal.eu_cookie_compliance.setStatus(cookieValueDisagreed);
    var popup = $('#sliding-popup');
    if (popup.hasClass('sliding-popup-top')) {
      popup.animate({ top: !Drupal.settings.eu_cookie_compliance.fixed_top_position ? -(parseInt($(Drupal.settings.eu_cookie_compliance.containing_element).css('padding-top')) + parseInt($(Drupal.settings.eu_cookie_compliance.containing_element).css('margin-top')) + popup.outerHeight()) : popup.outerHeight() * -1 }, Drupal.settings.eu_cookie_compliance.popup_delay, null, function () {
        popup.hide();
      }).trigger('eu_cookie_compliance_popup_close');
      $('body').removeClass('eu-cookie-compliance-popup-open');
    }
    else {
      popup.animate({ bottom: popup.outerHeight() * -1 }, Drupal.settings.eu_cookie_compliance.popup_delay, null, function () {
        popup.hide();
      }).trigger('eu_cookie_compliance_popup_close');
      $('body').removeClass('eu-cookie-compliance-popup-open');
    }
  };

  Drupal.eu_cookie_compliance.withdrawAction = function () {
    // Save "decline".
    Drupal.eu_cookie_compliance.setStatus(0);

    Drupal.eu_cookie_compliance.setAcceptedCategories([]);
    location.reload();
  };

  Drupal.eu_cookie_compliance.moreInfoAction = function () {
    if (Drupal.settings.eu_cookie_compliance.disagree_do_not_show_popup) {
      Drupal.eu_cookie_compliance.setStatus(cookieValueDisagreed);
      if (Drupal.settings.eu_cookie_compliance.withdraw_enabled && Drupal.settings.eu_cookie_compliance.withdraw_button_on_info_popup) {
        $('#sliding-popup .eu-cookie-compliance-banner').trigger('eu_cookie_compliance_popup_close').hide();
        $('body').removeClass('eu-cookie-compliance-popup-open');
      }
      else {
        $('#sliding-popup').trigger('eu_cookie_compliance_popup_close').remove();
        $('body').removeClass('eu-cookie-compliance-popup-open');
      }
    }
    else {
      if (Drupal.settings.eu_cookie_compliance.popup_link_new_window) {
        window.open(Drupal.settings.eu_cookie_compliance.popup_link);
      }
      else {
        window.location.href = Drupal.settings.eu_cookie_compliance.popup_link;
      }
    }
  };

  Drupal.eu_cookie_compliance.getCurrentStatus = function () {
    // Make a new observer & fire it to allow other scripts to hook in.
    var preStatusLoadObject = new PreStatusLoad();
    self.handleEvent('preStatusLoad', preStatusLoadObject);

    var cookieName = (typeof eu_cookie_compliance_cookie_name === 'undefined' || eu_cookie_compliance_cookie_name === '') ? 'cookie-agreed' : eu_cookie_compliance_cookie_name;
    if ($.cookie(cookieName) === cookieValueDisagreed) {
      var numericalStatus = '0';
    } else if  ($.cookie(cookieName) === cookieValueAgreedShowThankYou) {
      var numericalStatus = '1';
    } else if  ($.cookie(cookieName) === cookieValueAgreed) {
      var numericalStatus = '2';
    }
    var storedStatus = numericalStatus;
    _euccCurrentStatus = parseInt(storedStatus);
    if (isNaN(_euccCurrentStatus)) {
      _euccCurrentStatus = null;
    }

    // Make a new observer & fire it to allow other scripts to hook in.
    var postStatusLoadObject = new PostStatusLoad();
    self.handleEvent('postStatusLoad', postStatusLoadObject);

    return _euccCurrentStatus;
  };

  Drupal.eu_cookie_compliance.setPreferenceCheckboxes = function (categories) {
    // Unset all categories to prevent a problem where the checkboxes with a
    // default state set would always show up as checked.
    if ((categories.length && Drupal.eu_cookie_compliance.getCurrentStatus() !== null) || Drupal.eu_cookie_compliance.getCurrentStatus() === 0) {
      $("#eu-cookie-compliance-categories input:checkbox").removeAttr("checked");
    }
    // Check the appropriate checkboxes.
    for (var i in categories) {
      // Rewrite the id like we do in Drupal 7 drupal_html_class.
      var safeCategoryId = categories[i].replace(/[ _\/\[\]]/g,'-').toLowerCase();
      var categoryElement = document.getElementById('cookie-category-' + safeCategoryId);
      if (categoryElement !== null) {
        categoryElement.checked = true;
      }
    }
  }

  Drupal.eu_cookie_compliance.getAcceptedCategories = function () {
    // Make a new observer & fire it to allow other scripts to hook in.
    var prePreferencesLoadObject = new PrePreferencesLoad();
    self.handleEvent('prePreferencesLoad', prePreferencesLoadObject);

    var cookieName = (typeof eu_cookie_compliance_cookie_name === 'undefined' || eu_cookie_compliance_cookie_name === '') ? 'cookie-agreed-categories' : Drupal.settings.eu_cookie_compliance.cookie_name + '-categories';
    var storedCategories = $.cookie(cookieName);

    if (storedCategories !== null && typeof storedCategories !== 'undefined') {
      _euccSelectedCategories = JSON.parse(storedCategories);
    }
    else {
      _euccSelectedCategories = [];
    }

    // Merge in required categories if not already present. Mimics old
    // logic where "fix first category" changed logic in
    // .hasAgreedWithCategory and this function.
    for (var _categoryName in Drupal.settings.eu_cookie_compliance.cookie_categories_details) {
      var _category = Drupal.settings.eu_cookie_compliance.cookie_categories_details[_categoryName];
      if (_category.checkbox_default_state === 'required' && $.inArray(_category.machine_name, _euccSelectedCategories) === -1) {
        _euccSelectedCategories.push(_category.machine_name);
      }
    }

    // Make a new observer & fire it to allow other scripts to hook in.
    var postPreferencesLoadObject = new PostPreferencesLoad();
    self.handleEvent('postPreferencesLoad', postPreferencesLoadObject);

    return _euccSelectedCategories;
  };

  Drupal.eu_cookie_compliance.changeStatus = function (value) {
    var reloadPage = Drupal.settings.eu_cookie_compliance.reload_page;
    var previousState = _euccCurrentStatus;
    if (_euccCurrentStatus === parseInt(value)) {
      return;
    }

    if (Drupal.settings.eu_cookie_compliance.popup_position) {
      $('.sliding-popup-top').animate({ top: !Drupal.settings.eu_cookie_compliance.fixed_top_position ? -(parseInt($(Drupal.settings.eu_cookie_compliance.containing_element).css('padding-top')) + parseInt($(Drupal.settings.eu_cookie_compliance.containing_element).css('margin-top')) + $('#sliding-popup').outerHeight()) : $('#sliding-popup').outerHeight() * -1 }, Drupal.settings.eu_cookie_compliance.popup_delay, function () {
        if (value === cookieValueAgreedShowThankYou && previousState === null && !reloadPage) {
          $('.sliding-popup-top').not('.eu-cookie-withdraw-wrapper').html(Drupal.settings.eu_cookie_compliance.popup_html_agreed).animate({ top: !Drupal.settings.eu_cookie_compliance.fixed_top_position ? -(parseInt($(Drupal.settings.eu_cookie_compliance.containing_element).css('padding-top')) + parseInt($(Drupal.settings.eu_cookie_compliance.containing_element).css('margin-top'))) : 0 }, Drupal.settings.eu_cookie_compliance.popup_delay);
          Drupal.eu_cookie_compliance.attachHideEvents();
        }
        else if (previousState === cookieValueAgreedShowThankYou) {
          if (Drupal.settings.eu_cookie_compliance.withdraw_enabled && Drupal.settings.eu_cookie_compliance.withdraw_button_on_info_popup) {
            // Restore popup content.
            if (window.matchMedia('(max-width: ' + Drupal.settings.eu_cookie_compliance.mobile_breakpoint + 'px)').matches && Drupal.settings.eu_cookie_compliance.use_mobile_message) {
              $('.sliding-popup-top').not('.eu-cookie-withdraw-wrapper').html(Drupal.settings.eu_cookie_compliance.mobile_popup_html_info);
            }
            else {
              $('.sliding-popup-top').not('.eu-cookie-withdraw-wrapper').html(Drupal.settings.eu_cookie_compliance.popup_html_info);
            }
            Drupal.eu_cookie_compliance.initPopup();
            Drupal.eu_cookie_compliance.resizeListener();
          }
          else {
            $('.sliding-popup-top').not('.eu-cookie-withdraw-wrapper').trigger('eu_cookie_compliance_popup_close').remove();
            $('body').removeClass('eu-cookie-compliance-popup-open');
          }
        }
        if (Drupal.settings.eu_cookie_compliance.withdraw_enabled) {
          Drupal.eu_cookie_compliance.showWithdrawBanner(value);
        }
      });
    }
    else {
      $('.sliding-popup-bottom').animate({ bottom: $('#sliding-popup').outerHeight() * -1 }, Drupal.settings.eu_cookie_compliance.popup_delay, function () {
        if (value === cookieValueAgreedShowThankYou && previousState === null && !reloadPage) {
          $('.sliding-popup-bottom').not('.eu-cookie-withdraw-wrapper').html(Drupal.settings.eu_cookie_compliance.popup_html_agreed).animate({ bottom: 0 }, Drupal.settings.eu_cookie_compliance.popup_delay);
          Drupal.eu_cookie_compliance.attachHideEvents();
        }
        else if (previousState === cookieValueAgreedShowThankYou) {
          if (Drupal.settings.eu_cookie_compliance.withdraw_enabled && Drupal.settings.eu_cookie_compliance.withdraw_button_on_info_popup) {
            // Restore popup content.
            if (window.matchMedia('(max-width: ' + Drupal.settings.eu_cookie_compliance.mobile_breakpoint + 'px)').matches && Drupal.settings.eu_cookie_compliance.use_mobile_message) {
              $('.sliding-popup-bottom').not('.eu-cookie-withdraw-wrapper').html(Drupal.settings.eu_cookie_compliance.mobile_popup_html_info);
            }
            else {
              $('.sliding-popup-bottom').not('.eu-cookie-withdraw-wrapper').html(Drupal.settings.eu_cookie_compliance.popup_html_info);
            }
            Drupal.eu_cookie_compliance.initPopup();
            Drupal.eu_cookie_compliance.resizeListener();
          }
          else {
            $('.sliding-popup-bottom').not('.eu-cookie-withdraw-wrapper').trigger('eu_cookie_compliance_popup_close').remove();
            $('body').removeClass('eu-cookie-compliance-popup-open');
          }
        }
        if (Drupal.settings.eu_cookie_compliance.withdraw_enabled) {
          Drupal.eu_cookie_compliance.showWithdrawBanner(value);
        }
      });
    }

    if (reloadPage) {
      location.reload();
    }

    Drupal.eu_cookie_compliance.setStatus(value);
  };

  Drupal.eu_cookie_compliance.showWithdrawBanner = function (value) {
    if (value === cookieValueAgreed && Drupal.settings.eu_cookie_compliance.withdraw_enabled) {
      if (!Drupal.settings.eu_cookie_compliance.withdraw_button_on_info_popup) {
        Drupal.eu_cookie_compliance.createWithdrawBanner(Drupal.settings.eu_cookie_compliance.withdraw_markup);
        Drupal.eu_cookie_compliance.resizeListener();
      }
      Drupal.eu_cookie_compliance.attachWithdrawEvents();
      Drupal.eu_cookie_compliance.positionTab();
    }
  };

  Drupal.eu_cookie_compliance.setStatus = function (status) {

    // Make a new observer & fire it to allow other scripts to hook in.
    var preStatusSaveObject = new PreStatusSave();
    self.handleEvent('preStatusSave', preStatusSaveObject);

    var date = new Date();
    var domain = Drupal.settings.eu_cookie_compliance.domain ? Drupal.settings.eu_cookie_compliance.domain : '';
    var path = Drupal.settings.eu_cookie_compliance.domain_all_sites ? '/' : Drupal.settings.basePath;
    var cookieName = (typeof eu_cookie_compliance_cookie_name === 'undefined' || eu_cookie_compliance_cookie_name === '') ? 'cookie-agreed' : eu_cookie_compliance_cookie_name;
    if (path.length > 1) {
      var pathEnd = path.length - 1;
      if (path.lastIndexOf('/') === pathEnd) {
        path = path.substring(0, pathEnd);
      }
    }

    var cookieSession = parseInt(Drupal.settings.eu_cookie_compliance.cookie_session);
    if (cookieSession) {
      $.cookie(cookieName, status, { path: path, domain: domain });
    }
    else {
      var lifetime = parseInt(Drupal.settings.eu_cookie_compliance.cookie_lifetime);
      date.setDate(date.getDate() + lifetime);
      $.cookie(cookieName, status, { expires: date, path: path, domain: domain });
    }
    _euccCurrentStatus = status;
    $(document).trigger('eu_cookie_compliance.changeStatus', [status]);
    // Status set means something happened, update the version.
    Drupal.eu_cookie_compliance.setVersion();

    // Store consent if applicable.
    if (Drupal.settings.eu_cookie_compliance.store_consent && ((status === cookieValueAgreedShowThankYou && Drupal.settings.eu_cookie_compliance.popup_agreed_enabled) || (status === cookieValueAgreed  && !Drupal.settings.eu_cookie_compliance.popup_agreed_enabled))) {
      var url = Drupal.settings.basePath + Drupal.settings.pathPrefix + 'eu-cookie-compliance/store_consent/banner';
      $.post(url, {}, function (data) { });
    }

    // Make a new observer & fire it to allow other scripts to hook in.
    var postStatusSaveObject = new PostStatusSave();
    self.handleEvent('postStatusSave', postStatusSaveObject);

    if (status === cookieValueDisagreed && Drupal.settings.eu_cookie_compliance.method === 'opt_out') {
      euCookieComplianceBlockCookies = setInterval(Drupal.eu_cookie_compliance.BlockCookies, 5000);
    }
  };

  Drupal.eu_cookie_compliance.setAcceptedCategories = function (categories) {

    // Make a new observer & fire it to allow other scripts to hook in.
    var prePreferencesSaveObject = new PrePreferencesSave();
    self.handleEvent('prePreferencesSave', prePreferencesSaveObject);

    var date = new Date();
    var domain = Drupal.settings.eu_cookie_compliance.domain ? Drupal.settings.eu_cookie_compliance.domain : '';
    var path = Drupal.settings.eu_cookie_compliance.domain_all_sites ? '/' : Drupal.settings.basePath;
    var cookieName = (typeof eu_cookie_compliance_cookie_name === 'undefined' || eu_cookie_compliance_cookie_name === '') ? 'cookie-agreed-categories' : Drupal.settings.eu_cookie_compliance.cookie_name + '-categories';
    if (path.length > 1) {
      var pathEnd = path.length - 1;
      if (path.lastIndexOf('/') === pathEnd) {
        path = path.substring(0, pathEnd);
      }
    }
    var categoriesString = JSON.stringify(categories);
    var cookie_session = parseInt(Drupal.settings.eu_cookie_compliance.cookie_session);
    if (cookie_session) {
      $.cookie(cookieName, categoriesString, { path: path, domain: domain });
    }
    else {
      var lifetime = parseInt(Drupal.settings.eu_cookie_compliance.cookie_lifetime);
      date.setDate(date.getDate() + lifetime);
      $.cookie(cookieName, categoriesString, { expires: date, path: path, domain: domain });
    }
    _euccSelectedCategories = categories;
    $(document).trigger('eu_cookie_compliance.changePreferences', [categories]);

    // TODO: Store categories with consent if applicable?
    // Make a new observer & fire it to allow other scripts to hook in.
    var postPreferencesSaveObject = new PostPreferencesSave();
    self.handleEvent('postPreferencesSave', postPreferencesSaveObject);
  };

  Drupal.eu_cookie_compliance.hasAgreed = function (category) {
    var agreed = (_euccCurrentStatus === 1 || _euccCurrentStatus === 2);

    if (category !== undefined && agreed) {
      agreed = Drupal.eu_cookie_compliance.hasAgreedWithCategory(category);
    }

    return agreed;
  };

  Drupal.eu_cookie_compliance.hasAgreedWithCategory = function (category) {
    return $.inArray(category, _euccSelectedCategories) !== -1;
  };

  Drupal.eu_cookie_compliance.showBanner = function () {
    var showBanner = false;
    if ((_euccCurrentStatus === 0 && Drupal.settings.eu_cookie_compliance.method === 'default') || _euccCurrentStatus === null) {
      if (!Drupal.settings.eu_cookie_compliance.disagree_do_not_show_popup || _euccCurrentStatus === null) {
        showBanner = true;
      }
    }
    else if (_euccCurrentStatus === 1 && Drupal.settings.eu_cookie_compliance.popup_agreed_enabled) {
      showBanner = true;
    }
    else if (_euccCurrentStatus === 2 && Drupal.settings.eu_cookie_compliance.withdraw_enabled) {
      showBanner = true;
    }

    return showBanner;
  };

  Drupal.eu_cookie_compliance.cookiesEnabled = function () {
    var cookieEnabled = navigator.cookieEnabled;
    if (typeof navigator.cookieEnabled === 'undefined' && !cookieEnabled) {
      document.cookie = 'testCookie';
      cookieEnabled = (document.cookie.indexOf('testCookie') !== -1);
    }

    return cookieEnabled;
  };

  Drupal.eu_cookie_compliance.cookieMatches = function (cookieName, pattern) {
    if (cookieName === pattern) {
      return true;
    }
    if (pattern.indexOf('*') < 0) {
      return false;
    }
    try {
      var regexp = new RegExp('^' + pattern.replace(/\./g, '\\.').replace(/\*/g, '.+') + '$', 'g');
      return regexp.test(cookieName);
    }
    catch (err) {
      return false;
    }
  };

  Drupal.eu_cookie_compliance.isAllowed = function (cookieName) {
    // Skip the PHP session cookie.
    if (cookieName.indexOf('SESS') === 0 || cookieName.indexOf('SSESS') === 0) {
      return true;
    }
    // Split the allowed cookies.
    var euCookieComplianceAllowlist = Drupal.settings.eu_cookie_compliance.allowed_cookies.split(/\r\n|\n|\r/g);

    // Add the EU Cookie Compliance cookie.
    euCookieComplianceAllowlist.push((typeof Drupal.settings.eu_cookie_compliance.cookie_name === 'undefined' || Drupal.settings.eu_cookie_compliance.cookie_name === '') ? 'cookie-agreed' : Drupal.settings.eu_cookie_compliance.cookie_name);
    euCookieComplianceAllowlist.push((typeof Drupal.settings.eu_cookie_compliance.cookie_name === 'undefined' || Drupal.settings.eu_cookie_compliance.cookie_name === '') ? 'cookie-agreed-categories' : Drupal.settings.eu_cookie_compliance.cookie_name + '-categories');
    euCookieComplianceAllowlist.push((typeof Drupal.settings.eu_cookie_compliance.cookie_name === 'undefined' || Drupal.settings.eu_cookie_compliance.cookie_name === '') ? 'cookie-agreed-version' : Drupal.settings.eu_cookie_compliance.cookie_name + '-version');

    // Check if the cookie is allowed.
    for (var item in euCookieComplianceAllowlist) {
      // Defensively check types for comparison.
      if (typeof euCookieComplianceAllowlist[item] === "string") {
        if (Drupal.eu_cookie_compliance.cookieMatches(cookieName, euCookieComplianceAllowlist[item])) {
          return true;
        }
        // Handle cookie names that are prefixed with a category.
        if (Drupal.settings.eu_cookie_compliance.method === 'categories') {
          var separatorPos = euCookieComplianceAllowlist[item].indexOf(":");
          if (separatorPos !== -1) {
            var category = euCookieComplianceAllowlist[item].substr(0, separatorPos);
            var wlCookieName = euCookieComplianceAllowlist[item].substr(separatorPos + 1);

            if (Drupal.eu_cookie_compliance.cookieMatches(cookieName, wlCookieName) && Drupal.eu_cookie_compliance.hasAgreedWithCategory(category)) {
              return true;
            }
          }
        }
      }
    }

    return false;
  }

  // This code upgrades the cookie agreed status when upgrading for an old version.
  Drupal.eu_cookie_compliance.updateCheck = function () {
    var legacyCookie = 'cookie-agreed-' + Drupal.settings.eu_cookie_compliance.popup_language;
    var domain = Drupal.settings.eu_cookie_compliance.domain ? Drupal.settings.eu_cookie_compliance.domain : '';
    var path = Drupal.settings.eu_cookie_compliance.domain_all_sites ? '/' : Drupal.settings.basePath;
    var cookie = $.cookie(legacyCookie);
    var date = new Date();
    var cookieName = (typeof eu_cookie_compliance_cookie_name === 'undefined' || eu_cookie_compliance_cookie_name === '') ? 'cookie-agreed' : eu_cookie_compliance_cookie_name;

    // jQuery.cookie 1.0 (bundled with Drupal) returns null,
    // jQuery.cookie 1.4.1 (bundled with some themes) returns undefined.
    // We had a 1.4.1 related bug where the value was set to 'null' (string).
    if (cookie !== undefined && cookie !== null && cookie !== 'null') {
      date.setDate(date.getDate() + parseInt(Drupal.settings.eu_cookie_compliance.cookie_lifetime));
      $.cookie(cookieName, cookie, { expires: date, path:  path, domain: domain });

      // Use removeCookie if the function exists.
      if (typeof $.removeCookie !== 'undefined') {
        $.removeCookie(legacyCookie);
      }
      else {
        $.cookie(legacyCookie, null, { path: path, domain: domain });
      }
    }
  };

  Drupal.eu_cookie_compliance.getVersion = function () {
    var cookieName = (typeof Drupal.settings.eu_cookie_compliance.cookie_name === 'undefined' || Drupal.settings.eu_cookie_compliance.cookie_name === '') ? 'cookie-agreed-version' : Drupal.settings.eu_cookie_compliance.cookie_name + '-version';
    return $.cookie(cookieName);
  };

  Drupal.eu_cookie_compliance.setVersion = function () {
    var date = new Date();
    var domain = Drupal.settings.eu_cookie_compliance.domain ? Drupal.settings.eu_cookie_compliance.domain : '';
    var path = Drupal.settings.eu_cookie_compliance.domain_all_sites ? '/' : Drupal.settings.basePath;
    var cookieName = (typeof Drupal.settings.eu_cookie_compliance.cookie_name === 'undefined' || Drupal.settings.eu_cookie_compliance.cookie_name === '') ? 'cookie-agreed-version' : Drupal.settings.eu_cookie_compliance.cookie_name + '-version';

    if (path.length > 1) {
      var pathEnd = path.length - 1;
      if (path.lastIndexOf('/') === pathEnd) {
        path = path.substring(0, pathEnd);
      }
    }
    var eucc_version = Drupal.settings.eu_cookie_compliance.cookie_policy_version;
    var cookie_session = parseInt(Drupal.settings.eu_cookie_compliance.cookie_session);
    if (cookie_session) {
      $.cookie(cookieName, eucc_version, { path: path, domain: domain });
    }
    else {
      var lifetime = parseInt(Drupal.settings.eu_cookie_compliance.cookie_lifetime);
      date.setDate(date.getDate() + lifetime);
      $.cookie(cookieName, eucc_version, { expires: date, path: path, domain: domain });
    }
  };

  // Load blocked scripts if the user has agreed to being tracked.
  var euCookieComplianceHasLoadedScripts = false;
  var euCookieComplianceHasLoadedScriptsForCategory = [];
  $(function () {
    if (Drupal.eu_cookie_compliance.hasAgreed()
        || (_euccCurrentStatus === null && Drupal.settings.eu_cookie_compliance.method !== 'opt_in' && Drupal.settings.eu_cookie_compliance.method !== 'categories')
    ) {
      if (typeof euCookieComplianceLoadScripts === "function") {
        euCookieComplianceLoadScripts();
      }
      euCookieComplianceHasLoadedScripts = true;

      if (Drupal.settings.eu_cookie_compliance.method === 'categories') {
        Drupal.eu_cookie_compliance.loadCategoryScripts(_euccSelectedCategories);
      }
    }
  });

  // Block cookies when the user hasn't agreed.
  Drupal.behaviors.eu_cookie_compliance_popup_block_cookies = {
    initialized: false,
    attach: function (context, settings) {
      if (!Drupal.behaviors.eu_cookie_compliance_popup_block_cookies.initialized && settings.eu_cookie_compliance) {
        Drupal.behaviors.eu_cookie_compliance_popup_block_cookies.initialized = true;
        if (settings.eu_cookie_compliance.automatic_cookies_removal &&
          ((settings.eu_cookie_compliance.method === 'opt_in' && (_euccCurrentStatus === null || !Drupal.eu_cookie_compliance.hasAgreed()))
            || (settings.eu_cookie_compliance.method === 'opt_out' && !Drupal.eu_cookie_compliance.hasAgreed() && _euccCurrentStatus !== null)
          || (Drupal.settings.eu_cookie_compliance.method === 'categories'))
        ) {
          // Split the allowed cookies.
          var euCookieComplianceAllowlist = settings.eu_cookie_compliance.allowed_cookies.split(/\r\n|\n|\r/g);

          // Add the EU Cookie Compliance cookie.
          var cookieName = (typeof eu_cookie_compliance_cookie_name === 'undefined' || eu_cookie_compliance_cookie_name === '') ? 'cookie-agreed' : eu_cookie_compliance_cookie_name;
          euCookieComplianceAllowlist.push(cookieName);

          euCookieComplianceBlockCookies = setInterval(Drupal.eu_cookie_compliance.BlockCookies, 5000);
        }
      }
    }
  }

  Drupal.eu_cookie_compliance.BlockCookies = function () {
    // Load all cookies from jQuery.
    var cookies = $.cookie();

    // Check each cookie and try to remove it if it's not allowed.
    for (var i in cookies) {
      var remove = true;
      var hostname = window.location.hostname;
      var cookieRemoved = false;
      var index = 0;

      remove = !Drupal.eu_cookie_compliance.isAllowed(i);

      // Remove the cookie if it's not allowed.
      if (remove) {
        while (!cookieRemoved && hostname !== '') {
          // Attempt to remove.
          cookieRemoved = $.removeCookie(i, { domain: '.' + hostname, path: '/' });
          if (!cookieRemoved) {
            cookieRemoved = $.removeCookie(i, { domain: hostname, path: '/' });
          }

          index = hostname.indexOf('.');

          // We can be on a sub-domain, so keep checking the main domain as well.
          hostname = (index === -1) ? '' : hostname.substring(index + 1);
        }

        // Some jQuery Cookie versions don't remove cookies well.  Try again
        // using plain js.
        if (!cookieRemoved) {
          document.cookie = i + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/;';
        }
      }
    }
  }

  /**
   * Filter the event listeners by event name and return the list of handlers.
   *
   * @param forEventName
   *
   * @returns {[]}
   */
  var filterQueue = function (forEventName) {
    var handlers = [];
    if (typeof Drupal.eu_cookie_compliance !== 'undefined' &&
      typeof Drupal.eu_cookie_compliance.queue !== 'undefined' &&
      Drupal.eu_cookie_compliance.queue.length) {
      // Loop over the list of arguments (objects) pushed into the queue.
      for (var i = 0; i < Drupal.eu_cookie_compliance.queue.length; i++) {
        if (Drupal.eu_cookie_compliance.queue[i].length) {
          var queueItem = Drupal.eu_cookie_compliance.queue[i];
          var eventName = queueItem[0];
          var eventHandler = queueItem[1];
          // If the first element is a string and the second is a function.
          if (typeof eventName === 'string' && typeof eventHandler === 'function') {
            // And the string matches the event name.
            if (eventName === forEventName) {
              // Return the functions so they can be executed.
              handlers.push(eventHandler);
            }
          }
        }
      }
    }
    return handlers;
  }

  /**
   * Handle event by finding and executing handlers pushed to the queue.
   */
  self.handleEvent = function (eventName, observer) {
    var handlers = filterQueue(eventName);
    for (var i = 0; i < handlers.length; i++) {
      if (typeof handlers[i] !== 'undefined') {
        observer.subscribe(handlers[i]);
        observer.fire({
          currentStatus: _euccCurrentStatus,
          currentCategories: _euccSelectedCategories
        });
        observer.unsubscribe(handlers[i]);
      }
    }
  };

  /**
   * Observer: triggered before status gets read from cookie.
   */
  var PreStatusLoad = (function () {
    // Constructor.
    var PreStatusLoad = function () {
      // Observers.
      this.handlers = [];
    };
    // Convenience var for the prototype.
    var prototype = PreStatusLoad.prototype;
    prototype.subscribe = function (fn) {
      this.handlers.push(fn);
    };
    prototype.unsubscribe = function (fn) {
      this.handlers = this.handlers.filter(
        function (item) {
          if (item !== fn) {
            return item;
          }
        }
      );
    };
    prototype.fire = function (o, thisObj) {
      var scope = thisObj || window;
      this.handlers.forEach(function (item) {
        item.call(scope, o);
      });
    };
    return PreStatusLoad;
  })();

  /**
   * Observer: triggered after status was read from cookie and stored in private variable.
   */
  var PostStatusLoad = (function () {
    // Constructor.
    var PostStatusLoad = function () {
      // Observers.
      this.handlers = [];
    };
    // Convenience var for the prototype.
    var prototype = PostStatusLoad.prototype;
    prototype.subscribe = function (fn) {
      this.handlers.push(fn);
    };
    prototype.unsubscribe = function (fn) {
      this.handlers = this.handlers.filter(
        function (item) {
          if (item !== fn) {
            return item;
          }
        }
      );
    };
    prototype.fire = function (o, thisObj) {
      var scope = thisObj || window;
      this.handlers.forEach(function (item) {
        item.call(scope, o);
      });
    };
    return PostStatusLoad;
  })();

  /**
   * Observer: triggered before status gets saved into cookie.
   */
  var PreStatusSave = (function () {
    // Constructor.
    var PreStatusSave = function () {
      // Observers.
      this.handlers = [];
    };
    // Convenience var for the prototype.
    var prototype = PreStatusSave.prototype;
    prototype.subscribe = function (fn) {
      this.handlers.push(fn);
    };
    prototype.unsubscribe = function (fn) {
      this.handlers = this.handlers.filter(
        function (item) {
          if (item !== fn) {
            return item;
          }
        }
      );
    };
    prototype.fire = function (o, thisObj) {
      var scope = thisObj || window;
      this.handlers.forEach(function (item) {
        item.call(scope, o);
      });
    };
    return PreStatusSave;
  })();

  /**
   * Observer: triggered after status was saved into cookie.
   */
  var PostStatusSave = (function () {
    // Constructor.
    var PostStatusSave = function () {
      // Observers.
      this.handlers = [];
    };
    // Convenience var for the prototype.
    var prototype = PostStatusSave.prototype;
    prototype.subscribe = function (fn) {
      this.handlers.push(fn);
    };
    prototype.unsubscribe = function (fn) {
      this.handlers = this.handlers.filter(
        function (item) {
          if (item !== fn) {
            return item;
          }
        }
      );
    };
    prototype.fire = function (o, thisObj) {
      var scope = thisObj || window;
      this.handlers.forEach(function (item) {
        item.call(scope, o);
      });
    };
    return PostStatusSave;
  })();

  /**
   * Observer: triggered before categories are read from cookie.
   */
  var PrePreferencesLoad = (function () {
    // Constructor.
    var prePreferencesLoad = function () {
      // Observers.
      this.handlers = [];
    };
    // Convenience var for the prototype.
    var prototype = prePreferencesLoad.prototype;
    prototype.subscribe = function (fn) {
      this.handlers.push(fn);
    };
    prototype.unsubscribe = function (fn) {
      this.handlers = this.handlers.filter(
        function (item) {
          if (item !== fn) {
            return item;
          }
        }
      );
    };
    prototype.fire = function (o, thisObj) {
      var scope = thisObj || window;
      this.handlers.forEach(function (item) {
        item.call(scope, o);
      });
    };
    return prePreferencesLoad;
  })();

  /**
   * Observer: triggered after categories were read from cookie.
   */
  var PostPreferencesLoad = (function () {
    // Constructor.
    var postPreferencesLoad = function () {
      // Observers.
      this.handlers = [];
    };
    // Convenience var for the prototype.
    var prototype = postPreferencesLoad.prototype;
    prototype.subscribe = function (fn) {
      this.handlers.push(fn);
    };
    prototype.unsubscribe = function (fn) {
      this.handlers = this.handlers.filter(
        function (item) {
          if (item !== fn) {
            return item;
          }
        }
      );
    };
    prototype.fire = function (o, thisObj) {
      var scope = thisObj || window;
      this.handlers.forEach(function (item) {
        item.call(scope, o);
      });
    };
    return postPreferencesLoad;
  })();

  /**
   * Observer: triggered before categories are being saved to cookie.
   */
  var PrePreferencesSave = (function () {
    // Constructor.
    var prePreferencesSave = function () {
      // Observers.
      this.handlers = [];
    };
    // Convenience var for the prototype.
    var prototype = prePreferencesSave.prototype;
    prototype.subscribe = function (fn) {
      this.handlers.push(fn);
    };
    prototype.unsubscribe = function (fn) {
      this.handlers = this.handlers.filter(
        function (item) {
          if (item !== fn) {
            return item;
          }
        }
      );
    };
    prototype.fire = function (o, thisObj) {
      var scope = thisObj || window;
      this.handlers.forEach(function (item) {
        item.call(scope, o);
      });
    };
    return prePreferencesSave;
  })();

  /**
   * Observer: triggered after categories were saved to cookie.
   */
  var PostPreferencesSave = (function () {
    // Constructor.
    var postPreferencesSave = function () {
      // Observers.
      this.handlers = [];
    };
    // Convenience var for the prototype.
    var prototype = postPreferencesSave.prototype;
    prototype.subscribe = function (fn) {
      this.handlers.push(fn);
    };
    prototype.unsubscribe = function (fn) {
      this.handlers = this.handlers.filter(
        function (item) {
          if (item !== fn) {
            return item;
          }
        }
      );
    };
    prototype.fire = function (o, thisObj) {
      var scope = thisObj || window;
      this.handlers.forEach(function (item) {
        item.call(scope, o);
      });
    };
    return postPreferencesSave;
  })();

})(jQuery);
;/*})'"*/;/*})'"*/
(function ($) {
  'use strict';

  Drupal.behaviors.euccx = {
    attach: function (context, settings) {

      $(window).load(function () {
        Drupal.euccx.init();
      });

    }
  };

  Drupal.euccx = {};

  // Entry function for our script.
  // Delegates the jobs to other functions.
  Drupal.euccx.init = function () {
    // Check if our environment is valid and return if it's not
    if (!Drupal.euccx.verifyEnvironment()) {
      return;
    }
    Drupal.euccx.handleBanner();
    Drupal.euccx.handleCookieSettingsPage();
    Drupal.euccx.processStatus(Drupal.euccx.getCookieStatus());
  };

  // Since we are using the state of EU Cookie Compliance in multiple steps of
  // the process, we need to make sure that its main function is available.
  // This is important to avoid javascript errors in administrative pages where
  // the euccx block is loaded but the EUCC is "out of context".
  Drupal.euccx.verifyEnvironment = function () {
    return (typeof Drupal.eu_cookie_compliance !== 'undefined' &&
      Drupal.eu_cookie_compliance !== null);
  };

  /**
   * Helper function which returns true, if eucc uses opt-in by categories
   * method. This has several larger implications for us.
   *
   * See https://www.drupal.org/project/euccx/issues/3144073 for details.
   *
   * @return boolean
   */
  Drupal.euccx.usesCategories = function() {
    return Drupal.settings.eu_cookie_compliance.method === 'categories';
  }

  // Handle clicks on the main banner
  Drupal.euccx.handleBanner = function () {
    $(document).ready(function () {
      // When the user clicks on the agree button of the EU Cookie Compliance
      // module we consider it a "carte blanche" consent for all cookies that
      // are defined by our plugins. Instead of waiting for the next page
      // refresh, we can attach an event that unblocks everything right here,
      // right now.
      $('.agree-button').click(function () {
        Drupal.euccx.unblockAll();
        Drupal.euccx.yettUnblockAll();
      });

      // If the administrator did not enable the option in the admin interface
      // we do not need to assign any kind of actions to elements that have the
      // class "euccx-disable-all".
      if (!Drupal.settings.euccx.dab) {
        return;
      }
      // When the user clicks on the disagree button, all we need to do is set
      // our cookie to a blank value (by convention). This will tell prevent our
      // javascript from enabling anything that was blocked in the beginning.
      $('body').on('click', '.euccx-disable-all', function (e) {
        e.preventDefault();
        Drupal.euccx.setCookie('0');
        // We also need to call the decline action of the EU Cookie Compliance
        // module which will handle the status of EUCC and also close the banner
        // or do some other stuff depending on its settings.
        Drupal.eu_cookie_compliance.declineAction();
      });
    });
  };

  // If we are in the page where the cookie settings' block is included, we need
  // to do some stuff.
  Drupal.euccx.handleCookieSettingsPage = function () {
    var cookieBlock = $('#cookie-tabs');
    // If the cookie management block is not in the page, exit.
    // No need to run extra code for something that is not even in the page
    if (!cookieBlock.length) {
      return;
    }

    // Create the jquery ui tabs for the cookie management block
    cookieBlock.tabs();

    // Behaviour is different when using opt-in categories.
    if (!Drupal.euccx.usesCategories()) {
      // When opt-in categories are NOT used, we are offering switches
      // for each script.
      $('#sliding-popup').hide();
      // ... handle the switches
      Drupal.euccx.handleSwitches();
      // ... and attach functionality for the save key
      Drupal.euccx.handleCookieSettingsBehaviors();
    } else {
      // Special handling for category switches:
      Drupal.euccx.handleCategorySwitches();
    }
  };

  // The function that decides what to do with the current user's status.
  // Responsible for unblocking javascript when needed.
  Drupal.euccx.processStatus = function (status) {

    // If the main eucc cookie is not set, it means that the user has not agreed
    // to anything yet. Move on.
    // We also check if the status of cookie-eucc is equal to the string "0"
    // which means that the user denied the cookies.
    if (!status['cookie-eucc'] || status['cookie-eucc'] === '0') {
      // If the main cookie has not been set yet, we have no reason to override
      // the blocks yet. This way, if for example the user accepts all our
      // cookies we will not miss on a google adsense load.
      return;
    }

    // If the euccx cookie was never set but the eucc cookie was set (checked
    // for that above) it means that the user agreed to everything so we need to
    // unblock everything and move on.
    if (!status['cookie-euccx'] && !Drupal.euccx.usesCategories()) {
      Drupal.euccx.unblockAll();
      Drupal.euccx.yettUnblockAll();
      return;
    }

    // We are now in the case where both cookies are set. We need to surgically
    // unblock code depending on its plugin's settings.
    // We use getAcceptedCategoriesPluginNames() to respect opt-in categories
    // if used.
    var pluginNames = Drupal.euccx.getAcceptedCategoriesPluginNames();
    var settings = Drupal.settings.euccx;
    for (var i = 0; i < pluginNames.length; i++) {
      var currentPlugin = pluginNames[i];
      // If current plugin is not in the list of the plugins that the user chose
      // to keep enabled, we move on to the next plugin.
      if (status['cookie-euccx'] && status['cookie-euccx'].indexOf(currentPlugin) === -1) {
        Drupal.euccx.handleBlockOverrides(currentPlugin);
        continue;
      }


      // If the specific plugin has a YETT blacklist defined, we need to get it
      // and whitelist the set of rules
      var blacklist = false;
      if (settings['plugins'] && settings['plugins'][currentPlugin] &&
        settings['plugins'][currentPlugin]['blacklist']) {
        blacklist = settings['plugins'][currentPlugin]['blacklist'];
      }

      if (blacklist) {
        Drupal.euccx.yettUnblockPlugin(blacklist);
      }

      // If the specific plugin has a js_exclude list, there will be a function
      // defined that we need to call in order to run the scripts.
      var js_exclude = false;
      if (settings['plugins'] && settings['plugins'][currentPlugin] &&
        settings['plugins'][currentPlugin]['js_exclude']) {
        js_exclude = settings['plugins'][currentPlugin]['js_exclude'];
      }

      // Unblock if js_exclude OR no specific cookie has been set
      // (which can only happen if using opt-in categories)
      if (js_exclude || !status['cookie-euccx']) {
        Drupal.euccx.unblockPlugin(currentPlugin);
      }

    }
  };

  // Check whether our plugin has defined any block overrides. If it did, watch
  // the DOM for the selector and act accordingly.
  Drupal.euccx.handleBlockOverrides = function (plugin) {
    $(document).ready(function () {
      var settings = Drupal.settings.euccx;
      if (settings && settings['plugins']) {
        var plugins = [];
        if (plugin === '') {
          for (var pluginName in settings['plugins']) {
            if (!{}.hasOwnProperty.call(settings.plugins, pluginName)) {
              continue;
            }
            plugins.push(pluginName);
          }
        }
        else {
          if ({}.hasOwnProperty.call(settings.plugins, plugin)) {
            plugins.push(plugin);
          }
        }
        for (var i = 0; i < plugins.length; i++) {
          if (!{}.hasOwnProperty.call(
            settings['plugins'][plugins[i]],
            'overrides')) {
            continue;
          }
          for (var key in settings['plugins'][plugins[i]]['overrides']) {
            if (!{}.hasOwnProperty.call(
              settings['plugins'][plugins[i]]['overrides'], key)) {
              continue;
            }
            $(key)
              .empty()
              .append(settings['plugins'][plugins[i]]['overrides'][key]);
          }
        }
      }
    });
  };

  // Make sure that when the user hits the save button, it actually does
  // something.
  Drupal.euccx.handleCookieSettingsBehaviors = function () {
    $('body').on('click', '.cookie-settings-save', function (e) {
      try {
        e.preventDefault();
        // Make sure that the EU Cookie Compliance Module has set its cookie
        Drupal.eu_cookie_compliance.acceptAction();
        var plugin;
        // Create our cookie content
        // We need to at least have some content in the cookie in order to make
        // sure that we can check its contents easier later (if for example the
        // cookie was empty, it would not have been possible to check the user's
        // settings with a simple !status['cookie-euccx'].
        var cookieData = 'cookies-enabled:';
        $('#cookie-tabs input').each(function () {
          if ($(this).prop('checked')) {
            plugin = $(this).attr('name').match(/-[^-]+$/)[0].substring(1);
            cookieData += plugin + '|';
          }
        });
        // ... set our cookie
        Drupal.euccx.setCookie(cookieData);
        // ... and reload the page so that the user gets some feedback of
        // something happening and if for example he enabled google analytics it
        // records the visit.
        location.reload();
      }
      catch (error) {
        // console.log(error)
      }
    });
  };

  // Check the cookies that are stored in the user's browser and a return an
  // object with all the relevant information.
  Drupal.euccx.getCookieStatus = function () {
    var status = {};
    var cookieName = (typeof eu_cookie_compliance_cookie_name === 'undefined' ||
      eu_cookie_compliance_cookie_name === '') ?
      'cookie-agreed' :
      eu_cookie_compliance_cookie_name;
    var cookieEUCC = Drupal.euccx.getCookie(cookieName);
    var cookieEUCCX = Drupal.euccx.getCookie('cookie-extras-agreed');

    status['cookie-eucc'] = cookieEUCC;
    status['cookie-euccx'] = cookieEUCCX;
    if (typeof cookieEUCCX === 'string') {
      var pluginNames = Drupal.euccx.getPluginNames();
      for (var i = 0; i < pluginNames.length; i++) {
        status[pluginNames[i]] = (cookieEUCCX.indexOf(pluginNames[i]) !== -1);
      }
    }
    return status;
  };

  // Unblocks all plugins that used yett
  Drupal.euccx.yettUnblockAll = function () {
    if (!window.yett) {
      return;
    }
    window.yett.unblock();
  };

  // Whitelist a specific set of scripts that were blocked via yett
  Drupal.euccx.yettUnblockPlugin = function (rules) {
    if (!window.yett) {
      return;
    }
    // This should work now after a modification was made to the yett library.
    // See: https://github.com/snipsco/yett/issues/11 for more info on what the
    // problem was and how it was solved in 0.1.8 version of yett.

    // Convert rules to RegExps
    var regexp_rules = rules.map(function(rule) {
      // Strip leading/trailing slash.
      rule = rule.replace(/^\/(.+)\/$/, "$1");
      return new RegExp(rule);
    });

    window.yett.unblock.apply(this, regexp_rules);
  };

  // Unblock all plugins
  Drupal.euccx.unblockAll = function () {
    var plugins = Drupal.euccx.getPluginNames();
    for (var i = 0; i < plugins.length; i++) {
      Drupal.euccx.unblockPlugin(plugins[i]);
    }
  };

  /**
   * Returns a unique list of all accepted categories plugin names.
   * If categories are not used as opt-in method, returns all plugins.
   *
   * @return []
   */
  Drupal.euccx.getAcceptedCategoriesPluginNames = function () {
    var plugins = [];
    var categoryPlugins;
    if (Drupal.euccx.usesCategories()) {
      // Opt-in by categories is used, we may only unblock all from allowed
      // categories:
      if(!Drupal.eu_cookie_compliance.hasAgreed()){
        // We can return early here, nothing accepted at all!
        return [];
      }
      var acceptedCategories = Drupal.eu_cookie_compliance.getAcceptedCategories();
      for (var a = 0; a < acceptedCategories.length; a++) {
        categoryPlugins = Drupal.euccx.getPluginNamesByOptInCategory(acceptedCategories[a]);
        if(categoryPlugins && categoryPlugins.length > 0){
          plugins = plugins.concat(categoryPlugins.filter(function(el) {
            return plugins.indexOf(el) === -1;
          }));
        }
      }
    } else {
      // Not using categories, all defined plugins are accepted:
      plugins = Drupal.euccx.getPluginNames();
    }
    return plugins;
  };

  /**
   * Return an array of the plugin names that are in a given category.
   *
   * @param optInCategory The machine name of the eucc opt-in category
   * @return []
   */
  Drupal.euccx.getPluginNamesByOptInCategory = function (optInCategory) {
    if (Drupal.settings.euccx && Drupal.settings.euccx.plugins) {
      var pluginNames = [];
      for (var key in Drupal.settings.euccx.plugins) {
        if ({}.hasOwnProperty.call(Drupal.settings.euccx.plugins, key)) {
           if (Drupal.settings.euccx.plugins[key].opt_in_category == optInCategory) {
            pluginNames.push(key);
          }
        }
      }
      return pluginNames;
    }
    return false;
  };

  // Given a plugin name execute the function that will unblock its code
  Drupal.euccx.unblockPlugin = function (pluginName) {
    var functionName = 'euccx' + pluginName + 'Load';
    try {
      window[functionName]();
    }
    catch (e) {
      // console.log(e);
    }
  };

  // Return an array of the plugin names that are defined
  Drupal.euccx.getPluginNames = function () {
    if (Drupal.settings.euccx && Drupal.settings.euccx.plugins) {
      var pluginNames = [];
      for (var key in Drupal.settings.euccx.plugins) {
        if ({}.hasOwnProperty.call(Drupal.settings.euccx.plugins, key)) {
          pluginNames.push(key);
        }
      }
      return pluginNames;
    }
    return false;
  };

  // Return false when the cookie is not properly set or the cookie value when
  // it is (properly set).
  Drupal.euccx.getCookie = function (cookieName) {
    var cookieValue = $.cookie(cookieName);
    if (typeof (cookieValue) === 'undefined' || (cookieValue === null)) {
      return false;
    }
    return cookieValue;
  };

  // This is using the exact same code with EU Cookie since our cookie is also
  // respecting most of the settings that the user supplied in EU Cookie
  // Compliance module.
  Drupal.euccx.setCookie = function (content) {
    try {
      var date = new Date();
      var domain = Drupal.settings.eu_cookie_compliance.domain ?
        Drupal.settings.eu_cookie_compliance.domain :
        '';
      var path = Drupal.settings.basePath;
      var cookieName = 'cookie-extras-agreed';
      if (path.length > 1) {
        var pathEnd = path.length - 1;
        if (path.lastIndexOf('/') === pathEnd) {
          path = path.substring(0, pathEnd);
        }
      }
      var cookieSession = parseInt(
        Drupal.settings.eu_cookie_compliance.cookie_session
      );

      if (cookieSession) {
        $.cookie(cookieName, content, {path: path, domain: domain});
      }
      else {
        var lifetime = parseInt(
          Drupal.settings.eu_cookie_compliance.cookie_lifetime
        );
        date.setDate(date.getDate() + lifetime);
        $.cookie(cookieName, content, {
          expires: date,
          path: path,
          domain: domain
        });
      }

      // Store consent if applicable.
      if (Drupal.settings.eu_cookie_compliance.store_consent) {
        var url = Drupal.settings.basePath;
        url += Drupal.settings.pathPrefix;
        url += 'eu-cookie-compliance/store_consent/banner';

        $.post(url, {}, function (data) { });
      }
    }
    catch (e) {
      // console.log(e);
    }
  };

  // The switches in the block are always set to off. It's up to us to turn them
  // on, if the cookie stored tells us so.
  Drupal.euccx.handleSwitches = function () {
    // If the cookie is not set, just turn them on by default
    var cookieValue = Drupal.euccx.getCookie('cookie-extras-agreed');
    // If the cookie has never been set, we need to see if the user selected to
    // have the switches turned on or off by default
    // see: https://www.drupal.org/project/euccx/issues/3092522
    // If the user has already accepted the cookies in general (aka from the EU
    // Cookie Compliance button) then there is no reason to respect the
    // unticked option. For more information on the reasoning behind that
    // see: https://www.drupal.org/project/euccx/issues/3109741
    if (!cookieValue) {
      if (Drupal.settings.euccx.unticked && !Drupal.eu_cookie_compliance.hasAgreed()) {
        $('#cookie-tabs input').prop('checked', false);
      }
      else {
        $('#cookie-tabs input').prop('checked', true);
      }
    }
    else {
      var plugins = Drupal.settings.euccx.plugins;
      for (var key in plugins) {
        if ({}.hasOwnProperty.call(plugins, key)) {
          var input = $("input[name*='" + key + "']");
          if (input.length && (cookieValue.indexOf(key) !== -1)) {
            input.prop('checked', true);
          }
        }
      }
    }
  };

  /**
   * Handles the switches if eucc opt-in with categories is used.
   * In this case the switches are simple indicatory for the eucc category
   * status.
   */
  Drupal.euccx.handleCategorySwitches = function () {
    // Open the cookie popup whenever a pseudo switch is clicked.
    $("#cookie-tabs .euccx-slider").click(Drupal.eu_cookie_compliance.toggleWithdrawBanner);

    // Mark plugins from allowed categories as active (passively):
    var plugins = Drupal.euccx.getAcceptedCategoriesPluginNames();
    for (var i = 0; i < plugins.length; i++) {
      var currentPlugin = plugins[i];
      var $aliasSlider = $("#cookie-tabs .euccx-slider.euccx-slider-" + currentPlugin);
      if ($aliasSlider.length > 0) {
        $aliasSlider.addClass('euccx-slider-checked');
      }
    }
  };

  // Check our settings for cookies that plugins declared as being offensive.
  // If the pluginName is empty, return offending cookies from all enabled
  // plugins.
  // Note: this function screens out non-enabled plugins.
  Drupal.euccx.getOffendingCookies = function (pluginName) {
    var offendingCookies = [];
    var settings = Drupal.settings.euccx;
    var pluginNames = Drupal.euccx.getPluginNames();
    for (var i = 0; i < pluginNames.length; i++) {
      var currentPlugin = pluginNames[i];
      var cookies_handled = false;
      if (settings['plugins'] && settings['plugins'][currentPlugin] &&
        settings['plugins'][currentPlugin]['cookies_handled']) {
        cookies_handled = settings['plugins'][currentPlugin]['cookies_handled'];
      }

      // The below check translates to: if the plugin uses the cookies_handled
      // key AND it's an array AND (either this function was called for all
      // plugins or the plugin that it was called for is the one we're
      // checking right now), add the offending cookies to our array.
      if (cookies_handled && cookies_handled.constructor === Array &&
        (pluginName === '' || pluginName === pluginNames[i])) {
        offendingCookies = offendingCookies.concat(cookies_handled);
      }
    }
    return offendingCookies;
  };

  // We remove the offending cookies by setting their expiration date to the
  // past and their content to "null".
  // This is very similar to the functionality provided by the EU Cookie
  // Compliance module. The core differences are:
  // 1) Since the new version of jquery.cookie that you get through
  // jquery_update does not support removeCookie but instead allows you to
  // remove cookies by setting their value to null, we are using this new method
  // as fallback and are also setting the expiration date to the past.
  // 2) Since some cookies may be registered in both the subdomain but also the
  // root domain, we are blanket-replacing the cookie names that were defined by
  // our plugins.
  Drupal.behaviors.euccxRemoveOffendingCookies = {
    attach: function (context, settings) {
      $(document).ready(function () {
        var status = Drupal.euccx.getCookieStatus();
        var offendingCookies = [];
        // Check if there is an EU Cookie Compliance cookie. If there is not,
        // all cookies defined in our plugins, should be considered offending
        // cookies because the user has not agreed to anything yet.
        if (!status['cookie-eucc']) {
          offendingCookies = Drupal.euccx.getOffendingCookies('');
        }
        // If there is no euccx cookies but there is an eucc cookie, it means
        // that the user agreed to everything. However, if there is an eucc and
        // an euccx cookie, we need to dig a little deeper.
        else if (status['cookie-euccx']) {
          var pluginNames = Drupal.euccx.getPluginNames();
          for (let i = 0; i < pluginNames.length; i++) {
            var currentPlugin = pluginNames[i];
            // We only push the offending cookies of the current plugin, if the
            // plugin name is absent from our cookie.
            if (status['cookie-euccx'].indexOf(currentPlugin) === -1) {
              offendingCookies =
                Drupal.euccx.getOffendingCookies(currentPlugin);
            }
          }
        }
        // Loop through any offending cookie names that we've found above
        for (let i = 0; i < offendingCookies.length; i++) {
          var hostname = window.location.hostname;
          var index = 0;
          var ctd = offendingCookies[i];
          while (hostname !== '') {
            // Check if jQuery.removeCookie is available:
            if (typeof $.removeCookie !== typeof undefined) {
              // jQuery.removeCookie exists!
              // Remove the cookie entirely:
              $.removeCookie(ctd, {
                path: '/',
                domain: '.' + hostname
              });
              $.removeCookie(ctd, {
                path: '/',
                domain: hostname
              });
            } else {
              // Fallback if jQuery.removeCookie is not available.
              // Set the cookies content to null.
              // Only set the value if the cookie exists, otherwise we'd
              // create a new empty cookie here:
              if ($.cookie(ctd) !== typeof undefined) {
                // For subdomain:
                $.cookie(ctd, null, {
                  expires: -5,
                  domain: '.' + hostname,
                  path: '/'}
                );
                // For domain:
                $.cookie(ctd, null, {
                  expires: -5,
                  domain: hostname,
                  path: '/'}
                );
              }
            }
            index = hostname.indexOf('.');
            hostname = (index === -1) ? '' : hostname.substring(index + 1);
          }
        }
      });
    }
  };
})(jQuery);
;/*})'"*/;/*})'"*/
/**
 * @file
 * Special integration for EU Cookie Compliance module.
 *
 */
(function ($, Drupal, undefined) {
  'use strict';

  /**
   * Changes the passed jQuery element to another HTML type.
   */
  function _change_type($el, new_type) {
    let attrs = {};

    $.each($el[0].attributes, function(idx, attr){
      attrs[attr.nodeName] = attr.nodeValue;
    });

    $el.replaceWith(function() {
      return $('<' + new_type + ' />', attrs).append($(this).contents()).show();
    });
  }

  // Bail if EU CC is not present!
  if (!Drupal.eu_cookie_compliance) {
    if (console.log) {
      console.log("Error: Drupal.eu_cookie_compliance is not defined!");
    }
    return;
  }

  /**
   * Handle elements that can only be enabled if the relavent consent has
   * been given.
   */
  Drupal.behaviors.dailyukomegaCookieconsent = {
    attach: function (context, settings) {
      // todo This should go into a Daily UK module.
      let $dukEls = $('duk-content-el', context);
      let consentedCats = Drupal.eu_cookie_compliance.getAcceptedCategories();

      $dukEls.each(function(idx){
        let $thisEl = $(this);
        if ($thisEl.data('duk-cc') && $thisEl.data('type') ) {
          if (consentedCats.indexOf($thisEl.data('duk-cc')) != -1 ) {
            _change_type($thisEl, $thisEl.data('type'));
          }
        }
      });

    }
  };

  // Monkey patch EU Cookie Consent
  var _orig_initPopup = Drupal.eu_cookie_compliance.initPopup;
  Drupal.eu_cookie_compliance.initPopup = function () {
    _orig_initPopup();

    var $menu = $('.l-region--footer-smallprint .pane-menu-menu-footer .menu').first();
    if ($menu.length) {
      // Hide the original tab button because we will add our own link.
      $('.eu-cookie-withdraw-tab').hide();

      $menu.once('domega-eu-cookie-settings', function(){
        var $cookieSettingsWrapper = $('<li class="domega-eu-cookie-settings-wrapper">' +
          '<a class="domega-eu-cookie-settings-toggle" href="#">Privacy Settings</a></li>');
        var $cookieSettingsLink = $cookieSettingsWrapper.find('a').first();
        $cookieSettingsLink.bind('click.domega-cc', function(e){
          e.preventDefault();
          Drupal.eu_cookie_compliance.toggleWithdrawBanner();
          return false;
        });
        $menu.append($cookieSettingsWrapper);
      });
    }
  };

  // We don't want the floating tab to ever show.
  Drupal.eu_cookie_compliance.positionTab = function () {
    return;
  };

  // Reformat the pop-up and add a "Manage" option
  let _orig_createPopup = Drupal.eu_cookie_compliance.createPopup;
  Drupal.eu_cookie_compliance.createPopup = function (html, closed) {
    _orig_createPopup(html, closed);
    let $popup = $('#sliding-popup');

    if (!$popup.length) return;

    let $cookieCategories = $popup.find('#eu-cookie-compliance-categories');
    let $catButtonsWrapper = $popup.find('.eu-cookie-compliance-categories-buttons');
    let $catSaveButton = $catButtonsWrapper.find('.eu-cookie-compliance-save-preferences-button');
    let $buttonsWrapper = $popup.find('#popup-buttons');
    let $manageButton = $('<button type="button" class="eu-cookie-compliance-manage-preferences-button">Manage preferences</button>');

    $catButtonsWrapper.append($manageButton).insertAfter($cookieCategories);

    // Put all the buttons together
    $buttonsWrapper.prepend($catButtonsWrapper);

    // Hide the categories.
    $cookieCategories.addClass('eu-cookie-compliance-hidden');
    $catSaveButton.addClass('eu-cookie-compliance-hidden');

    let _cat_vis_state = false;
    $manageButton.bind('click.toggleCats', function(e){
      e.preventDefault();
      $cookieCategories.toggleClass('eu-cookie-compliance-hidden');
      $catSaveButton.toggleClass('eu-cookie-compliance-hidden');
      this.blur();
    });
  }

})(jQuery, Drupal);
;/*})'"*/;/*})'"*/
