/* Minification failed. Returning unminified contents.
(11356,35-36): run-time error JS1195: Expected expression: )
(11356,38-39): run-time error JS1195: Expected expression: >
(11358,10-11): run-time error JS1195: Expected expression: )
(11371,52-53): run-time error JS1195: Expected expression: >
(11373,9-10): run-time error JS1002: Syntax error: }
(11395,9-10): run-time error JS1002: Syntax error: }
(11398,37-38): run-time error JS1004: Expected ';': {
(11404,34-35): run-time error JS1014: Invalid character: `
(11404,35-36): run-time error JS1014: Invalid character: #
(11404,37-38): run-time error JS1193: Expected ',' or ')': {
(11404,69-70): run-time error JS1014: Invalid character: `
(11404,70-71): run-time error JS1195: Expected expression: )
(11405,18-19): run-time error JS1195: Expected expression: ,
(11412,32-33): run-time error JS1014: Invalid character: `
(11412,76-77): run-time error JS1014: Invalid character: `
(11417,29-30): run-time error JS1195: Expected expression: )
(11417,32-33): run-time error JS1195: Expected expression: >
(11421,18-19): run-time error JS1195: Expected expression: ,
(11424,5-6): run-time error JS1002: Syntax error: }
(11426,30-31): run-time error JS1004: Expected ';': {
(11454,30-31): run-time error JS1014: Invalid character: `
(11454,31-32): run-time error JS1014: Invalid character: #
(11454,37-38): run-time error JS1193: Expected ',' or ')': {
(11454,45-46): run-time error JS1014: Invalid character: `
(11454,46-47): run-time error JS1195: Expected expression: )
(11455,13-14): run-time error JS1195: Expected expression: }
(11455,14-15): run-time error JS1195: Expected expression: ,
(11456,13-19): run-time error JS1197: Too many errors. The file might not be a JavaScript file: window
 */
// ==========================================================================
// Project:     Image Scale
// Description: Scale images to fit or fill any target size via two simple properties: scale and align.
// Copyright:   ©2012-2016 GestiXi
// License:     Licensed under the MIT license (see LICENCE)
// Version:     2.2
// Author:      Nicolas BADIA
// ==========================================================================

// Uses CommonJS, AMD or browser globals to create a jQuery plugin.
(function(factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['jquery'], factory);
  } 
  else if (typeof module === 'object' && module.exports) {
    // Node/CommonJS
    module.exports = function( root, jQuery ) {
      if ( jQuery === undefined ) {
        // require('jQuery') returns a factory that requires window to
        // build a jQuery instance, we normalize how we use modules
        // that require this pattern but the window provided is a noop
        // if it's defined (how jquery works)
        if (typeof window !== 'undefined') {
          jQuery = require('jquery');
        }
        else {
          jQuery = require('jquery')(root);
        }
      }
      factory(jQuery);
      return jQuery;
    };
  } 
  else {
    // Browser globals
    factory(jQuery);
  }
}(function($) {

  "use strict";

  // ..........................................................
  // IMAGE SCALE PLUGIN DEFINITION
  //

  $.fn.imageScale = function( options ) {

    return this.each(function() {
      var that = this,
        $this = $(this),
        data = $this.data('imageScale'),
        $img = this.tagName === 'IMG' ? $this : $this.find("img");

      if (!data) {
        var didLoad = $img[0].complete,
            formattedOpt = $.extend({}, $.fn.imageScale.defaults, typeof options == 'object' && options),

            loadFunc = function() {
              $this.data('imageScale', (data = new ImageScale(that, formattedOpt)));

              data.scale(true, formattedOpt);
            };

        if (didLoad) {
          loadFunc.apply($this[0]);
        }
        else {
          $img.on("load", loadFunc).attr("src", $img.attr("src"));
        }
      }
      else {
        if (typeof options == 'string') data[options]();
        else if (typeof options == 'object') {
          var method = options.method || 'scale';
          data[method](false, options);
        }
        else data.scale();
      }
    })
  }

  $.fn.imageScale.defaults = {
    /**
      Determines how the image will scale to fit within its containing space. Possible values:

      * **fill** - stretches or compresses the source image to fill the target frame
      * **best-fill** - fits the shortest side of the source image within the target frame while maintaining the original aspect ratio
      * **best-fit** - fits the longest edge of the source image within the target frame while maintaining the original aspect ratio
      * **best-fit-down** - same as *best-fit* but will not stretch the source if it is smaller than the target
      * **none** - the source image is left unscaled

      @type String
      @default best-fill
      @since Version 1.2
    */
    scale: 'best-fill',

    /**
      Align the image within its frame. Possible values:

      * **left**
      * **right**
      * **center**
      * **top**
      * **bottom**
      * **top-left**
      * **top-right**
      * **bottom-left**
      * **bottom-right**

      @type String
      @default center
      @since Version 1.2
    */
    align: 'center',

    /**
      A jQuery Object against which the image size will be calculated.
      If null, the parent of the image will be used.

      @type jQuery Object
      @default null
      @since Version 1.0
    */
    parent: null,

    /**
      A boolean determining if the parent should hide its overflow.

      @type Boolean
      @default true
      @since Version 1.0
    */
    hideParentOverflow: true,

    /**
      A duration in milliseconds determining how long the fadeIn animation will run when your image is scale for the firstTime.

      Set it to 0 if you don't want any animation.

      @type Number|String
      @default 0
      @since Version 1.1
    */
    fadeInDuration: 0,

    /**
      A boolean indicating if the image size should be rescaled when the window is resized.

      The window size is checked using requestAnimationFrame for good performance.

      Example:

          $images.imageScale({ 
            rescaleOnResize: true
          });
      
      @type Boolean
      @default false
      @since Version 1.0
    */
    rescaleOnResize: true,

    /**
      A function that will be call each time the receiver is scaled.

      Example:

          $images.imageScale({
            didScale: function() {
              console.log('did scale img: ', this.element);
            }
          });

      @type Function
      @param firstTime {Boolean} true if the image was scale for the first time.
      @param options {Object} the options passed to the scale method.
      @since Version 2.0
    */
    didScale: function(firstTime, options) {},

    /**
      A number indicating the log level :

      0: silent
      1: error
      2: error & warning
      3: error & warning & notice

      @type Number
      @default 0
      @since Version 1.0
    */
    logLevel: 0
  }

  // ..........................................................
  // IMAGE SCALE PUBLIC CLASS DEFINITION
  //

  var ImageScale = function(element, options) {
    var that = this;
    that.options = options;
    that.element = element;

    var $element = that.$element = $(element),
      $img = that.$img = element.tagName === 'IMG' ? $element : $element.find("img"),
      img = that.img = $img[0];

    that.src = $img.attr('src');

    that.imgWidth = img.naturalWidth || img.width;
    that.imgHeight = img.naturalHeight || img.height;

    var $parent = that.$parent = options.parent?options.parent:$($element.parent()[0]);
    that.parent = $parent[0];

    // Fixes: https://github.com/gestixi/image-scale/issues/1
    if ($parent.css('position') === 'static') {
      $parent.css('position', 'relative');
    }

    if (options.rescaleOnResize) {
      $(window).resize(function(e) { that.scheduleScale(); });
    }
  }

  $.fn.imageScale.Constructor = ImageScale;

  ImageScale.prototype = {

    NONE: "none",
    FILL: "fill",
    BEST_FILL: "best-fill",
    BEST_FIT: "best-fit",
    BEST_FIT_DOWN_ONLY: "best-fit-down",

    ALIGN_LEFT: 'left',
    ALIGN_RIGHT: 'right',
    ALIGN_CENTER: 'center',
    ALIGN_TOP: 'top',
    ALIGN_BOTTOM: 'bottom',
    ALIGN_TOP_LEFT: 'top-left',
    ALIGN_TOP_RIGHT: 'top-right',
    ALIGN_BOTTOM_LEFT: 'bottom-left',
    ALIGN_BOTTOM_RIGHT: 'bottom-right',

    constructor: ImageScale,

    /**
      The initial element.

      @type DOM Element
    */
    element: null,

    /**
      The passed options.

      @type Object
    */
    options: null,

    /**
      Main method. Used to scale the images.

      When `rescaleOnResize` is set to true, this method is executed each time the
      windows size changes.

      If `rescaleOnResize` is set to false, you may want to call it manually. Here is an
      example on how you should do it:

          $image.imageScale('scale');


      @param {Boolean} firstTime
    */
    scale: function(firstTime, opt) {
      if (this._isDestroyed || this._canScale === false) return;

      var that = this,
          options = this.options,
          $parent = this.$parent,
          element = this.element,
          $element = this.$element,
          img = this.img,
          $img = this.$img;

      if (firstTime) {
        if (options.hideParentOverflow) {
          $parent.css({ overflow: 'hidden' });
        }
      }
      else {
        // If the source of the image has changed
        if (this.src !== $img.attr('src')) {
          this.destroy();
          $element.data('imageScale', null);
          $element.imageScale(options);
          return;
        }
      }

      this._didScheduleScale = false;

      if (options.rescaleOnResize && !opt) {
        if (!this._needUpdate(this.parent)) return;
      }
      opt = opt ? opt : {};

      var transition = opt.transition;
      if (transition) {
        this._canScale = false;
        $element.css('transition', 'all '+transition+'ms');

        setTimeout(function() {
          that._canScale = null;
          $element.css('transition', 'null');
        }, transition);
      }

      var destWidth = opt.destWidth ? opt.destWidth : $parent.outerWidth(),
          destHeight = opt.destHeight ? opt.destHeight : $parent.outerHeight(),

          destInnerWidth = opt.destWidth ? opt.destWidth : $parent.innerWidth(),
          destInnerHeight = opt.destHeight ? opt.destHeight : $parent.innerHeight(),

          widthOffset = destWidth - destInnerWidth,
          heightOffset = destHeight - destInnerHeight,

          scaleData = $element.attr('data-scale'),
          alignData = $element.attr('data-align'),

          scale = scaleData?scaleData:options.scale,
          align = alignData?alignData:options.align,

          fadeInDuration = options.fadeInDuration;

      if (!scale) {
        if (options.logLevel > 2) {
          console.log("imageScale - DEBUG NOTICE: The scale property is null.", element);
        }
        return;
      }

      if (this._cacheDestWidth === destWidth && this._cacheDestHeight === destHeight) {
        if (options.logLevel > 2) {
          console.log("imageScale - DEBUG NOTICE: The parent size hasn't changed: dest width: '"+destWidth+"' - dest height: '"+destHeight+"'.", element);
        }
      }

      var sourceWidth = this.imgWidth,
          sourceHeight = this.imgHeight;

      if (!(destWidth && destHeight && sourceWidth && sourceHeight)) {
        if (options.logLevel > 0) {
          console.error("imageScale - DEBUG ERROR: The dimensions are incorrect: source width: '"+sourceWidth+"' - source height: '"+sourceHeight+"' - dest width: '"+destWidth+"' - dest height: '"+destHeight+"'.", element);
        }
        return;
      }

      this._cacheDestWidth = destWidth;
      this._cacheDestHeight = destHeight;

      var layout = this._innerFrameForSize(scale, align, sourceWidth, sourceHeight, destWidth, destHeight);

      if (widthOffset) layout.x -= widthOffset/2;
      if (heightOffset) layout.y -= heightOffset/2;

      $element.css({ position: 'absolute', top: layout.y+'px', left: layout.x+'px', width: layout.width+'px', height: layout.height+'px', 'max-width': 'none' });

      if (firstTime && fadeInDuration) {
        $element.css({ display: 'none' });
        $element.fadeIn(fadeInDuration);
      }

      options.didScale.call(this, firstTime, opt);
    },

    /**
      Removes the data from the element.

      Here is an example on how you can call the destroy method:

          $image.imageScale('destroy');

    */
    destroy: function() {
      this._isDestroyed = true;
      this.$element.removeData('imageScale');
    },

    /**
      @private

      Returns a frame (x, y, width, height) fitting the source size (sourceWidth & sourceHeight) within the
      destination size (destWidth & destHeight) according to the align and scale properties.

      @param {String} scale
      @param {String} align
      @param {Number} sourceWidth
      @param {Number} sourceHeight
      @param {Number} destWidth
      @param {Number} destHeight
      @returns {Object} the inner frame with properties: { x: value, y: value, width: value, height: value }
    */
    _innerFrameForSize: function(scale, align, sourceWidth, sourceHeight, destWidth, destHeight) {
      var scaleX,
          scaleY,
          result;

      // Fast path
      result = { x: 0, y: 0, width: destWidth, height: destHeight };
      if (scale === this.FILL) return result;

      // Determine the appropriate scale
      scaleX = destWidth / sourceWidth;
      scaleY = destHeight / sourceHeight;

      switch (scale) {
        case this.BEST_FIT_DOWN_ONLY:
          if (scale !== this.BEST_FIT_DOWN_ONLY && this.options.logLevel > 1) {
            console.warn("imageScale - DEBUG WARNING: The scale '"+scale+"' was not understood.");
          }

          if ((sourceWidth > destWidth) || (sourceHeight > destHeight)) {
            scale = scaleX < scaleY ? scaleX : scaleY;
          } else {
            scale = 1.0;
          }
          break;
        case this.BEST_FIT:
          scale = scaleX < scaleY ? scaleX : scaleY;
          break;
        case this.NONE:
          scale = 1.0;
          break;
        //case this.BEST_FILL:
        default:
          scale = scaleX > scaleY ? scaleX : scaleY;
          break;
      }

      sourceWidth *= scale;
      sourceHeight *= scale;
      result.width = Math.round(sourceWidth);
      result.height = Math.round(sourceHeight);

      // Align the image within its frame
      switch (align) {
        case this.ALIGN_LEFT:
          result.x = 0;
          result.y = (destHeight / 2) - (sourceHeight / 2);
          break;
        case this.ALIGN_RIGHT:
          result.x = destWidth - sourceWidth;
          result.y = (destHeight / 2) - (sourceHeight / 2);
          break;
        case this.ALIGN_TOP:
          result.x = (destWidth / 2) - (sourceWidth / 2);
          result.y = 0;
          break;
        case this.ALIGN_BOTTOM:
          result.x = (destWidth / 2) - (sourceWidth / 2);
          result.y = destHeight - sourceHeight;
          break;
        case this.ALIGN_TOP_LEFT:
          result.x = 0;
          result.y = 0;
          break;
        case this.ALIGN_TOP_RIGHT:
          result.x = destWidth - sourceWidth;
          result.y = 0;
          break;
        case this.ALIGN_BOTTOM_LEFT:
          result.x = 0;
          result.y = destHeight - sourceHeight;
          break;
        case this.ALIGN_BOTTOM_RIGHT:
          result.x = destWidth - sourceWidth;
          result.y = destHeight - sourceHeight;
          break;
        default: // this.ALIGN_CENTER
          if (align !== this.ALIGN_CENTER && this.options.logLevel > 1) {
            console.warn("imageScale - DEBUG WARNING: The align '"+align+"' was not understood.");
          }
          result.x = (destWidth / 2) - (sourceWidth / 2);
          result.y = (destHeight / 2) - (sourceHeight / 2);
      }

      return result;
    },

    /**
      @private

      Determines if the windows size has changed since the last update.

      @returns {Boolean}
    */
    _needUpdate: function(parent) {
      var size = parent.clientHeight + ' ' + parent.clientWidth;

      if (this._lastParentSize !== size) {
        this._lastParentSize = size;
        return true;
      }
      return false;
    },

    /**
      @private

      Schedule a scale update.
    */
    scheduleScale: function() {
      if (this._didScheduleScale) return;

      if (window.requestAnimationFrame) {
        var that = this;
        this._didScheduleScale = true;
        // setTimeout important when resizing down if the scrollbar were visible
        requestAnimationFrame(function() { setTimeout(function() { that.scale(); }, 0); });
      }
      else {
        this.scale();
      }
    }
  }

}));
;
/*
    The MIT License (MIT)

    Copyright (c) 2014 Dirk Groenen

    Permission is hereby granted, free of charge, to any person obtaining a copy of
    this software and associated documentation files (the "Software"), to deal in
    the Software without restriction, including without limitation the rights to
    use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
    the Software, and to permit persons to whom the Software is furnished to do so,
    subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all
    copies or substantial portions of the Software.
*/

(function($){
    $.fn.viewportChecker = function(useroptions){
        // Define options and extend with user
        var options = {
            classToAdd: 'visible',
            classToRemove : 'invisible',
            classToAddForFullView : 'full-visible',
            removeClassAfterAnimation: false,
            offset: 100,
            repeat: false,
            invertBottomOffset: true,
            callbackFunction: function(elem, action){},
            scrollHorizontal: false,
            scrollBox: window
        };
        $.extend(options, useroptions);

        // Cache the given element and height of the browser
        var $elem = this,
            boxSize = {height: $(options.scrollBox).height(), width: $(options.scrollBox).width()};

        /*
         * Main method that checks the elements and adds or removes the class(es)
         */
        this.checkElements = function(){
            var viewportStart, viewportEnd;

            // Set some vars to check with
            if (!options.scrollHorizontal){
                viewportStart = Math.max(
                    $('html').scrollTop(),
                    $('body').scrollTop(),
                    $(window).scrollTop()
                );
                viewportEnd = (viewportStart + boxSize.height);
            }
            else{
                viewportStart = Math.max(
                    $('html').scrollLeft(),
                    $('body').scrollLeft(),
                    $(window).scrollLeft()
                );
                viewportEnd = (viewportStart + boxSize.width);
            }

            // Loop through all given dom elements
            $elem.each(function(){
                var $obj = $(this),
                    objOptions = {},
                    attrOptions = {};

                //  Get any individual attribution data
                if ($obj.data('vp-add-class'))
                    attrOptions.classToAdd = $obj.data('vp-add-class');
                if ($obj.data('vp-remove-class'))
                    attrOptions.classToRemove = $obj.data('vp-remove-class');
                if ($obj.data('vp-add-class-full-view'))
                    attrOptions.classToAddForFullView = $obj.data('vp-add-class-full-view');
                if ($obj.data('vp-keep-add-class'))
                    attrOptions.removeClassAfterAnimation = $obj.data('vp-remove-after-animation');
                if ($obj.data('vp-offset'))
                    attrOptions.offset = $obj.data('vp-offset');
                if ($obj.data('vp-repeat'))
                    attrOptions.repeat = $obj.data('vp-repeat');
                if ($obj.data('vp-scrollHorizontal'))
                    attrOptions.scrollHorizontal = $obj.data('vp-scrollHorizontal');
                if ($obj.data('vp-invertBottomOffset'))
                    attrOptions.scrollHorizontal = $obj.data('vp-invertBottomOffset');

                // Extend objOptions with data attributes and default options
                $.extend(objOptions, options);
                $.extend(objOptions, attrOptions);

                // If class already exists; quit
                if ($obj.data('vp-animated') && !objOptions.repeat){
                    return;
                }

                // Check if the offset is percentage based
                if (String(objOptions.offset).indexOf("%") > 0)
                    objOptions.offset = (parseInt(objOptions.offset) / 100) * boxSize.height;

                // Get the raw start and end positions
                var rawStart = (!objOptions.scrollHorizontal) ? $obj.offset().top : $obj.offset().left,
                    rawEnd = (!objOptions.scrollHorizontal) ? rawStart + $obj.height() : rawStart + $obj.width();

                // Add the defined offset
                var elemStart = Math.round( rawStart ) + objOptions.offset,
                    elemEnd = (!objOptions.scrollHorizontal) ? elemStart + $obj.height() : elemStart + $obj.width();

                if (objOptions.invertBottomOffset)
                    elemEnd -= (objOptions.offset * 2);

                // Add class if in viewport
                if ((elemStart < viewportEnd) && (elemEnd > viewportStart)){

                    // Remove class
                    $obj.removeClass(objOptions.classToRemove);
                    $obj.addClass(objOptions.classToAdd);

                    // Do the callback function. Callback wil send the jQuery object as parameter
                    objOptions.callbackFunction($obj, "add");

                    // Check if full element is in view
                    if (rawEnd <= viewportEnd && rawStart >= viewportStart)
                        $obj.addClass(objOptions.classToAddForFullView);
                    else
                        $obj.removeClass(objOptions.classToAddForFullView);

                    // Set element as already animated
                    $obj.data('vp-animated', true);

                    if (objOptions.removeClassAfterAnimation) {
                        $obj.one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
                            $obj.removeClass(objOptions.classToAdd);
                        });
                    }

                // Remove class if not in viewport and repeat is true
                } else if ($obj.hasClass(objOptions.classToAdd) && (objOptions.repeat)){
                    $obj.removeClass(objOptions.classToAdd + " " + objOptions.classToAddForFullView);

                    // Do the callback function.
                    objOptions.callbackFunction($obj, "remove");

                    // Remove already-animated-flag
                    $obj.data('vp-animated', false);
                }
            });

        };

        /**
         * Binding the correct event listener is still a tricky thing.
         * People have expierenced sloppy scrolling when both scroll and touch
         * events are added, but to make sure devices with both scroll and touch
         * are handles too we always have to add the window.scroll event
         *
         * @see  https://github.com/dirkgroenen/jQuery-viewport-checker/issues/25
         * @see  https://github.com/dirkgroenen/jQuery-viewport-checker/issues/27
         */

        // Select the correct events
        if( 'ontouchstart' in window || 'onmsgesturechange' in window ){
            // Device with touchscreen
            $(document).bind("touchmove MSPointerMove pointermove", this.checkElements);
        }

        // Always load on window load
        $(options.scrollBox).bind("load scroll", this.checkElements);

        // On resize change the height var
        $(window).resize(function(e){
            boxSize = {height: $(options.scrollBox).height(), width: $(options.scrollBox).width()};
            $elem.checkElements();
        });

        // trigger inital check if elements already visible
        this.checkElements();

        // Default jquery plugin behaviour
        return this;
    };
})(jQuery);
;
/*! lazysizes - v5.1.0 */
(function(window, factory) {
	var lazySizes = factory(window, window.document);
	window.lazySizes = lazySizes;
	if(typeof module == 'object' && module.exports){
		module.exports = lazySizes;
	}
}(typeof window != 'undefined' ?
      window : {}, function l(window, document) {
	'use strict';
	/*jshint eqnull:true */

	var lazysizes, lazySizesCfg;

	(function(){
		var prop;

		var lazySizesDefaults = {
			lazyClass: 'lazyload',
			loadedClass: 'lazyloaded',
			loadingClass: 'lazyloading',
			preloadClass: 'lazypreload',
			errorClass: 'lazyerror',
			//strictClass: 'lazystrict',
			autosizesClass: 'lazyautosizes',
			srcAttr: 'data-src',
			srcsetAttr: 'data-srcset',
			sizesAttr: 'data-sizes',
			//preloadAfterLoad: false,
			minSize: 40,
			customMedia: {},
			init: true,
			expFactor: 1.5,
			hFac: 0.8,
			loadMode: 2,
			loadHidden: true,
			ricTimeout: 0,
			throttleDelay: 125,
		};

		lazySizesCfg = window.lazySizesConfig || window.lazysizesConfig || {};

		for(prop in lazySizesDefaults){
			if(!(prop in lazySizesCfg)){
				lazySizesCfg[prop] = lazySizesDefaults[prop];
			}
		}
	})();

	if (!document || !document.getElementsByClassName) {
		return {
			init: function () {},
			cfg: lazySizesCfg,
			noSupport: true,
		};
	}

	var docElem = document.documentElement;

	var Date = window.Date;

	var supportPicture = window.HTMLPictureElement;

	var _addEventListener = 'addEventListener';

	var _getAttribute = 'getAttribute';

	var addEventListener = window[_addEventListener];

	var setTimeout = window.setTimeout;

	var requestAnimationFrame = window.requestAnimationFrame || setTimeout;

	var requestIdleCallback = window.requestIdleCallback;

	var regPicture = /^picture$/i;

	var loadEvents = ['load', 'error', 'lazyincluded', '_lazyloaded'];

	var regClassCache = {};

	var forEach = Array.prototype.forEach;

	var hasClass = function(ele, cls) {
		if(!regClassCache[cls]){
			regClassCache[cls] = new RegExp('(\\s|^)'+cls+'(\\s|$)');
		}
		return regClassCache[cls].test(ele[_getAttribute]('class') || '') && regClassCache[cls];
	};

	var addClass = function(ele, cls) {
		if (!hasClass(ele, cls)){
			ele.setAttribute('class', (ele[_getAttribute]('class') || '').trim() + ' ' + cls);
		}
	};

	var removeClass = function(ele, cls) {
		var reg;
		if ((reg = hasClass(ele,cls))) {
			ele.setAttribute('class', (ele[_getAttribute]('class') || '').replace(reg, ' '));
		}
	};

	var addRemoveLoadEvents = function(dom, fn, add){
		var action = add ? _addEventListener : 'removeEventListener';
		if(add){
			addRemoveLoadEvents(dom, fn);
		}
		loadEvents.forEach(function(evt){
			dom[action](evt, fn);
		});
	};

	var triggerEvent = function(elem, name, detail, noBubbles, noCancelable){
		var event = document.createEvent('Event');

		if(!detail){
			detail = {};
		}

		detail.instance = lazysizes;

		event.initEvent(name, !noBubbles, !noCancelable);

		event.detail = detail;

		elem.dispatchEvent(event);
		return event;
	};

	var updatePolyfill = function (el, full){
		var polyfill;
		if( !supportPicture && ( polyfill = (window.picturefill || lazySizesCfg.pf) ) ){
			if(full && full.src && !el[_getAttribute]('srcset')){
				el.setAttribute('srcset', full.src);
			}
			polyfill({reevaluate: true, elements: [el]});
		} else if(full && full.src){
			el.src = full.src;
		}
	};

	var getCSS = function (elem, style){
		return (getComputedStyle(elem, null) || {})[style];
	};

	var getWidth = function(elem, parent, width){
		width = width || elem.offsetWidth;

		while(width < lazySizesCfg.minSize && parent && !elem._lazysizesWidth){
			width =  parent.offsetWidth;
			parent = parent.parentNode;
		}

		return width;
	};

	var rAF = (function(){
		var running, waiting;
		var firstFns = [];
		var secondFns = [];
		var fns = firstFns;

		var run = function(){
			var runFns = fns;

			fns = firstFns.length ? secondFns : firstFns;

			running = true;
			waiting = false;

			while(runFns.length){
				runFns.shift()();
			}

			running = false;
		};

		var rafBatch = function(fn, queue){
			if(running && !queue){
				fn.apply(this, arguments);
			} else {
				fns.push(fn);

				if(!waiting){
					waiting = true;
					(document.hidden ? setTimeout : requestAnimationFrame)(run);
				}
			}
		};

		rafBatch._lsFlush = run;

		return rafBatch;
	})();

	var rAFIt = function(fn, simple){
		return simple ?
			function() {
				rAF(fn);
			} :
			function(){
				var that = this;
				var args = arguments;
				rAF(function(){
					fn.apply(that, args);
				});
			}
		;
	};

	var throttle = function(fn){
		var running;
		var lastTime = 0;
		var gDelay = lazySizesCfg.throttleDelay;
		var rICTimeout = lazySizesCfg.ricTimeout;
		var run = function(){
			running = false;
			lastTime = Date.now();
			fn();
		};
		var idleCallback = requestIdleCallback && rICTimeout > 49 ?
			function(){
				requestIdleCallback(run, {timeout: rICTimeout});

				if(rICTimeout !== lazySizesCfg.ricTimeout){
					rICTimeout = lazySizesCfg.ricTimeout;
				}
			} :
			rAFIt(function(){
				setTimeout(run);
			}, true)
		;

		return function(isPriority){
			var delay;

			if((isPriority = isPriority === true)){
				rICTimeout = 33;
			}

			if(running){
				return;
			}

			running =  true;

			delay = gDelay - (Date.now() - lastTime);

			if(delay < 0){
				delay = 0;
			}

			if(isPriority || delay < 9){
				idleCallback();
			} else {
				setTimeout(idleCallback, delay);
			}
		};
	};

	//based on http://modernjavascript.blogspot.de/2013/08/building-better-debounce.html
	var debounce = function(func) {
		var timeout, timestamp;
		var wait = 99;
		var run = function(){
			timeout = null;
			func();
		};
		var later = function() {
			var last = Date.now() - timestamp;

			if (last < wait) {
				setTimeout(later, wait - last);
			} else {
				(requestIdleCallback || run)(run);
			}
		};

		return function() {
			timestamp = Date.now();

			if (!timeout) {
				timeout = setTimeout(later, wait);
			}
		};
	};

	var loader = (function(){
		var preloadElems, isCompleted, resetPreloadingTimer, loadMode, started;

		var eLvW, elvH, eLtop, eLleft, eLright, eLbottom, isBodyHidden;

		var regImg = /^img$/i;
		var regIframe = /^iframe$/i;

		var supportScroll = ('onscroll' in window) && !(/(gle|ing)bot/.test(navigator.userAgent));

		var shrinkExpand = 0;
		var currentExpand = 0;

		var isLoading = 0;
		var lowRuns = -1;

		var resetPreloading = function(e){
			isLoading--;
			if(!e || isLoading < 0 || !e.target){
				isLoading = 0;
			}
		};

		var isVisible = function (elem) {
			if (isBodyHidden == null) {
				isBodyHidden = getCSS(document.body, 'visibility') == 'hidden';
			}

			return isBodyHidden || (getCSS(elem.parentNode, 'visibility') != 'hidden' && getCSS(elem, 'visibility') != 'hidden');
		};

		var isNestedVisible = function(elem, elemExpand){
			var outerRect;
			var parent = elem;
			var visible = isVisible(elem);

			eLtop -= elemExpand;
			eLbottom += elemExpand;
			eLleft -= elemExpand;
			eLright += elemExpand;

			while(visible && (parent = parent.offsetParent) && parent != document.body && parent != docElem){
				visible = ((getCSS(parent, 'opacity') || 1) > 0);

				if(visible && getCSS(parent, 'overflow') != 'visible'){
					outerRect = parent.getBoundingClientRect();
					visible = eLright > outerRect.left &&
						eLleft < outerRect.right &&
						eLbottom > outerRect.top - 1 &&
						eLtop < outerRect.bottom + 1
					;
				}
			}

			return visible;
		};

		var checkElements = function() {
			var eLlen, i, rect, autoLoadElem, loadedSomething, elemExpand, elemNegativeExpand, elemExpandVal,
				beforeExpandVal, defaultExpand, preloadExpand, hFac;
			var lazyloadElems = lazysizes.elements;

			if((loadMode = lazySizesCfg.loadMode) && isLoading < 8 && (eLlen = lazyloadElems.length)){

				i = 0;

				lowRuns++;

				for(; i < eLlen; i++){

					if(!lazyloadElems[i] || lazyloadElems[i]._lazyRace){continue;}

					if(!supportScroll || (lazysizes.prematureUnveil && lazysizes.prematureUnveil(lazyloadElems[i]))){unveilElement(lazyloadElems[i]);continue;}

					if(!(elemExpandVal = lazyloadElems[i][_getAttribute]('data-expand')) || !(elemExpand = elemExpandVal * 1)){
						elemExpand = currentExpand;
					}

					if (!defaultExpand) {
						defaultExpand = (!lazySizesCfg.expand || lazySizesCfg.expand < 1) ?
							docElem.clientHeight > 500 && docElem.clientWidth > 500 ? 500 : 370 :
							lazySizesCfg.expand;

						lazysizes._defEx = defaultExpand;

						preloadExpand = defaultExpand * lazySizesCfg.expFactor;
						hFac = lazySizesCfg.hFac;
						isBodyHidden = null;

						if(currentExpand < preloadExpand && isLoading < 1 && lowRuns > 2 && loadMode > 2 && !document.hidden){
							currentExpand = preloadExpand;
							lowRuns = 0;
						} else if(loadMode > 1 && lowRuns > 1 && isLoading < 6){
							currentExpand = defaultExpand;
						} else {
							currentExpand = shrinkExpand;
						}
					}

					if(beforeExpandVal !== elemExpand){
						eLvW = innerWidth + (elemExpand * hFac);
						elvH = innerHeight + elemExpand;
						elemNegativeExpand = elemExpand * -1;
						beforeExpandVal = elemExpand;
					}

					rect = lazyloadElems[i].getBoundingClientRect();

					if ((eLbottom = rect.bottom) >= elemNegativeExpand &&
						(eLtop = rect.top) <= elvH &&
						(eLright = rect.right) >= elemNegativeExpand * hFac &&
						(eLleft = rect.left) <= eLvW &&
						(eLbottom || eLright || eLleft || eLtop) &&
						(lazySizesCfg.loadHidden || isVisible(lazyloadElems[i])) &&
						((isCompleted && isLoading < 3 && !elemExpandVal && (loadMode < 3 || lowRuns < 4)) || isNestedVisible(lazyloadElems[i], elemExpand))){
						unveilElement(lazyloadElems[i]);
						loadedSomething = true;
						if(isLoading > 9){break;}
					} else if(!loadedSomething && isCompleted && !autoLoadElem &&
						isLoading < 4 && lowRuns < 4 && loadMode > 2 &&
						(preloadElems[0] || lazySizesCfg.preloadAfterLoad) &&
						(preloadElems[0] || (!elemExpandVal && ((eLbottom || eLright || eLleft || eLtop) || lazyloadElems[i][_getAttribute](lazySizesCfg.sizesAttr) != 'auto')))){
						autoLoadElem = preloadElems[0] || lazyloadElems[i];
					}
				}

				if(autoLoadElem && !loadedSomething){
					unveilElement(autoLoadElem);
				}
			}
		};

		var throttledCheckElements = throttle(checkElements);

		var switchLoadingClass = function(e){
			var elem = e.target;

			if (elem._lazyCache) {
				delete elem._lazyCache;
				return;
			}

			resetPreloading(e);
			addClass(elem, lazySizesCfg.loadedClass);
			removeClass(elem, lazySizesCfg.loadingClass);
			addRemoveLoadEvents(elem, rafSwitchLoadingClass);
			triggerEvent(elem, 'lazyloaded');
		};
		var rafedSwitchLoadingClass = rAFIt(switchLoadingClass);
		var rafSwitchLoadingClass = function(e){
			rafedSwitchLoadingClass({target: e.target});
		};

		var changeIframeSrc = function(elem, src){
			try {
				elem.contentWindow.location.replace(src);
			} catch(e){
				elem.src = src;
			}
		};

		var handleSources = function(source){
			var customMedia;

			var sourceSrcset = source[_getAttribute](lazySizesCfg.srcsetAttr);

			if( (customMedia = lazySizesCfg.customMedia[source[_getAttribute]('data-media') || source[_getAttribute]('media')]) ){
				source.setAttribute('media', customMedia);
			}

			if(sourceSrcset){
				source.setAttribute('srcset', sourceSrcset);
			}
		};

		var lazyUnveil = rAFIt(function (elem, detail, isAuto, sizes, isImg){
			var src, srcset, parent, isPicture, event, firesLoad;

			if(!(event = triggerEvent(elem, 'lazybeforeunveil', detail)).defaultPrevented){

				if(sizes){
					if(isAuto){
						addClass(elem, lazySizesCfg.autosizesClass);
					} else {
						elem.setAttribute('sizes', sizes);
					}
				}

				srcset = elem[_getAttribute](lazySizesCfg.srcsetAttr);
				src = elem[_getAttribute](lazySizesCfg.srcAttr);

				if(isImg) {
					parent = elem.parentNode;
					isPicture = parent && regPicture.test(parent.nodeName || '');
				}

				firesLoad = detail.firesLoad || (('src' in elem) && (srcset || src || isPicture));

				event = {target: elem};

				addClass(elem, lazySizesCfg.loadingClass);

				if(firesLoad){
					clearTimeout(resetPreloadingTimer);
					resetPreloadingTimer = setTimeout(resetPreloading, 2500);
					addRemoveLoadEvents(elem, rafSwitchLoadingClass, true);
				}

				if(isPicture){
					forEach.call(parent.getElementsByTagName('source'), handleSources);
				}

				if(srcset){
					elem.setAttribute('srcset', srcset);
				} else if(src && !isPicture){
					if(regIframe.test(elem.nodeName)){
						changeIframeSrc(elem, src);
					} else {
						elem.src = src;
					}
				}

				if(isImg && (srcset || isPicture)){
					updatePolyfill(elem, {src: src});
				}
			}

			if(elem._lazyRace){
				delete elem._lazyRace;
			}
			removeClass(elem, lazySizesCfg.lazyClass);

			rAF(function(){
				// Part of this can be removed as soon as this fix is older: https://bugs.chromium.org/p/chromium/issues/detail?id=7731 (2015)
				var isLoaded = elem.complete && elem.naturalWidth > 1;

				if( !firesLoad || isLoaded){
					if (isLoaded) {
						addClass(elem, 'ls-is-cached');
					}
					switchLoadingClass(event);
					elem._lazyCache = true;
					setTimeout(function(){
						if ('_lazyCache' in elem) {
							delete elem._lazyCache;
						}
					}, 9);
				}
				if (elem.loading == 'lazy') {
					isLoading--;
				}
			}, true);
		});

		var unveilElement = function (elem){
			if (elem._lazyRace) {return;}
			var detail;

			var isImg = regImg.test(elem.nodeName);

			//allow using sizes="auto", but don't use. it's invalid. Use data-sizes="auto" or a valid value for sizes instead (i.e.: sizes="80vw")
			var sizes = isImg && (elem[_getAttribute](lazySizesCfg.sizesAttr) || elem[_getAttribute]('sizes'));
			var isAuto = sizes == 'auto';

			if( (isAuto || !isCompleted) && isImg && (elem[_getAttribute]('src') || elem.srcset) && !elem.complete && !hasClass(elem, lazySizesCfg.errorClass) && hasClass(elem, lazySizesCfg.lazyClass)){return;}

			detail = triggerEvent(elem, 'lazyunveilread').detail;

			if(isAuto){
				 autoSizer.updateElem(elem, true, elem.offsetWidth);
			}

			elem._lazyRace = true;
			isLoading++;

			lazyUnveil(elem, detail, isAuto, sizes, isImg);
		};

		var afterScroll = debounce(function(){
			lazySizesCfg.loadMode = 3;
			throttledCheckElements();
		});

		var altLoadmodeScrollListner = function(){
			if(lazySizesCfg.loadMode == 3){
				lazySizesCfg.loadMode = 2;
			}
			afterScroll();
		};

		var onload = function(){
			if(isCompleted){return;}
			if(Date.now() - started < 999){
				setTimeout(onload, 999);
				return;
			}


			isCompleted = true;

			lazySizesCfg.loadMode = 3;

			throttledCheckElements();

			addEventListener('scroll', altLoadmodeScrollListner, true);
		};

		return {
			_: function(){
				started = Date.now();

				lazysizes.elements = document.getElementsByClassName(lazySizesCfg.lazyClass);
				preloadElems = document.getElementsByClassName(lazySizesCfg.lazyClass + ' ' + lazySizesCfg.preloadClass);

				addEventListener('scroll', throttledCheckElements, true);

				addEventListener('resize', throttledCheckElements, true);

				if(window.MutationObserver){
					new MutationObserver( throttledCheckElements ).observe( docElem, {childList: true, subtree: true, attributes: true} );
				} else {
					docElem[_addEventListener]('DOMNodeInserted', throttledCheckElements, true);
					docElem[_addEventListener]('DOMAttrModified', throttledCheckElements, true);
					setInterval(throttledCheckElements, 999);
				}

				addEventListener('hashchange', throttledCheckElements, true);

				//, 'fullscreenchange'
				['focus', 'mouseover', 'click', 'load', 'transitionend', 'animationend'].forEach(function(name){
					document[_addEventListener](name, throttledCheckElements, true);
				});

				if((/d$|^c/.test(document.readyState))){
					onload();
				} else {
					addEventListener('load', onload);
					document[_addEventListener]('DOMContentLoaded', throttledCheckElements);
					setTimeout(onload, 20000);
				}

				if(lazysizes.elements.length){
					checkElements();
					rAF._lsFlush();
				} else {
					throttledCheckElements();
				}
			},
			checkElems: throttledCheckElements,
			unveil: unveilElement,
			_aLSL: altLoadmodeScrollListner,
		};
	})();


	var autoSizer = (function(){
		var autosizesElems;

		var sizeElement = rAFIt(function(elem, parent, event, width){
			var sources, i, len;
			elem._lazysizesWidth = width;
			width += 'px';

			elem.setAttribute('sizes', width);

			if(regPicture.test(parent.nodeName || '')){
				sources = parent.getElementsByTagName('source');
				for(i = 0, len = sources.length; i < len; i++){
					sources[i].setAttribute('sizes', width);
				}
			}

			if(!event.detail.dataAttr){
				updatePolyfill(elem, event.detail);
			}
		});
		var getSizeElement = function (elem, dataAttr, width){
			var event;
			var parent = elem.parentNode;

			if(parent){
				width = getWidth(elem, parent, width);
				event = triggerEvent(elem, 'lazybeforesizes', {width: width, dataAttr: !!dataAttr});

				if(!event.defaultPrevented){
					width = event.detail.width;

					if(width && width !== elem._lazysizesWidth){
						sizeElement(elem, parent, event, width);
					}
				}
			}
		};

		var updateElementsSizes = function(){
			var i;
			var len = autosizesElems.length;
			if(len){
				i = 0;

				for(; i < len; i++){
					getSizeElement(autosizesElems[i]);
				}
			}
		};

		var debouncedUpdateElementsSizes = debounce(updateElementsSizes);

		return {
			_: function(){
				autosizesElems = document.getElementsByClassName(lazySizesCfg.autosizesClass);
				addEventListener('resize', debouncedUpdateElementsSizes);
			},
			checkElems: debouncedUpdateElementsSizes,
			updateElem: getSizeElement
		};
	})();

	var init = function(){
		if(!init.i && document.getElementsByClassName){
			init.i = true;
			autoSizer._();
			loader._();
		}
	};

	setTimeout(function(){
		if(lazySizesCfg.init){
			init();
		}
	});

	lazysizes = {
		cfg: lazySizesCfg,
		autoSizer: autoSizer,
		loader: loader,
		init: init,
		uP: updatePolyfill,
		aC: addClass,
		rC: removeClass,
		hC: hasClass,
		fire: triggerEvent,
		gW: getWidth,
		rAF: rAF,
	};

	return lazysizes;
}
));;
/*! npm.im/object-fit-images 3.2.4 */
var objectFitImages = (function () {
'use strict';

var OFI = 'bfred-it:object-fit-images';
var propRegex = /(object-fit|object-position)\s*:\s*([-.\w\s%]+)/g;
var testImg = typeof Image === 'undefined' ? {style: {'object-position': 1}} : new Image();
var supportsObjectFit = 'object-fit' in testImg.style;
var supportsObjectPosition = 'object-position' in testImg.style;
var supportsOFI = 'background-size' in testImg.style;
var supportsCurrentSrc = typeof testImg.currentSrc === 'string';
var nativeGetAttribute = testImg.getAttribute;
var nativeSetAttribute = testImg.setAttribute;
var autoModeEnabled = false;

function createPlaceholder(w, h) {
	return ("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='" + w + "' height='" + h + "'%3E%3C/svg%3E");
}

function polyfillCurrentSrc(el) {
	if (el.srcset && !supportsCurrentSrc && window.picturefill) {
		var pf = window.picturefill._;
		// parse srcset with picturefill where currentSrc isn't available
		if (!el[pf.ns] || !el[pf.ns].evaled) {
			// force synchronous srcset parsing
			pf.fillImg(el, {reselect: true});
		}

		if (!el[pf.ns].curSrc) {
			// force picturefill to parse srcset
			el[pf.ns].supported = false;
			pf.fillImg(el, {reselect: true});
		}

		// retrieve parsed currentSrc, if any
		el.currentSrc = el[pf.ns].curSrc || el.src;
	}
}

function getStyle(el) {
	var style = getComputedStyle(el).fontFamily;
	var parsed;
	var props = {};
	while ((parsed = propRegex.exec(style)) !== null) {
		props[parsed[1]] = parsed[2];
	}
	return props;
}

function setPlaceholder(img, width, height) {
	// Default: fill width, no height
	var placeholder = createPlaceholder(width || 1, height || 0);

	// Only set placeholder if it's different
	if (nativeGetAttribute.call(img, 'src') !== placeholder) {
		nativeSetAttribute.call(img, 'src', placeholder);
	}
}

function onImageReady(img, callback) {
	// naturalWidth is only available when the image headers are loaded,
	// this loop will poll it every 100ms.
	if (img.naturalWidth) {
		callback(img);
	} else {
		setTimeout(onImageReady, 100, img, callback);
	}
}

function fixOne(el) {
	var style = getStyle(el);
	var ofi = el[OFI];
	style['object-fit'] = style['object-fit'] || 'fill'; // default value

	// Avoid running where unnecessary, unless OFI had already done its deed
	if (!ofi.img) {
		// fill is the default behavior so no action is necessary
		if (style['object-fit'] === 'fill') {
			return;
		}

		// Where object-fit is supported and object-position isn't (Safari < 10)
		if (
			!ofi.skipTest && // unless user wants to apply regardless of browser support
			supportsObjectFit && // if browser already supports object-fit
			!style['object-position'] // unless object-position is used
		) {
			return;
		}
	}

	// keep a clone in memory while resetting the original to a blank
	if (!ofi.img) {
		ofi.img = new Image(el.width, el.height);
		ofi.img.srcset = nativeGetAttribute.call(el, "data-ofi-srcset") || el.srcset;
		ofi.img.src = nativeGetAttribute.call(el, "data-ofi-src") || el.src;

		// preserve for any future cloneNode calls
		// https://github.com/bfred-it/object-fit-images/issues/53
		nativeSetAttribute.call(el, "data-ofi-src", el.src);
		if (el.srcset) {
			nativeSetAttribute.call(el, "data-ofi-srcset", el.srcset);
		}

		setPlaceholder(el, el.naturalWidth || el.width, el.naturalHeight || el.height);

		// remove srcset because it overrides src
		if (el.srcset) {
			el.srcset = '';
		}
		try {
			keepSrcUsable(el);
		} catch (err) {
			if (window.console) {
				console.warn('https://bit.ly/ofi-old-browser');
			}
		}
	}

	polyfillCurrentSrc(ofi.img);

	el.style.backgroundImage = "url(\"" + ((ofi.img.currentSrc || ofi.img.src).replace(/"/g, '\\"')) + "\")";
	el.style.backgroundPosition = style['object-position'] || 'center';
	el.style.backgroundRepeat = 'no-repeat';
	el.style.backgroundOrigin = 'content-box';

	if (/scale-down/.test(style['object-fit'])) {
		onImageReady(ofi.img, function () {
			if (ofi.img.naturalWidth > el.width || ofi.img.naturalHeight > el.height) {
				el.style.backgroundSize = 'contain';
			} else {
				el.style.backgroundSize = 'auto';
			}
		});
	} else {
		el.style.backgroundSize = style['object-fit'].replace('none', 'auto').replace('fill', '100% 100%');
	}

	onImageReady(ofi.img, function (img) {
		setPlaceholder(el, img.naturalWidth, img.naturalHeight);
	});
}

function keepSrcUsable(el) {
	var descriptors = {
		get: function get(prop) {
			return el[OFI].img[prop ? prop : 'src'];
		},
		set: function set(value, prop) {
			el[OFI].img[prop ? prop : 'src'] = value;
			nativeSetAttribute.call(el, ("data-ofi-" + prop), value); // preserve for any future cloneNode
			fixOne(el);
			return value;
		}
	};
	Object.defineProperty(el, 'src', descriptors);
	Object.defineProperty(el, 'currentSrc', {
		get: function () { return descriptors.get('currentSrc'); }
	});
	Object.defineProperty(el, 'srcset', {
		get: function () { return descriptors.get('srcset'); },
		set: function (ss) { return descriptors.set(ss, 'srcset'); }
	});
}

function hijackAttributes() {
	function getOfiImageMaybe(el, name) {
		return el[OFI] && el[OFI].img && (name === 'src' || name === 'srcset') ? el[OFI].img : el;
	}
	if (!supportsObjectPosition) {
		HTMLImageElement.prototype.getAttribute = function (name) {
			return nativeGetAttribute.call(getOfiImageMaybe(this, name), name);
		};

		HTMLImageElement.prototype.setAttribute = function (name, value) {
			return nativeSetAttribute.call(getOfiImageMaybe(this, name), name, String(value));
		};
	}
}

function fix(imgs, opts) {
	var startAutoMode = !autoModeEnabled && !imgs;
	opts = opts || {};
	imgs = imgs || 'img';

	if ((supportsObjectPosition && !opts.skipTest) || !supportsOFI) {
		return false;
	}

	// use imgs as a selector or just select all images
	if (imgs === 'img') {
		imgs = document.getElementsByTagName('img');
	} else if (typeof imgs === 'string') {
		imgs = document.querySelectorAll(imgs);
	} else if (!('length' in imgs)) {
		imgs = [imgs];
	}

	// apply fix to all
	for (var i = 0; i < imgs.length; i++) {
		imgs[i][OFI] = imgs[i][OFI] || {
			skipTest: opts.skipTest
		};
		fixOne(imgs[i]);
	}

	if (startAutoMode) {
		document.body.addEventListener('load', function (e) {
			if (e.target.tagName === 'IMG') {
				fix(e.target, {
					skipTest: opts.skipTest
				});
			}
		}, true);
		autoModeEnabled = true;
		imgs = 'img'; // reset to a generic selector for watchMQ
	}

	// if requested, watch media queries for object-fit change
	if (opts.watchMQ) {
		window.addEventListener('resize', fix.bind(null, imgs, {
			skipTest: opts.skipTest
		}));
	}
}

fix.supportsObjectFit = supportsObjectFit;
fix.supportsObjectPosition = supportsObjectPosition;

hijackAttributes();

return fix;

}());;
/*!
 * Select2 4.0.12
 * https://select2.github.io
 *
 * Released under the MIT license
 * https://github.com/select2/select2/blob/master/LICENSE.md
 */
;(function (factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['jquery'], factory);
  } else if (typeof module === 'object' && module.exports) {
    // Node/CommonJS
    module.exports = function (root, jQuery) {
      if (jQuery === undefined) {
        // require('jQuery') returns a factory that requires window to
        // build a jQuery instance, we normalize how we use modules
        // that require this pattern but the window provided is a noop
        // if it's defined (how jquery works)
        if (typeof window !== 'undefined') {
          jQuery = require('jquery');
        }
        else {
          jQuery = require('jquery')(root);
        }
      }
      factory(jQuery);
      return jQuery;
    };
  } else {
    // Browser globals
    factory(jQuery);
  }
} (function (jQuery) {
  // This is needed so we can catch the AMD loader configuration and use it
  // The inner file should be wrapped (by `banner.start.js`) in a function that
  // returns the AMD loader references.
  var S2 =(function () {
  // Restore the Select2 AMD loader so it can be used
  // Needed mostly in the language files, where the loader is not inserted
  if (jQuery && jQuery.fn && jQuery.fn.select2 && jQuery.fn.select2.amd) {
    var S2 = jQuery.fn.select2.amd;
  }
var S2;(function () { if (!S2 || !S2.requirejs) {
if (!S2) { S2 = {}; } else { require = S2; }
/**
 * @license almond 0.3.3 Copyright jQuery Foundation and other contributors.
 * Released under MIT license, http://github.com/requirejs/almond/LICENSE
 */
//Going sloppy to avoid 'use strict' string cost, but strict practices should
//be followed.
/*global setTimeout: false */

var requirejs, require, define;
(function (undef) {
    var main, req, makeMap, handlers,
        defined = {},
        waiting = {},
        config = {},
        defining = {},
        hasOwn = Object.prototype.hasOwnProperty,
        aps = [].slice,
        jsSuffixRegExp = /\.js$/;

    function hasProp(obj, prop) {
        return hasOwn.call(obj, prop);
    }

    /**
     * Given a relative module name, like ./something, normalize it to
     * a real name that can be mapped to a path.
     * @param {String} name the relative name
     * @param {String} baseName a real name that the name arg is relative
     * to.
     * @returns {String} normalized name
     */
    function normalize(name, baseName) {
        var nameParts, nameSegment, mapValue, foundMap, lastIndex,
            foundI, foundStarMap, starI, i, j, part, normalizedBaseParts,
            baseParts = baseName && baseName.split("/"),
            map = config.map,
            starMap = (map && map['*']) || {};

        //Adjust any relative paths.
        if (name) {
            name = name.split('/');
            lastIndex = name.length - 1;

            // If wanting node ID compatibility, strip .js from end
            // of IDs. Have to do this here, and not in nameToUrl
            // because node allows either .js or non .js to map
            // to same file.
            if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) {
                name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, '');
            }

            // Starts with a '.' so need the baseName
            if (name[0].charAt(0) === '.' && baseParts) {
                //Convert baseName to array, and lop off the last part,
                //so that . matches that 'directory' and not name of the baseName's
                //module. For instance, baseName of 'one/two/three', maps to
                //'one/two/three.js', but we want the directory, 'one/two' for
                //this normalization.
                normalizedBaseParts = baseParts.slice(0, baseParts.length - 1);
                name = normalizedBaseParts.concat(name);
            }

            //start trimDots
            for (i = 0; i < name.length; i++) {
                part = name[i];
                if (part === '.') {
                    name.splice(i, 1);
                    i -= 1;
                } else if (part === '..') {
                    // If at the start, or previous value is still ..,
                    // keep them so that when converted to a path it may
                    // still work when converted to a path, even though
                    // as an ID it is less than ideal. In larger point
                    // releases, may be better to just kick out an error.
                    if (i === 0 || (i === 1 && name[2] === '..') || name[i - 1] === '..') {
                        continue;
                    } else if (i > 0) {
                        name.splice(i - 1, 2);
                        i -= 2;
                    }
                }
            }
            //end trimDots

            name = name.join('/');
        }

        //Apply map config if available.
        if ((baseParts || starMap) && map) {
            nameParts = name.split('/');

            for (i = nameParts.length; i > 0; i -= 1) {
                nameSegment = nameParts.slice(0, i).join("/");

                if (baseParts) {
                    //Find the longest baseName segment match in the config.
                    //So, do joins on the biggest to smallest lengths of baseParts.
                    for (j = baseParts.length; j > 0; j -= 1) {
                        mapValue = map[baseParts.slice(0, j).join('/')];

                        //baseName segment has  config, find if it has one for
                        //this name.
                        if (mapValue) {
                            mapValue = mapValue[nameSegment];
                            if (mapValue) {
                                //Match, update name to the new value.
                                foundMap = mapValue;
                                foundI = i;
                                break;
                            }
                        }
                    }
                }

                if (foundMap) {
                    break;
                }

                //Check for a star map match, but just hold on to it,
                //if there is a shorter segment match later in a matching
                //config, then favor over this star map.
                if (!foundStarMap && starMap && starMap[nameSegment]) {
                    foundStarMap = starMap[nameSegment];
                    starI = i;
                }
            }

            if (!foundMap && foundStarMap) {
                foundMap = foundStarMap;
                foundI = starI;
            }

            if (foundMap) {
                nameParts.splice(0, foundI, foundMap);
                name = nameParts.join('/');
            }
        }

        return name;
    }

    function makeRequire(relName, forceSync) {
        return function () {
            //A version of a require function that passes a moduleName
            //value for items that may need to
            //look up paths relative to the moduleName
            var args = aps.call(arguments, 0);

            //If first arg is not require('string'), and there is only
            //one arg, it is the array form without a callback. Insert
            //a null so that the following concat is correct.
            if (typeof args[0] !== 'string' && args.length === 1) {
                args.push(null);
            }
            return req.apply(undef, args.concat([relName, forceSync]));
        };
    }

    function makeNormalize(relName) {
        return function (name) {
            return normalize(name, relName);
        };
    }

    function makeLoad(depName) {
        return function (value) {
            defined[depName] = value;
        };
    }

    function callDep(name) {
        if (hasProp(waiting, name)) {
            var args = waiting[name];
            delete waiting[name];
            defining[name] = true;
            main.apply(undef, args);
        }

        if (!hasProp(defined, name) && !hasProp(defining, name)) {
            throw new Error('No ' + name);
        }
        return defined[name];
    }

    //Turns a plugin!resource to [plugin, resource]
    //with the plugin being undefined if the name
    //did not have a plugin prefix.
    function splitPrefix(name) {
        var prefix,
            index = name ? name.indexOf('!') : -1;
        if (index > -1) {
            prefix = name.substring(0, index);
            name = name.substring(index + 1, name.length);
        }
        return [prefix, name];
    }

    //Creates a parts array for a relName where first part is plugin ID,
    //second part is resource ID. Assumes relName has already been normalized.
    function makeRelParts(relName) {
        return relName ? splitPrefix(relName) : [];
    }

    /**
     * Makes a name map, normalizing the name, and using a plugin
     * for normalization if necessary. Grabs a ref to plugin
     * too, as an optimization.
     */
    makeMap = function (name, relParts) {
        var plugin,
            parts = splitPrefix(name),
            prefix = parts[0],
            relResourceName = relParts[1];

        name = parts[1];

        if (prefix) {
            prefix = normalize(prefix, relResourceName);
            plugin = callDep(prefix);
        }

        //Normalize according
        if (prefix) {
            if (plugin && plugin.normalize) {
                name = plugin.normalize(name, makeNormalize(relResourceName));
            } else {
                name = normalize(name, relResourceName);
            }
        } else {
            name = normalize(name, relResourceName);
            parts = splitPrefix(name);
            prefix = parts[0];
            name = parts[1];
            if (prefix) {
                plugin = callDep(prefix);
            }
        }

        //Using ridiculous property names for space reasons
        return {
            f: prefix ? prefix + '!' + name : name, //fullName
            n: name,
            pr: prefix,
            p: plugin
        };
    };

    function makeConfig(name) {
        return function () {
            return (config && config.config && config.config[name]) || {};
        };
    }

    handlers = {
        require: function (name) {
            return makeRequire(name);
        },
        exports: function (name) {
            var e = defined[name];
            if (typeof e !== 'undefined') {
                return e;
            } else {
                return (defined[name] = {});
            }
        },
        module: function (name) {
            return {
                id: name,
                uri: '',
                exports: defined[name],
                config: makeConfig(name)
            };
        }
    };

    main = function (name, deps, callback, relName) {
        var cjsModule, depName, ret, map, i, relParts,
            args = [],
            callbackType = typeof callback,
            usingExports;

        //Use name if no relName
        relName = relName || name;
        relParts = makeRelParts(relName);

        //Call the callback to define the module, if necessary.
        if (callbackType === 'undefined' || callbackType === 'function') {
            //Pull out the defined dependencies and pass the ordered
            //values to the callback.
            //Default to [require, exports, module] if no deps
            deps = !deps.length && callback.length ? ['require', 'exports', 'module'] : deps;
            for (i = 0; i < deps.length; i += 1) {
                map = makeMap(deps[i], relParts);
                depName = map.f;

                //Fast path CommonJS standard dependencies.
                if (depName === "require") {
                    args[i] = handlers.require(name);
                } else if (depName === "exports") {
                    //CommonJS module spec 1.1
                    args[i] = handlers.exports(name);
                    usingExports = true;
                } else if (depName === "module") {
                    //CommonJS module spec 1.1
                    cjsModule = args[i] = handlers.module(name);
                } else if (hasProp(defined, depName) ||
                           hasProp(waiting, depName) ||
                           hasProp(defining, depName)) {
                    args[i] = callDep(depName);
                } else if (map.p) {
                    map.p.load(map.n, makeRequire(relName, true), makeLoad(depName), {});
                    args[i] = defined[depName];
                } else {
                    throw new Error(name + ' missing ' + depName);
                }
            }

            ret = callback ? callback.apply(defined[name], args) : undefined;

            if (name) {
                //If setting exports via "module" is in play,
                //favor that over return value and exports. After that,
                //favor a non-undefined return value over exports use.
                if (cjsModule && cjsModule.exports !== undef &&
                        cjsModule.exports !== defined[name]) {
                    defined[name] = cjsModule.exports;
                } else if (ret !== undef || !usingExports) {
                    //Use the return value from the function.
                    defined[name] = ret;
                }
            }
        } else if (name) {
            //May just be an object definition for the module. Only
            //worry about defining if have a module name.
            defined[name] = callback;
        }
    };

    requirejs = require = req = function (deps, callback, relName, forceSync, alt) {
        if (typeof deps === "string") {
            if (handlers[deps]) {
                //callback in this case is really relName
                return handlers[deps](callback);
            }
            //Just return the module wanted. In this scenario, the
            //deps arg is the module name, and second arg (if passed)
            //is just the relName.
            //Normalize module name, if it contains . or ..
            return callDep(makeMap(deps, makeRelParts(callback)).f);
        } else if (!deps.splice) {
            //deps is a config object, not an array.
            config = deps;
            if (config.deps) {
                req(config.deps, config.callback);
            }
            if (!callback) {
                return;
            }

            if (callback.splice) {
                //callback is an array, which means it is a dependency list.
                //Adjust args if there are dependencies
                deps = callback;
                callback = relName;
                relName = null;
            } else {
                deps = undef;
            }
        }

        //Support require(['a'])
        callback = callback || function () {};

        //If relName is a function, it is an errback handler,
        //so remove it.
        if (typeof relName === 'function') {
            relName = forceSync;
            forceSync = alt;
        }

        //Simulate async callback;
        if (forceSync) {
            main(undef, deps, callback, relName);
        } else {
            //Using a non-zero value because of concern for what old browsers
            //do, and latest browsers "upgrade" to 4 if lower value is used:
            //http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#dom-windowtimers-settimeout:
            //If want a value immediately, use require('id') instead -- something
            //that works in almond on the global level, but not guaranteed and
            //unlikely to work in other AMD implementations.
            setTimeout(function () {
                main(undef, deps, callback, relName);
            }, 4);
        }

        return req;
    };

    /**
     * Just drops the config on the floor, but returns req in case
     * the config return value is used.
     */
    req.config = function (cfg) {
        return req(cfg);
    };

    /**
     * Expose module registry for debugging and tooling
     */
    requirejs._defined = defined;

    define = function (name, deps, callback) {
        if (typeof name !== 'string') {
            throw new Error('See almond README: incorrect module build, no module name');
        }

        //This module may not have dependencies
        if (!deps.splice) {
            //deps is not an array, so probably means
            //an object literal or factory function for
            //the value. Adjust args.
            callback = deps;
            deps = [];
        }

        if (!hasProp(defined, name) && !hasProp(waiting, name)) {
            waiting[name] = [name, deps, callback];
        }
    };

    define.amd = {
        jQuery: true
    };
}());

S2.requirejs = requirejs;S2.require = require;S2.define = define;
}
}());
S2.define("almond", function(){});

/* global jQuery:false, $:false */
S2.define('jquery',[],function () {
  var _$ = jQuery || $;

  if (_$ == null && console && console.error) {
    console.error(
      'Select2: An instance of jQuery or a jQuery-compatible library was not ' +
      'found. Make sure that you are including jQuery before Select2 on your ' +
      'web page.'
    );
  }

  return _$;
});

S2.define('select2/utils',[
  'jquery'
], function ($) {
  var Utils = {};

  Utils.Extend = function (ChildClass, SuperClass) {
    var __hasProp = {}.hasOwnProperty;

    function BaseConstructor () {
      this.constructor = ChildClass;
    }

    for (var key in SuperClass) {
      if (__hasProp.call(SuperClass, key)) {
        ChildClass[key] = SuperClass[key];
      }
    }

    BaseConstructor.prototype = SuperClass.prototype;
    ChildClass.prototype = new BaseConstructor();
    ChildClass.__super__ = SuperClass.prototype;

    return ChildClass;
  };

  function getMethods (theClass) {
    var proto = theClass.prototype;

    var methods = [];

    for (var methodName in proto) {
      var m = proto[methodName];

      if (typeof m !== 'function') {
        continue;
      }

      if (methodName === 'constructor') {
        continue;
      }

      methods.push(methodName);
    }

    return methods;
  }

  Utils.Decorate = function (SuperClass, DecoratorClass) {
    var decoratedMethods = getMethods(DecoratorClass);
    var superMethods = getMethods(SuperClass);

    function DecoratedClass () {
      var unshift = Array.prototype.unshift;

      var argCount = DecoratorClass.prototype.constructor.length;

      var calledConstructor = SuperClass.prototype.constructor;

      if (argCount > 0) {
        unshift.call(arguments, SuperClass.prototype.constructor);

        calledConstructor = DecoratorClass.prototype.constructor;
      }

      calledConstructor.apply(this, arguments);
    }

    DecoratorClass.displayName = SuperClass.displayName;

    function ctr () {
      this.constructor = DecoratedClass;
    }

    DecoratedClass.prototype = new ctr();

    for (var m = 0; m < superMethods.length; m++) {
      var superMethod = superMethods[m];

      DecoratedClass.prototype[superMethod] =
        SuperClass.prototype[superMethod];
    }

    var calledMethod = function (methodName) {
      // Stub out the original method if it's not decorating an actual method
      var originalMethod = function () {};

      if (methodName in DecoratedClass.prototype) {
        originalMethod = DecoratedClass.prototype[methodName];
      }

      var decoratedMethod = DecoratorClass.prototype[methodName];

      return function () {
        var unshift = Array.prototype.unshift;

        unshift.call(arguments, originalMethod);

        return decoratedMethod.apply(this, arguments);
      };
    };

    for (var d = 0; d < decoratedMethods.length; d++) {
      var decoratedMethod = decoratedMethods[d];

      DecoratedClass.prototype[decoratedMethod] = calledMethod(decoratedMethod);
    }

    return DecoratedClass;
  };

  var Observable = function () {
    this.listeners = {};
  };

  Observable.prototype.on = function (event, callback) {
    this.listeners = this.listeners || {};

    if (event in this.listeners) {
      this.listeners[event].push(callback);
    } else {
      this.listeners[event] = [callback];
    }
  };

  Observable.prototype.trigger = function (event) {
    var slice = Array.prototype.slice;
    var params = slice.call(arguments, 1);

    this.listeners = this.listeners || {};

    // Params should always come in as an array
    if (params == null) {
      params = [];
    }

    // If there are no arguments to the event, use a temporary object
    if (params.length === 0) {
      params.push({});
    }

    // Set the `_type` of the first object to the event
    params[0]._type = event;

    if (event in this.listeners) {
      this.invoke(this.listeners[event], slice.call(arguments, 1));
    }

    if ('*' in this.listeners) {
      this.invoke(this.listeners['*'], arguments);
    }
  };

  Observable.prototype.invoke = function (listeners, params) {
    for (var i = 0, len = listeners.length; i < len; i++) {
      listeners[i].apply(this, params);
    }
  };

  Utils.Observable = Observable;

  Utils.generateChars = function (length) {
    var chars = '';

    for (var i = 0; i < length; i++) {
      var randomChar = Math.floor(Math.random() * 36);
      chars += randomChar.toString(36);
    }

    return chars;
  };

  Utils.bind = function (func, context) {
    return function () {
      func.apply(context, arguments);
    };
  };

  Utils._convertData = function (data) {
    for (var originalKey in data) {
      var keys = originalKey.split('-');

      var dataLevel = data;

      if (keys.length === 1) {
        continue;
      }

      for (var k = 0; k < keys.length; k++) {
        var key = keys[k];

        // Lowercase the first letter
        // By default, dash-separated becomes camelCase
        key = key.substring(0, 1).toLowerCase() + key.substring(1);

        if (!(key in dataLevel)) {
          dataLevel[key] = {};
        }

        if (k == keys.length - 1) {
          dataLevel[key] = data[originalKey];
        }

        dataLevel = dataLevel[key];
      }

      delete data[originalKey];
    }

    return data;
  };

  Utils.hasScroll = function (index, el) {
    // Adapted from the function created by @ShadowScripter
    // and adapted by @BillBarry on the Stack Exchange Code Review website.
    // The original code can be found at
    // http://codereview.stackexchange.com/q/13338
    // and was designed to be used with the Sizzle selector engine.

    var $el = $(el);
    var overflowX = el.style.overflowX;
    var overflowY = el.style.overflowY;

    //Check both x and y declarations
    if (overflowX === overflowY &&
        (overflowY === 'hidden' || overflowY === 'visible')) {
      return false;
    }

    if (overflowX === 'scroll' || overflowY === 'scroll') {
      return true;
    }

    return ($el.innerHeight() < el.scrollHeight ||
      $el.innerWidth() < el.scrollWidth);
  };

  Utils.escapeMarkup = function (markup) {
    var replaceMap = {
      '\\': '&#92;',
      '&': '&amp;',
      '<': '&lt;',
      '>': '&gt;',
      '"': '&quot;',
      '\'': '&#39;',
      '/': '&#47;'
    };

    // Do not try to escape the markup if it's not a string
    if (typeof markup !== 'string') {
      return markup;
    }

    return String(markup).replace(/[&<>"'\/\\]/g, function (match) {
      return replaceMap[match];
    });
  };

  // Append an array of jQuery nodes to a given element.
  Utils.appendMany = function ($element, $nodes) {
    // jQuery 1.7.x does not support $.fn.append() with an array
    // Fall back to a jQuery object collection using $.fn.add()
    if ($.fn.jquery.substr(0, 3) === '1.7') {
      var $jqNodes = $();

      $.map($nodes, function (node) {
        $jqNodes = $jqNodes.add(node);
      });

      $nodes = $jqNodes;
    }

    $element.append($nodes);
  };

  // Cache objects in Utils.__cache instead of $.data (see #4346)
  Utils.__cache = {};

  var id = 0;
  Utils.GetUniqueElementId = function (element) {
    // Get a unique element Id. If element has no id,
    // creates a new unique number, stores it in the id
    // attribute and returns the new id.
    // If an id already exists, it simply returns it.

    var select2Id = element.getAttribute('data-select2-id');
    if (select2Id == null) {
      // If element has id, use it.
      if (element.id) {
        select2Id = element.id;
        element.setAttribute('data-select2-id', select2Id);
      } else {
        element.setAttribute('data-select2-id', ++id);
        select2Id = id.toString();
      }
    }
    return select2Id;
  };

  Utils.StoreData = function (element, name, value) {
    // Stores an item in the cache for a specified element.
    // name is the cache key.
    var id = Utils.GetUniqueElementId(element);
    if (!Utils.__cache[id]) {
      Utils.__cache[id] = {};
    }

    Utils.__cache[id][name] = value;
  };

  Utils.GetData = function (element, name) {
    // Retrieves a value from the cache by its key (name)
    // name is optional. If no name specified, return
    // all cache items for the specified element.
    // and for a specified element.
    var id = Utils.GetUniqueElementId(element);
    if (name) {
      if (Utils.__cache[id]) {
        if (Utils.__cache[id][name] != null) {
          return Utils.__cache[id][name];
        }
        return $(element).data(name); // Fallback to HTML5 data attribs.
      }
      return $(element).data(name); // Fallback to HTML5 data attribs.
    } else {
      return Utils.__cache[id];
    }
  };

  Utils.RemoveData = function (element) {
    // Removes all cached items for a specified element.
    var id = Utils.GetUniqueElementId(element);
    if (Utils.__cache[id] != null) {
      delete Utils.__cache[id];
    }

    element.removeAttribute('data-select2-id');
  };

  return Utils;
});

S2.define('select2/results',[
  'jquery',
  './utils'
], function ($, Utils) {
  function Results ($element, options, dataAdapter) {
    this.$element = $element;
    this.data = dataAdapter;
    this.options = options;

    Results.__super__.constructor.call(this);
  }

  Utils.Extend(Results, Utils.Observable);

  Results.prototype.render = function () {
    var $results = $(
      '<ul class="select2-results__options" role="listbox"></ul>'
    );

    if (this.options.get('multiple')) {
      $results.attr('aria-multiselectable', 'true');
    }

    this.$results = $results;

    return $results;
  };

  Results.prototype.clear = function () {
    this.$results.empty();
  };

  Results.prototype.displayMessage = function (params) {
    var escapeMarkup = this.options.get('escapeMarkup');

    this.clear();
    this.hideLoading();

    var $message = $(
      '<li role="alert" aria-live="assertive"' +
      ' class="select2-results__option"></li>'
    );

    var message = this.options.get('translations').get(params.message);

    $message.append(
      escapeMarkup(
        message(params.args)
      )
    );

    $message[0].className += ' select2-results__message';

    this.$results.append($message);
  };

  Results.prototype.hideMessages = function () {
    this.$results.find('.select2-results__message').remove();
  };

  Results.prototype.append = function (data) {
    this.hideLoading();

    var $options = [];

    if (data.results == null || data.results.length === 0) {
      if (this.$results.children().length === 0) {
        this.trigger('results:message', {
          message: 'noResults'
        });
      }

      return;
    }

    data.results = this.sort(data.results);

    for (var d = 0; d < data.results.length; d++) {
      var item = data.results[d];

      var $option = this.option(item);

      $options.push($option);
    }

    this.$results.append($options);
  };

  Results.prototype.position = function ($results, $dropdown) {
    var $resultsContainer = $dropdown.find('.select2-results');
    $resultsContainer.append($results);
  };

  Results.prototype.sort = function (data) {
    var sorter = this.options.get('sorter');

    return sorter(data);
  };

  Results.prototype.highlightFirstItem = function () {
    var $options = this.$results
      .find('.select2-results__option[aria-selected]');

    var $selected = $options.filter('[aria-selected=true]');

    // Check if there are any selected options
    if ($selected.length > 0) {
      // If there are selected options, highlight the first
      $selected.first().trigger('mouseenter');
    } else {
      // If there are no selected options, highlight the first option
      // in the dropdown
      $options.first().trigger('mouseenter');
    }

    this.ensureHighlightVisible();
  };

  Results.prototype.setClasses = function () {
    var self = this;

    this.data.current(function (selected) {
      var selectedIds = $.map(selected, function (s) {
        return s.id.toString();
      });

      var $options = self.$results
        .find('.select2-results__option[aria-selected]');

      $options.each(function () {
        var $option = $(this);

        var item = Utils.GetData(this, 'data');

        // id needs to be converted to a string when comparing
        var id = '' + item.id;

        if ((item.element != null && item.element.selected) ||
            (item.element == null && $.inArray(id, selectedIds) > -1)) {
          $option.attr('aria-selected', 'true');
        } else {
          $option.attr('aria-selected', 'false');
        }
      });

    });
  };

  Results.prototype.showLoading = function (params) {
    this.hideLoading();

    var loadingMore = this.options.get('translations').get('searching');

    var loading = {
      disabled: true,
      loading: true,
      text: loadingMore(params)
    };
    var $loading = this.option(loading);
    $loading.className += ' loading-results';

    this.$results.prepend($loading);
  };

  Results.prototype.hideLoading = function () {
    this.$results.find('.loading-results').remove();
  };

  Results.prototype.option = function (data) {
    var option = document.createElement('li');
    option.className = 'select2-results__option';

    var attrs = {
      'role': 'option',
      'aria-selected': 'false'
    };

    var matches = window.Element.prototype.matches ||
      window.Element.prototype.msMatchesSelector ||
      window.Element.prototype.webkitMatchesSelector;

    if ((data.element != null && matches.call(data.element, ':disabled')) ||
        (data.element == null && data.disabled)) {
      delete attrs['aria-selected'];
      attrs['aria-disabled'] = 'true';
    }

    if (data.id == null) {
      delete attrs['aria-selected'];
    }

    if (data._resultId != null) {
      option.id = data._resultId;
    }

    if (data.title) {
      option.title = data.title;
    }

    if (data.children) {
      attrs.role = 'group';
      attrs['aria-label'] = data.text;
      delete attrs['aria-selected'];
    }

    for (var attr in attrs) {
      var val = attrs[attr];

      option.setAttribute(attr, val);
    }

    if (data.children) {
      var $option = $(option);

      var label = document.createElement('strong');
      label.className = 'select2-results__group';

      var $label = $(label);
      this.template(data, label);

      var $children = [];

      for (var c = 0; c < data.children.length; c++) {
        var child = data.children[c];

        var $child = this.option(child);

        $children.push($child);
      }

      var $childrenContainer = $('<ul></ul>', {
        'class': 'select2-results__options select2-results__options--nested'
      });

      $childrenContainer.append($children);

      $option.append(label);
      $option.append($childrenContainer);
    } else {
      this.template(data, option);
    }

    Utils.StoreData(option, 'data', data);

    return option;
  };

  Results.prototype.bind = function (container, $container) {
    var self = this;

    var id = container.id + '-results';

    this.$results.attr('id', id);

    container.on('results:all', function (params) {
      self.clear();
      self.append(params.data);

      if (container.isOpen()) {
        self.setClasses();
        self.highlightFirstItem();
      }
    });

    container.on('results:append', function (params) {
      self.append(params.data);

      if (container.isOpen()) {
        self.setClasses();
      }
    });

    container.on('query', function (params) {
      self.hideMessages();
      self.showLoading(params);
    });

    container.on('select', function () {
      if (!container.isOpen()) {
        return;
      }

      self.setClasses();

      if (self.options.get('scrollAfterSelect')) {
        self.highlightFirstItem();
      }
    });

    container.on('unselect', function () {
      if (!container.isOpen()) {
        return;
      }

      self.setClasses();

      if (self.options.get('scrollAfterSelect')) {
        self.highlightFirstItem();
      }
    });

    container.on('open', function () {
      // When the dropdown is open, aria-expended="true"
      self.$results.attr('aria-expanded', 'true');
      self.$results.attr('aria-hidden', 'false');

      self.setClasses();
      self.ensureHighlightVisible();
    });

    container.on('close', function () {
      // When the dropdown is closed, aria-expended="false"
      self.$results.attr('aria-expanded', 'false');
      self.$results.attr('aria-hidden', 'true');
      self.$results.removeAttr('aria-activedescendant');
    });

    container.on('results:toggle', function () {
      var $highlighted = self.getHighlightedResults();

      if ($highlighted.length === 0) {
        return;
      }

      $highlighted.trigger('mouseup');
    });

    container.on('results:select', function () {
      var $highlighted = self.getHighlightedResults();

      if ($highlighted.length === 0) {
        return;
      }

      var data = Utils.GetData($highlighted[0], 'data');

      if ($highlighted.attr('aria-selected') == 'true') {
        self.trigger('close', {});
      } else {
        self.trigger('select', {
          data: data
        });
      }
    });

    container.on('results:previous', function () {
      var $highlighted = self.getHighlightedResults();

      var $options = self.$results.find('[aria-selected]');

      var currentIndex = $options.index($highlighted);

      // If we are already at the top, don't move further
      // If no options, currentIndex will be -1
      if (currentIndex <= 0) {
        return;
      }

      var nextIndex = currentIndex - 1;

      // If none are highlighted, highlight the first
      if ($highlighted.length === 0) {
        nextIndex = 0;
      }

      var $next = $options.eq(nextIndex);

      $next.trigger('mouseenter');

      var currentOffset = self.$results.offset().top;
      var nextTop = $next.offset().top;
      var nextOffset = self.$results.scrollTop() + (nextTop - currentOffset);

      if (nextIndex === 0) {
        self.$results.scrollTop(0);
      } else if (nextTop - currentOffset < 0) {
        self.$results.scrollTop(nextOffset);
      }
    });

    container.on('results:next', function () {
      var $highlighted = self.getHighlightedResults();

      var $options = self.$results.find('[aria-selected]');

      var currentIndex = $options.index($highlighted);

      var nextIndex = currentIndex + 1;

      // If we are at the last option, stay there
      if (nextIndex >= $options.length) {
        return;
      }

      var $next = $options.eq(nextIndex);

      $next.trigger('mouseenter');

      var currentOffset = self.$results.offset().top +
        self.$results.outerHeight(false);
      var nextBottom = $next.offset().top + $next.outerHeight(false);
      var nextOffset = self.$results.scrollTop() + nextBottom - currentOffset;

      if (nextIndex === 0) {
        self.$results.scrollTop(0);
      } else if (nextBottom > currentOffset) {
        self.$results.scrollTop(nextOffset);
      }
    });

    container.on('results:focus', function (params) {
      params.element.addClass('select2-results__option--highlighted');
    });

    container.on('results:message', function (params) {
      self.displayMessage(params);
    });

    if ($.fn.mousewheel) {
      this.$results.on('mousewheel', function (e) {
        var top = self.$results.scrollTop();

        var bottom = self.$results.get(0).scrollHeight - top + e.deltaY;

        var isAtTop = e.deltaY > 0 && top - e.deltaY <= 0;
        var isAtBottom = e.deltaY < 0 && bottom <= self.$results.height();

        if (isAtTop) {
          self.$results.scrollTop(0);

          e.preventDefault();
          e.stopPropagation();
        } else if (isAtBottom) {
          self.$results.scrollTop(
            self.$results.get(0).scrollHeight - self.$results.height()
          );

          e.preventDefault();
          e.stopPropagation();
        }
      });
    }

    this.$results.on('mouseup', '.select2-results__option[aria-selected]',
      function (evt) {
      var $this = $(this);

      var data = Utils.GetData(this, 'data');

      if ($this.attr('aria-selected') === 'true') {
        if (self.options.get('multiple')) {
          self.trigger('unselect', {
            originalEvent: evt,
            data: data
          });
        } else {
          self.trigger('close', {});
        }

        return;
      }

      self.trigger('select', {
        originalEvent: evt,
        data: data
      });
    });

    this.$results.on('mouseenter', '.select2-results__option[aria-selected]',
      function (evt) {
      var data = Utils.GetData(this, 'data');

      self.getHighlightedResults()
          .removeClass('select2-results__option--highlighted');

      self.trigger('results:focus', {
        data: data,
        element: $(this)
      });
    });
  };

  Results.prototype.getHighlightedResults = function () {
    var $highlighted = this.$results
    .find('.select2-results__option--highlighted');

    return $highlighted;
  };

  Results.prototype.destroy = function () {
    this.$results.remove();
  };

  Results.prototype.ensureHighlightVisible = function () {
    var $highlighted = this.getHighlightedResults();

    if ($highlighted.length === 0) {
      return;
    }

    var $options = this.$results.find('[aria-selected]');

    var currentIndex = $options.index($highlighted);

    var currentOffset = this.$results.offset().top;
    var nextTop = $highlighted.offset().top;
    var nextOffset = this.$results.scrollTop() + (nextTop - currentOffset);

    var offsetDelta = nextTop - currentOffset;
    nextOffset -= $highlighted.outerHeight(false) * 2;

    if (currentIndex <= 2) {
      this.$results.scrollTop(0);
    } else if (offsetDelta > this.$results.outerHeight() || offsetDelta < 0) {
      this.$results.scrollTop(nextOffset);
    }
  };

  Results.prototype.template = function (result, container) {
    var template = this.options.get('templateResult');
    var escapeMarkup = this.options.get('escapeMarkup');

    var content = template(result, container);

    if (content == null) {
      container.style.display = 'none';
    } else if (typeof content === 'string') {
      container.innerHTML = escapeMarkup(content);
    } else {
      $(container).append(content);
    }
  };

  return Results;
});

S2.define('select2/keys',[

], function () {
  var KEYS = {
    BACKSPACE: 8,
    TAB: 9,
    ENTER: 13,
    SHIFT: 16,
    CTRL: 17,
    ALT: 18,
    ESC: 27,
    SPACE: 32,
    PAGE_UP: 33,
    PAGE_DOWN: 34,
    END: 35,
    HOME: 36,
    LEFT: 37,
    UP: 38,
    RIGHT: 39,
    DOWN: 40,
    DELETE: 46
  };

  return KEYS;
});

S2.define('select2/selection/base',[
  'jquery',
  '../utils',
  '../keys'
], function ($, Utils, KEYS) {
  function BaseSelection ($element, options) {
    this.$element = $element;
    this.options = options;

    BaseSelection.__super__.constructor.call(this);
  }

  Utils.Extend(BaseSelection, Utils.Observable);

  BaseSelection.prototype.render = function () {
    var $selection = $(
      '<span class="select2-selection" role="combobox" ' +
      ' aria-haspopup="true" aria-expanded="false">' +
      '</span>'
    );

    this._tabindex = 0;

    if (Utils.GetData(this.$element[0], 'old-tabindex') != null) {
      this._tabindex = Utils.GetData(this.$element[0], 'old-tabindex');
    } else if (this.$element.attr('tabindex') != null) {
      this._tabindex = this.$element.attr('tabindex');
    }

    $selection.attr('title', this.$element.attr('title'));
    $selection.attr('tabindex', this._tabindex);
    $selection.attr('aria-disabled', 'false');

    this.$selection = $selection;

    return $selection;
  };

  BaseSelection.prototype.bind = function (container, $container) {
    var self = this;

    var resultsId = container.id + '-results';

    this.container = container;

    this.$selection.on('focus', function (evt) {
      self.trigger('focus', evt);
    });

    this.$selection.on('blur', function (evt) {
      self._handleBlur(evt);
    });

    this.$selection.on('keydown', function (evt) {
      self.trigger('keypress', evt);

      if (evt.which === KEYS.SPACE) {
        evt.preventDefault();
      }
    });

    container.on('results:focus', function (params) {
      self.$selection.attr('aria-activedescendant', params.data._resultId);
    });

    container.on('selection:update', function (params) {
      self.update(params.data);
    });

    container.on('open', function () {
      // When the dropdown is open, aria-expanded="true"
      self.$selection.attr('aria-expanded', 'true');
      self.$selection.attr('aria-owns', resultsId);

      self._attachCloseHandler(container);
    });

    container.on('close', function () {
      // When the dropdown is closed, aria-expanded="false"
      self.$selection.attr('aria-expanded', 'false');
      self.$selection.removeAttr('aria-activedescendant');
      self.$selection.removeAttr('aria-owns');

      self.$selection.trigger('focus');

      self._detachCloseHandler(container);
    });

    container.on('enable', function () {
      self.$selection.attr('tabindex', self._tabindex);
      self.$selection.attr('aria-disabled', 'false');
    });

    container.on('disable', function () {
      self.$selection.attr('tabindex', '-1');
      self.$selection.attr('aria-disabled', 'true');
    });
  };

  BaseSelection.prototype._handleBlur = function (evt) {
    var self = this;

    // This needs to be delayed as the active element is the body when the tab
    // key is pressed, possibly along with others.
    window.setTimeout(function () {
      // Don't trigger `blur` if the focus is still in the selection
      if (
        (document.activeElement == self.$selection[0]) ||
        ($.contains(self.$selection[0], document.activeElement))
      ) {
        return;
      }

      self.trigger('blur', evt);
    }, 1);
  };

  BaseSelection.prototype._attachCloseHandler = function (container) {

    $(document.body).on('mousedown.select2.' + container.id, function (e) {
      var $target = $(e.target);

      var $select = $target.closest('.select2');

      var $all = $('.select2.select2-container--open');

      $all.each(function () {
        if (this == $select[0]) {
          return;
        }

        var $element = Utils.GetData(this, 'element');

        $element.select2('close');
      });
    });
  };

  BaseSelection.prototype._detachCloseHandler = function (container) {
    $(document.body).off('mousedown.select2.' + container.id);
  };

  BaseSelection.prototype.position = function ($selection, $container) {
    var $selectionContainer = $container.find('.selection');
    $selectionContainer.append($selection);
  };

  BaseSelection.prototype.destroy = function () {
    this._detachCloseHandler(this.container);
  };

  BaseSelection.prototype.update = function (data) {
    throw new Error('The `update` method must be defined in child classes.');
  };

  return BaseSelection;
});

S2.define('select2/selection/single',[
  'jquery',
  './base',
  '../utils',
  '../keys'
], function ($, BaseSelection, Utils, KEYS) {
  function SingleSelection () {
    SingleSelection.__super__.constructor.apply(this, arguments);
  }

  Utils.Extend(SingleSelection, BaseSelection);

  SingleSelection.prototype.render = function () {
    var $selection = SingleSelection.__super__.render.call(this);

    $selection.addClass('select2-selection--single');

    $selection.html(
      '<span class="select2-selection__rendered"></span>' +
      '<span class="select2-selection__arrow" role="presentation">' +
        '<b role="presentation"></b>' +
      '</span>'
    );

    return $selection;
  };

  SingleSelection.prototype.bind = function (container, $container) {
    var self = this;

    SingleSelection.__super__.bind.apply(this, arguments);

    var id = container.id + '-container';

    this.$selection.find('.select2-selection__rendered')
      .attr('id', id)
      .attr('role', 'textbox')
      .attr('aria-readonly', 'true');
    this.$selection.attr('aria-labelledby', id);

    this.$selection.on('mousedown', function (evt) {
      // Only respond to left clicks
      if (evt.which !== 1) {
        return;
      }

      self.trigger('toggle', {
        originalEvent: evt
      });
    });

    this.$selection.on('focus', function (evt) {
      // User focuses on the container
    });

    this.$selection.on('blur', function (evt) {
      // User exits the container
    });

    container.on('focus', function (evt) {
      if (!container.isOpen()) {
        self.$selection.trigger('focus');
      }
    });
  };

  SingleSelection.prototype.clear = function () {
    var $rendered = this.$selection.find('.select2-selection__rendered');
    $rendered.empty();
    $rendered.removeAttr('title'); // clear tooltip on empty
  };

  SingleSelection.prototype.display = function (data, container) {
    var template = this.options.get('templateSelection');
    var escapeMarkup = this.options.get('escapeMarkup');

    return escapeMarkup(template(data, container));
  };

  SingleSelection.prototype.selectionContainer = function () {
    return $('<span></span>');
  };

  SingleSelection.prototype.update = function (data) {
    if (data.length === 0) {
      this.clear();
      return;
    }

    var selection = data[0];

    var $rendered = this.$selection.find('.select2-selection__rendered');
    var formatted = this.display(selection, $rendered);

    $rendered.empty().append(formatted);

    var title = selection.title || selection.text;

    if (title) {
      $rendered.attr('title', title);
    } else {
      $rendered.removeAttr('title');
    }
  };

  return SingleSelection;
});

S2.define('select2/selection/multiple',[
  'jquery',
  './base',
  '../utils'
], function ($, BaseSelection, Utils) {
  function MultipleSelection ($element, options) {
    MultipleSelection.__super__.constructor.apply(this, arguments);
  }

  Utils.Extend(MultipleSelection, BaseSelection);

  MultipleSelection.prototype.render = function () {
    var $selection = MultipleSelection.__super__.render.call(this);

    $selection.addClass('select2-selection--multiple');

    $selection.html(
      '<ul class="select2-selection__rendered"></ul>'
    );

    return $selection;
  };

  MultipleSelection.prototype.bind = function (container, $container) {
    var self = this;

    MultipleSelection.__super__.bind.apply(this, arguments);

    this.$selection.on('click', function (evt) {
      self.trigger('toggle', {
        originalEvent: evt
      });
    });

    this.$selection.on(
      'click',
      '.select2-selection__choice__remove',
      function (evt) {
        // Ignore the event if it is disabled
        if (self.options.get('disabled')) {
          return;
        }

        var $remove = $(this);
        var $selection = $remove.parent();

        var data = Utils.GetData($selection[0], 'data');

        self.trigger('unselect', {
          originalEvent: evt,
          data: data
        });
      }
    );
  };

  MultipleSelection.prototype.clear = function () {
    var $rendered = this.$selection.find('.select2-selection__rendered');
    $rendered.empty();
    $rendered.removeAttr('title');
  };

  MultipleSelection.prototype.display = function (data, container) {
    var template = this.options.get('templateSelection');
    var escapeMarkup = this.options.get('escapeMarkup');

    return escapeMarkup(template(data, container));
  };

  MultipleSelection.prototype.selectionContainer = function () {
    var $container = $(
      '<li class="select2-selection__choice">' +
        '<span class="select2-selection__choice__remove" role="presentation">' +
          '&times;' +
        '</span>' +
      '</li>'
    );

    return $container;
  };

  MultipleSelection.prototype.update = function (data) {
    this.clear();

    if (data.length === 0) {
      return;
    }

    var $selections = [];

    for (var d = 0; d < data.length; d++) {
      var selection = data[d];

      var $selection = this.selectionContainer();
      var formatted = this.display(selection, $selection);

      $selection.append(formatted);

      var title = selection.title || selection.text;

      if (title) {
        $selection.attr('title', title);
      }

      Utils.StoreData($selection[0], 'data', selection);

      $selections.push($selection);
    }

    var $rendered = this.$selection.find('.select2-selection__rendered');

    Utils.appendMany($rendered, $selections);
  };

  return MultipleSelection;
});

S2.define('select2/selection/placeholder',[
  '../utils'
], function (Utils) {
  function Placeholder (decorated, $element, options) {
    this.placeholder = this.normalizePlaceholder(options.get('placeholder'));

    decorated.call(this, $element, options);
  }

  Placeholder.prototype.normalizePlaceholder = function (_, placeholder) {
    if (typeof placeholder === 'string') {
      placeholder = {
        id: '',
        text: placeholder
      };
    }

    return placeholder;
  };

  Placeholder.prototype.createPlaceholder = function (decorated, placeholder) {
    var $placeholder = this.selectionContainer();

    $placeholder.html(this.display(placeholder));
    $placeholder.addClass('select2-selection__placeholder')
                .removeClass('select2-selection__choice');

    return $placeholder;
  };

  Placeholder.prototype.update = function (decorated, data) {
    var singlePlaceholder = (
      data.length == 1 && data[0].id != this.placeholder.id
    );
    var multipleSelections = data.length > 1;

    if (multipleSelections || singlePlaceholder) {
      return decorated.call(this, data);
    }

    this.clear();

    var $placeholder = this.createPlaceholder(this.placeholder);

    this.$selection.find('.select2-selection__rendered').append($placeholder);
  };

  return Placeholder;
});

S2.define('select2/selection/allowClear',[
  'jquery',
  '../keys',
  '../utils'
], function ($, KEYS, Utils) {
  function AllowClear () { }

  AllowClear.prototype.bind = function (decorated, container, $container) {
    var self = this;

    decorated.call(this, container, $container);

    if (this.placeholder == null) {
      if (this.options.get('debug') && window.console && console.error) {
        console.error(
          'Select2: The `allowClear` option should be used in combination ' +
          'with the `placeholder` option.'
        );
      }
    }

    this.$selection.on('mousedown', '.select2-selection__clear',
      function (evt) {
        self._handleClear(evt);
    });

    container.on('keypress', function (evt) {
      self._handleKeyboardClear(evt, container);
    });
  };

  AllowClear.prototype._handleClear = function (_, evt) {
    // Ignore the event if it is disabled
    if (this.options.get('disabled')) {
      return;
    }

    var $clear = this.$selection.find('.select2-selection__clear');

    // Ignore the event if nothing has been selected
    if ($clear.length === 0) {
      return;
    }

    evt.stopPropagation();

    var data = Utils.GetData($clear[0], 'data');

    var previousVal = this.$element.val();
    this.$element.val(this.placeholder.id);

    var unselectData = {
      data: data
    };
    this.trigger('clear', unselectData);
    if (unselectData.prevented) {
      this.$element.val(previousVal);
      return;
    }

    for (var d = 0; d < data.length; d++) {
      unselectData = {
        data: data[d]
      };

      // Trigger the `unselect` event, so people can prevent it from being
      // cleared.
      this.trigger('unselect', unselectData);

      // If the event was prevented, don't clear it out.
      if (unselectData.prevented) {
        this.$element.val(previousVal);
        return;
      }
    }

    this.$element.trigger('change');

    this.trigger('toggle', {});
  };

  AllowClear.prototype._handleKeyboardClear = function (_, evt, container) {
    if (container.isOpen()) {
      return;
    }

    if (evt.which == KEYS.DELETE || evt.which == KEYS.BACKSPACE) {
      this._handleClear(evt);
    }
  };

  AllowClear.prototype.update = function (decorated, data) {
    decorated.call(this, data);

    if (this.$selection.find('.select2-selection__placeholder').length > 0 ||
        data.length === 0) {
      return;
    }

    var removeAll = this.options.get('translations').get('removeAllItems');   

    var $remove = $(
      '<span class="select2-selection__clear" title="' + removeAll() +'">' +
        '&times;' +
      '</span>'
    );
    Utils.StoreData($remove[0], 'data', data);

    this.$selection.find('.select2-selection__rendered').prepend($remove);
  };

  return AllowClear;
});

S2.define('select2/selection/search',[
  'jquery',
  '../utils',
  '../keys'
], function ($, Utils, KEYS) {
  function Search (decorated, $element, options) {
    decorated.call(this, $element, options);
  }

  Search.prototype.render = function (decorated) {
    var $search = $(
      '<li class="select2-search select2-search--inline">' +
        '<label for="filterLabel" class="vh">Zoek specifieke filter</label>'+
        '<input id="filter-label"  class="select2-search__field" type="search" tabindex="-1"' +
        ' autocomplete="off" autocorrect="off" autocapitalize="none"' +
        ' spellcheck="false" role="searchbox" aria-autocomplete="list" />' +
      '</li>'
    );

    this.$searchContainer = $search;
    this.$search = $search.find('input');

    var $rendered = decorated.call(this);

    this._transferTabIndex();

    return $rendered;
  };

  Search.prototype.bind = function (decorated, container, $container) {
    var self = this;

    var resultsId = container.id + '-results';

    decorated.call(this, container, $container);

    container.on('open', function () {
      self.$search.attr('aria-controls', resultsId);
      self.$search.trigger('focus');
    });

    container.on('close', function () {
      self.$search.val('');
      self.$search.removeAttr('aria-controls');
      self.$search.removeAttr('aria-activedescendant');
      self.$search.trigger('focus');
    });

    container.on('enable', function () {
      self.$search.prop('disabled', false);

      self._transferTabIndex();
    });

    container.on('disable', function () {
      self.$search.prop('disabled', true);
    });

    container.on('focus', function (evt) {
      self.$search.trigger('focus');
    });

    container.on('results:focus', function (params) {
      if (params.data._resultId) {
        self.$search.attr('aria-activedescendant', params.data._resultId);
      } else {
        self.$search.removeAttr('aria-activedescendant');
      }
    });

    this.$selection.on('focusin', '.select2-search--inline', function (evt) {
      self.trigger('focus', evt);
    });

    this.$selection.on('focusout', '.select2-search--inline', function (evt) {
      self._handleBlur(evt);
    });

    this.$selection.on('keydown', '.select2-search--inline', function (evt) {
      evt.stopPropagation();

      self.trigger('keypress', evt);

      self._keyUpPrevented = evt.isDefaultPrevented();

      var key = evt.which;

      if (key === KEYS.BACKSPACE && self.$search.val() === '') {
        var $previousChoice = self.$searchContainer
          .prev('.select2-selection__choice');

        if ($previousChoice.length > 0) {
          var item = Utils.GetData($previousChoice[0], 'data');

          self.searchRemoveChoice(item);

          evt.preventDefault();
        }
      }
    });

    this.$selection.on('click', '.select2-search--inline', function (evt) {
      if (self.$search.val()) {
        evt.stopPropagation();
      }
    });

    // Try to detect the IE version should the `documentMode` property that
    // is stored on the document. This is only implemented in IE and is
    // slightly cleaner than doing a user agent check.
    // This property is not available in Edge, but Edge also doesn't have
    // this bug.
    var msie = document.documentMode;
    var disableInputEvents = msie && msie <= 11;

    // Workaround for browsers which do not support the `input` event
    // This will prevent double-triggering of events for browsers which support
    // both the `keyup` and `input` events.
    this.$selection.on(
      'input.searchcheck',
      '.select2-search--inline',
      function (evt) {
        // IE will trigger the `input` event when a placeholder is used on a
        // search box. To get around this issue, we are forced to ignore all
        // `input` events in IE and keep using `keyup`.
        if (disableInputEvents) {
          self.$selection.off('input.search input.searchcheck');
          return;
        }

        // Unbind the duplicated `keyup` event
        self.$selection.off('keyup.search');
      }
    );

    this.$selection.on(
      'keyup.search input.search',
      '.select2-search--inline',
      function (evt) {
        // IE will trigger the `input` event when a placeholder is used on a
        // search box. To get around this issue, we are forced to ignore all
        // `input` events in IE and keep using `keyup`.
        if (disableInputEvents && evt.type === 'input') {
          self.$selection.off('input.search input.searchcheck');
          return;
        }

        var key = evt.which;

        // We can freely ignore events from modifier keys
        if (key == KEYS.SHIFT || key == KEYS.CTRL || key == KEYS.ALT) {
          return;
        }

        // Tabbing will be handled during the `keydown` phase
        if (key == KEYS.TAB) {
          return;
        }

        self.handleSearch(evt);
      }
    );
  };

  /**
   * This method will transfer the tabindex attribute from the rendered
   * selection to the search box. This allows for the search box to be used as
   * the primary focus instead of the selection container.
   *
   * @private
   */
  Search.prototype._transferTabIndex = function (decorated) {
    this.$search.attr('tabindex', this.$selection.attr('tabindex'));
    this.$selection.attr('tabindex', '-1');
  };

  Search.prototype.createPlaceholder = function (decorated, placeholder) {
    this.$search.attr('placeholder', placeholder.text);
  };

  Search.prototype.update = function (decorated, data) {
    var searchHadFocus = this.$search[0] == document.activeElement;

    this.$search.attr('placeholder', '');

    decorated.call(this, data);

    this.$selection.find('.select2-selection__rendered')
                   .append(this.$searchContainer);

    this.resizeSearch();
    if (searchHadFocus) {
      this.$search.trigger('focus');
    }
  };

  Search.prototype.handleSearch = function () {
    this.resizeSearch();

    if (!this._keyUpPrevented) {
      var input = this.$search.val();

      this.trigger('query', {
        term: input
      });
    }

    this._keyUpPrevented = false;
  };

  Search.prototype.searchRemoveChoice = function (decorated, item) {
    this.trigger('unselect', {
      data: item
    });

    this.$search.val(item.text);
    this.handleSearch();
  };

  Search.prototype.resizeSearch = function () {
    this.$search.css('width', '25px');

    var width = '';

    if (this.$search.attr('placeholder') !== '') {
      width = this.$selection.find('.select2-selection__rendered').width();
    } else {
      var minimumWidth = this.$search.val().length + 1;

      width = (minimumWidth * 0.75) + 'em';
    }

    this.$search.css('width', width);
  };

  return Search;
});

S2.define('select2/selection/eventRelay',[
  'jquery'
], function ($) {
  function EventRelay () { }

  EventRelay.prototype.bind = function (decorated, container, $container) {
    var self = this;
    var relayEvents = [
      'open', 'opening',
      'close', 'closing',
      'select', 'selecting',
      'unselect', 'unselecting',
      'clear', 'clearing'
    ];

    var preventableEvents = [
      'opening', 'closing', 'selecting', 'unselecting', 'clearing'
    ];

    decorated.call(this, container, $container);

    container.on('*', function (name, params) {
      // Ignore events that should not be relayed
      if ($.inArray(name, relayEvents) === -1) {
        return;
      }

      // The parameters should always be an object
      params = params || {};

      // Generate the jQuery event for the Select2 event
      var evt = $.Event('select2:' + name, {
        params: params
      });

      self.$element.trigger(evt);

      // Only handle preventable events if it was one
      if ($.inArray(name, preventableEvents) === -1) {
        return;
      }

      params.prevented = evt.isDefaultPrevented();
    });
  };

  return EventRelay;
});

S2.define('select2/translation',[
  'jquery',
  'require'
], function ($, require) {
  function Translation (dict) {
    this.dict = dict || {};
  }

  Translation.prototype.all = function () {
    return this.dict;
  };

  Translation.prototype.get = function (key) {
    return this.dict[key];
  };

  Translation.prototype.extend = function (translation) {
    this.dict = $.extend({}, translation.all(), this.dict);
  };

  // Static functions

  Translation._cache = {};

  Translation.loadPath = function (path) {
    if (!(path in Translation._cache)) {
      var translations = require(path);

      Translation._cache[path] = translations;
    }

    return new Translation(Translation._cache[path]);
  };

  return Translation;
});

S2.define('select2/diacritics',[

], function () {
  var diacritics = {
    '\u24B6': 'A',
    '\uFF21': 'A',
    '\u00C0': 'A',
    '\u00C1': 'A',
    '\u00C2': 'A',
    '\u1EA6': 'A',
    '\u1EA4': 'A',
    '\u1EAA': 'A',
    '\u1EA8': 'A',
    '\u00C3': 'A',
    '\u0100': 'A',
    '\u0102': 'A',
    '\u1EB0': 'A',
    '\u1EAE': 'A',
    '\u1EB4': 'A',
    '\u1EB2': 'A',
    '\u0226': 'A',
    '\u01E0': 'A',
    '\u00C4': 'A',
    '\u01DE': 'A',
    '\u1EA2': 'A',
    '\u00C5': 'A',
    '\u01FA': 'A',
    '\u01CD': 'A',
    '\u0200': 'A',
    '\u0202': 'A',
    '\u1EA0': 'A',
    '\u1EAC': 'A',
    '\u1EB6': 'A',
    '\u1E00': 'A',
    '\u0104': 'A',
    '\u023A': 'A',
    '\u2C6F': 'A',
    '\uA732': 'AA',
    '\u00C6': 'AE',
    '\u01FC': 'AE',
    '\u01E2': 'AE',
    '\uA734': 'AO',
    '\uA736': 'AU',
    '\uA738': 'AV',
    '\uA73A': 'AV',
    '\uA73C': 'AY',
    '\u24B7': 'B',
    '\uFF22': 'B',
    '\u1E02': 'B',
    '\u1E04': 'B',
    '\u1E06': 'B',
    '\u0243': 'B',
    '\u0182': 'B',
    '\u0181': 'B',
    '\u24B8': 'C',
    '\uFF23': 'C',
    '\u0106': 'C',
    '\u0108': 'C',
    '\u010A': 'C',
    '\u010C': 'C',
    '\u00C7': 'C',
    '\u1E08': 'C',
    '\u0187': 'C',
    '\u023B': 'C',
    '\uA73E': 'C',
    '\u24B9': 'D',
    '\uFF24': 'D',
    '\u1E0A': 'D',
    '\u010E': 'D',
    '\u1E0C': 'D',
    '\u1E10': 'D',
    '\u1E12': 'D',
    '\u1E0E': 'D',
    '\u0110': 'D',
    '\u018B': 'D',
    '\u018A': 'D',
    '\u0189': 'D',
    '\uA779': 'D',
    '\u01F1': 'DZ',
    '\u01C4': 'DZ',
    '\u01F2': 'Dz',
    '\u01C5': 'Dz',
    '\u24BA': 'E',
    '\uFF25': 'E',
    '\u00C8': 'E',
    '\u00C9': 'E',
    '\u00CA': 'E',
    '\u1EC0': 'E',
    '\u1EBE': 'E',
    '\u1EC4': 'E',
    '\u1EC2': 'E',
    '\u1EBC': 'E',
    '\u0112': 'E',
    '\u1E14': 'E',
    '\u1E16': 'E',
    '\u0114': 'E',
    '\u0116': 'E',
    '\u00CB': 'E',
    '\u1EBA': 'E',
    '\u011A': 'E',
    '\u0204': 'E',
    '\u0206': 'E',
    '\u1EB8': 'E',
    '\u1EC6': 'E',
    '\u0228': 'E',
    '\u1E1C': 'E',
    '\u0118': 'E',
    '\u1E18': 'E',
    '\u1E1A': 'E',
    '\u0190': 'E',
    '\u018E': 'E',
    '\u24BB': 'F',
    '\uFF26': 'F',
    '\u1E1E': 'F',
    '\u0191': 'F',
    '\uA77B': 'F',
    '\u24BC': 'G',
    '\uFF27': 'G',
    '\u01F4': 'G',
    '\u011C': 'G',
    '\u1E20': 'G',
    '\u011E': 'G',
    '\u0120': 'G',
    '\u01E6': 'G',
    '\u0122': 'G',
    '\u01E4': 'G',
    '\u0193': 'G',
    '\uA7A0': 'G',
    '\uA77D': 'G',
    '\uA77E': 'G',
    '\u24BD': 'H',
    '\uFF28': 'H',
    '\u0124': 'H',
    '\u1E22': 'H',
    '\u1E26': 'H',
    '\u021E': 'H',
    '\u1E24': 'H',
    '\u1E28': 'H',
    '\u1E2A': 'H',
    '\u0126': 'H',
    '\u2C67': 'H',
    '\u2C75': 'H',
    '\uA78D': 'H',
    '\u24BE': 'I',
    '\uFF29': 'I',
    '\u00CC': 'I',
    '\u00CD': 'I',
    '\u00CE': 'I',
    '\u0128': 'I',
    '\u012A': 'I',
    '\u012C': 'I',
    '\u0130': 'I',
    '\u00CF': 'I',
    '\u1E2E': 'I',
    '\u1EC8': 'I',
    '\u01CF': 'I',
    '\u0208': 'I',
    '\u020A': 'I',
    '\u1ECA': 'I',
    '\u012E': 'I',
    '\u1E2C': 'I',
    '\u0197': 'I',
    '\u24BF': 'J',
    '\uFF2A': 'J',
    '\u0134': 'J',
    '\u0248': 'J',
    '\u24C0': 'K',
    '\uFF2B': 'K',
    '\u1E30': 'K',
    '\u01E8': 'K',
    '\u1E32': 'K',
    '\u0136': 'K',
    '\u1E34': 'K',
    '\u0198': 'K',
    '\u2C69': 'K',
    '\uA740': 'K',
    '\uA742': 'K',
    '\uA744': 'K',
    '\uA7A2': 'K',
    '\u24C1': 'L',
    '\uFF2C': 'L',
    '\u013F': 'L',
    '\u0139': 'L',
    '\u013D': 'L',
    '\u1E36': 'L',
    '\u1E38': 'L',
    '\u013B': 'L',
    '\u1E3C': 'L',
    '\u1E3A': 'L',
    '\u0141': 'L',
    '\u023D': 'L',
    '\u2C62': 'L',
    '\u2C60': 'L',
    '\uA748': 'L',
    '\uA746': 'L',
    '\uA780': 'L',
    '\u01C7': 'LJ',
    '\u01C8': 'Lj',
    '\u24C2': 'M',
    '\uFF2D': 'M',
    '\u1E3E': 'M',
    '\u1E40': 'M',
    '\u1E42': 'M',
    '\u2C6E': 'M',
    '\u019C': 'M',
    '\u24C3': 'N',
    '\uFF2E': 'N',
    '\u01F8': 'N',
    '\u0143': 'N',
    '\u00D1': 'N',
    '\u1E44': 'N',
    '\u0147': 'N',
    '\u1E46': 'N',
    '\u0145': 'N',
    '\u1E4A': 'N',
    '\u1E48': 'N',
    '\u0220': 'N',
    '\u019D': 'N',
    '\uA790': 'N',
    '\uA7A4': 'N',
    '\u01CA': 'NJ',
    '\u01CB': 'Nj',
    '\u24C4': 'O',
    '\uFF2F': 'O',
    '\u00D2': 'O',
    '\u00D3': 'O',
    '\u00D4': 'O',
    '\u1ED2': 'O',
    '\u1ED0': 'O',
    '\u1ED6': 'O',
    '\u1ED4': 'O',
    '\u00D5': 'O',
    '\u1E4C': 'O',
    '\u022C': 'O',
    '\u1E4E': 'O',
    '\u014C': 'O',
    '\u1E50': 'O',
    '\u1E52': 'O',
    '\u014E': 'O',
    '\u022E': 'O',
    '\u0230': 'O',
    '\u00D6': 'O',
    '\u022A': 'O',
    '\u1ECE': 'O',
    '\u0150': 'O',
    '\u01D1': 'O',
    '\u020C': 'O',
    '\u020E': 'O',
    '\u01A0': 'O',
    '\u1EDC': 'O',
    '\u1EDA': 'O',
    '\u1EE0': 'O',
    '\u1EDE': 'O',
    '\u1EE2': 'O',
    '\u1ECC': 'O',
    '\u1ED8': 'O',
    '\u01EA': 'O',
    '\u01EC': 'O',
    '\u00D8': 'O',
    '\u01FE': 'O',
    '\u0186': 'O',
    '\u019F': 'O',
    '\uA74A': 'O',
    '\uA74C': 'O',
    '\u0152': 'OE',
    '\u01A2': 'OI',
    '\uA74E': 'OO',
    '\u0222': 'OU',
    '\u24C5': 'P',
    '\uFF30': 'P',
    '\u1E54': 'P',
    '\u1E56': 'P',
    '\u01A4': 'P',
    '\u2C63': 'P',
    '\uA750': 'P',
    '\uA752': 'P',
    '\uA754': 'P',
    '\u24C6': 'Q',
    '\uFF31': 'Q',
    '\uA756': 'Q',
    '\uA758': 'Q',
    '\u024A': 'Q',
    '\u24C7': 'R',
    '\uFF32': 'R',
    '\u0154': 'R',
    '\u1E58': 'R',
    '\u0158': 'R',
    '\u0210': 'R',
    '\u0212': 'R',
    '\u1E5A': 'R',
    '\u1E5C': 'R',
    '\u0156': 'R',
    '\u1E5E': 'R',
    '\u024C': 'R',
    '\u2C64': 'R',
    '\uA75A': 'R',
    '\uA7A6': 'R',
    '\uA782': 'R',
    '\u24C8': 'S',
    '\uFF33': 'S',
    '\u1E9E': 'S',
    '\u015A': 'S',
    '\u1E64': 'S',
    '\u015C': 'S',
    '\u1E60': 'S',
    '\u0160': 'S',
    '\u1E66': 'S',
    '\u1E62': 'S',
    '\u1E68': 'S',
    '\u0218': 'S',
    '\u015E': 'S',
    '\u2C7E': 'S',
    '\uA7A8': 'S',
    '\uA784': 'S',
    '\u24C9': 'T',
    '\uFF34': 'T',
    '\u1E6A': 'T',
    '\u0164': 'T',
    '\u1E6C': 'T',
    '\u021A': 'T',
    '\u0162': 'T',
    '\u1E70': 'T',
    '\u1E6E': 'T',
    '\u0166': 'T',
    '\u01AC': 'T',
    '\u01AE': 'T',
    '\u023E': 'T',
    '\uA786': 'T',
    '\uA728': 'TZ',
    '\u24CA': 'U',
    '\uFF35': 'U',
    '\u00D9': 'U',
    '\u00DA': 'U',
    '\u00DB': 'U',
    '\u0168': 'U',
    '\u1E78': 'U',
    '\u016A': 'U',
    '\u1E7A': 'U',
    '\u016C': 'U',
    '\u00DC': 'U',
    '\u01DB': 'U',
    '\u01D7': 'U',
    '\u01D5': 'U',
    '\u01D9': 'U',
    '\u1EE6': 'U',
    '\u016E': 'U',
    '\u0170': 'U',
    '\u01D3': 'U',
    '\u0214': 'U',
    '\u0216': 'U',
    '\u01AF': 'U',
    '\u1EEA': 'U',
    '\u1EE8': 'U',
    '\u1EEE': 'U',
    '\u1EEC': 'U',
    '\u1EF0': 'U',
    '\u1EE4': 'U',
    '\u1E72': 'U',
    '\u0172': 'U',
    '\u1E76': 'U',
    '\u1E74': 'U',
    '\u0244': 'U',
    '\u24CB': 'V',
    '\uFF36': 'V',
    '\u1E7C': 'V',
    '\u1E7E': 'V',
    '\u01B2': 'V',
    '\uA75E': 'V',
    '\u0245': 'V',
    '\uA760': 'VY',
    '\u24CC': 'W',
    '\uFF37': 'W',
    '\u1E80': 'W',
    '\u1E82': 'W',
    '\u0174': 'W',
    '\u1E86': 'W',
    '\u1E84': 'W',
    '\u1E88': 'W',
    '\u2C72': 'W',
    '\u24CD': 'X',
    '\uFF38': 'X',
    '\u1E8A': 'X',
    '\u1E8C': 'X',
    '\u24CE': 'Y',
    '\uFF39': 'Y',
    '\u1EF2': 'Y',
    '\u00DD': 'Y',
    '\u0176': 'Y',
    '\u1EF8': 'Y',
    '\u0232': 'Y',
    '\u1E8E': 'Y',
    '\u0178': 'Y',
    '\u1EF6': 'Y',
    '\u1EF4': 'Y',
    '\u01B3': 'Y',
    '\u024E': 'Y',
    '\u1EFE': 'Y',
    '\u24CF': 'Z',
    '\uFF3A': 'Z',
    '\u0179': 'Z',
    '\u1E90': 'Z',
    '\u017B': 'Z',
    '\u017D': 'Z',
    '\u1E92': 'Z',
    '\u1E94': 'Z',
    '\u01B5': 'Z',
    '\u0224': 'Z',
    '\u2C7F': 'Z',
    '\u2C6B': 'Z',
    '\uA762': 'Z',
    '\u24D0': 'a',
    '\uFF41': 'a',
    '\u1E9A': 'a',
    '\u00E0': 'a',
    '\u00E1': 'a',
    '\u00E2': 'a',
    '\u1EA7': 'a',
    '\u1EA5': 'a',
    '\u1EAB': 'a',
    '\u1EA9': 'a',
    '\u00E3': 'a',
    '\u0101': 'a',
    '\u0103': 'a',
    '\u1EB1': 'a',
    '\u1EAF': 'a',
    '\u1EB5': 'a',
    '\u1EB3': 'a',
    '\u0227': 'a',
    '\u01E1': 'a',
    '\u00E4': 'a',
    '\u01DF': 'a',
    '\u1EA3': 'a',
    '\u00E5': 'a',
    '\u01FB': 'a',
    '\u01CE': 'a',
    '\u0201': 'a',
    '\u0203': 'a',
    '\u1EA1': 'a',
    '\u1EAD': 'a',
    '\u1EB7': 'a',
    '\u1E01': 'a',
    '\u0105': 'a',
    '\u2C65': 'a',
    '\u0250': 'a',
    '\uA733': 'aa',
    '\u00E6': 'ae',
    '\u01FD': 'ae',
    '\u01E3': 'ae',
    '\uA735': 'ao',
    '\uA737': 'au',
    '\uA739': 'av',
    '\uA73B': 'av',
    '\uA73D': 'ay',
    '\u24D1': 'b',
    '\uFF42': 'b',
    '\u1E03': 'b',
    '\u1E05': 'b',
    '\u1E07': 'b',
    '\u0180': 'b',
    '\u0183': 'b',
    '\u0253': 'b',
    '\u24D2': 'c',
    '\uFF43': 'c',
    '\u0107': 'c',
    '\u0109': 'c',
    '\u010B': 'c',
    '\u010D': 'c',
    '\u00E7': 'c',
    '\u1E09': 'c',
    '\u0188': 'c',
    '\u023C': 'c',
    '\uA73F': 'c',
    '\u2184': 'c',
    '\u24D3': 'd',
    '\uFF44': 'd',
    '\u1E0B': 'd',
    '\u010F': 'd',
    '\u1E0D': 'd',
    '\u1E11': 'd',
    '\u1E13': 'd',
    '\u1E0F': 'd',
    '\u0111': 'd',
    '\u018C': 'd',
    '\u0256': 'd',
    '\u0257': 'd',
    '\uA77A': 'd',
    '\u01F3': 'dz',
    '\u01C6': 'dz',
    '\u24D4': 'e',
    '\uFF45': 'e',
    '\u00E8': 'e',
    '\u00E9': 'e',
    '\u00EA': 'e',
    '\u1EC1': 'e',
    '\u1EBF': 'e',
    '\u1EC5': 'e',
    '\u1EC3': 'e',
    '\u1EBD': 'e',
    '\u0113': 'e',
    '\u1E15': 'e',
    '\u1E17': 'e',
    '\u0115': 'e',
    '\u0117': 'e',
    '\u00EB': 'e',
    '\u1EBB': 'e',
    '\u011B': 'e',
    '\u0205': 'e',
    '\u0207': 'e',
    '\u1EB9': 'e',
    '\u1EC7': 'e',
    '\u0229': 'e',
    '\u1E1D': 'e',
    '\u0119': 'e',
    '\u1E19': 'e',
    '\u1E1B': 'e',
    '\u0247': 'e',
    '\u025B': 'e',
    '\u01DD': 'e',
    '\u24D5': 'f',
    '\uFF46': 'f',
    '\u1E1F': 'f',
    '\u0192': 'f',
    '\uA77C': 'f',
    '\u24D6': 'g',
    '\uFF47': 'g',
    '\u01F5': 'g',
    '\u011D': 'g',
    '\u1E21': 'g',
    '\u011F': 'g',
    '\u0121': 'g',
    '\u01E7': 'g',
    '\u0123': 'g',
    '\u01E5': 'g',
    '\u0260': 'g',
    '\uA7A1': 'g',
    '\u1D79': 'g',
    '\uA77F': 'g',
    '\u24D7': 'h',
    '\uFF48': 'h',
    '\u0125': 'h',
    '\u1E23': 'h',
    '\u1E27': 'h',
    '\u021F': 'h',
    '\u1E25': 'h',
    '\u1E29': 'h',
    '\u1E2B': 'h',
    '\u1E96': 'h',
    '\u0127': 'h',
    '\u2C68': 'h',
    '\u2C76': 'h',
    '\u0265': 'h',
    '\u0195': 'hv',
    '\u24D8': 'i',
    '\uFF49': 'i',
    '\u00EC': 'i',
    '\u00ED': 'i',
    '\u00EE': 'i',
    '\u0129': 'i',
    '\u012B': 'i',
    '\u012D': 'i',
    '\u00EF': 'i',
    '\u1E2F': 'i',
    '\u1EC9': 'i',
    '\u01D0': 'i',
    '\u0209': 'i',
    '\u020B': 'i',
    '\u1ECB': 'i',
    '\u012F': 'i',
    '\u1E2D': 'i',
    '\u0268': 'i',
    '\u0131': 'i',
    '\u24D9': 'j',
    '\uFF4A': 'j',
    '\u0135': 'j',
    '\u01F0': 'j',
    '\u0249': 'j',
    '\u24DA': 'k',
    '\uFF4B': 'k',
    '\u1E31': 'k',
    '\u01E9': 'k',
    '\u1E33': 'k',
    '\u0137': 'k',
    '\u1E35': 'k',
    '\u0199': 'k',
    '\u2C6A': 'k',
    '\uA741': 'k',
    '\uA743': 'k',
    '\uA745': 'k',
    '\uA7A3': 'k',
    '\u24DB': 'l',
    '\uFF4C': 'l',
    '\u0140': 'l',
    '\u013A': 'l',
    '\u013E': 'l',
    '\u1E37': 'l',
    '\u1E39': 'l',
    '\u013C': 'l',
    '\u1E3D': 'l',
    '\u1E3B': 'l',
    '\u017F': 'l',
    '\u0142': 'l',
    '\u019A': 'l',
    '\u026B': 'l',
    '\u2C61': 'l',
    '\uA749': 'l',
    '\uA781': 'l',
    '\uA747': 'l',
    '\u01C9': 'lj',
    '\u24DC': 'm',
    '\uFF4D': 'm',
    '\u1E3F': 'm',
    '\u1E41': 'm',
    '\u1E43': 'm',
    '\u0271': 'm',
    '\u026F': 'm',
    '\u24DD': 'n',
    '\uFF4E': 'n',
    '\u01F9': 'n',
    '\u0144': 'n',
    '\u00F1': 'n',
    '\u1E45': 'n',
    '\u0148': 'n',
    '\u1E47': 'n',
    '\u0146': 'n',
    '\u1E4B': 'n',
    '\u1E49': 'n',
    '\u019E': 'n',
    '\u0272': 'n',
    '\u0149': 'n',
    '\uA791': 'n',
    '\uA7A5': 'n',
    '\u01CC': 'nj',
    '\u24DE': 'o',
    '\uFF4F': 'o',
    '\u00F2': 'o',
    '\u00F3': 'o',
    '\u00F4': 'o',
    '\u1ED3': 'o',
    '\u1ED1': 'o',
    '\u1ED7': 'o',
    '\u1ED5': 'o',
    '\u00F5': 'o',
    '\u1E4D': 'o',
    '\u022D': 'o',
    '\u1E4F': 'o',
    '\u014D': 'o',
    '\u1E51': 'o',
    '\u1E53': 'o',
    '\u014F': 'o',
    '\u022F': 'o',
    '\u0231': 'o',
    '\u00F6': 'o',
    '\u022B': 'o',
    '\u1ECF': 'o',
    '\u0151': 'o',
    '\u01D2': 'o',
    '\u020D': 'o',
    '\u020F': 'o',
    '\u01A1': 'o',
    '\u1EDD': 'o',
    '\u1EDB': 'o',
    '\u1EE1': 'o',
    '\u1EDF': 'o',
    '\u1EE3': 'o',
    '\u1ECD': 'o',
    '\u1ED9': 'o',
    '\u01EB': 'o',
    '\u01ED': 'o',
    '\u00F8': 'o',
    '\u01FF': 'o',
    '\u0254': 'o',
    '\uA74B': 'o',
    '\uA74D': 'o',
    '\u0275': 'o',
    '\u0153': 'oe',
    '\u01A3': 'oi',
    '\u0223': 'ou',
    '\uA74F': 'oo',
    '\u24DF': 'p',
    '\uFF50': 'p',
    '\u1E55': 'p',
    '\u1E57': 'p',
    '\u01A5': 'p',
    '\u1D7D': 'p',
    '\uA751': 'p',
    '\uA753': 'p',
    '\uA755': 'p',
    '\u24E0': 'q',
    '\uFF51': 'q',
    '\u024B': 'q',
    '\uA757': 'q',
    '\uA759': 'q',
    '\u24E1': 'r',
    '\uFF52': 'r',
    '\u0155': 'r',
    '\u1E59': 'r',
    '\u0159': 'r',
    '\u0211': 'r',
    '\u0213': 'r',
    '\u1E5B': 'r',
    '\u1E5D': 'r',
    '\u0157': 'r',
    '\u1E5F': 'r',
    '\u024D': 'r',
    '\u027D': 'r',
    '\uA75B': 'r',
    '\uA7A7': 'r',
    '\uA783': 'r',
    '\u24E2': 's',
    '\uFF53': 's',
    '\u00DF': 's',
    '\u015B': 's',
    '\u1E65': 's',
    '\u015D': 's',
    '\u1E61': 's',
    '\u0161': 's',
    '\u1E67': 's',
    '\u1E63': 's',
    '\u1E69': 's',
    '\u0219': 's',
    '\u015F': 's',
    '\u023F': 's',
    '\uA7A9': 's',
    '\uA785': 's',
    '\u1E9B': 's',
    '\u24E3': 't',
    '\uFF54': 't',
    '\u1E6B': 't',
    '\u1E97': 't',
    '\u0165': 't',
    '\u1E6D': 't',
    '\u021B': 't',
    '\u0163': 't',
    '\u1E71': 't',
    '\u1E6F': 't',
    '\u0167': 't',
    '\u01AD': 't',
    '\u0288': 't',
    '\u2C66': 't',
    '\uA787': 't',
    '\uA729': 'tz',
    '\u24E4': 'u',
    '\uFF55': 'u',
    '\u00F9': 'u',
    '\u00FA': 'u',
    '\u00FB': 'u',
    '\u0169': 'u',
    '\u1E79': 'u',
    '\u016B': 'u',
    '\u1E7B': 'u',
    '\u016D': 'u',
    '\u00FC': 'u',
    '\u01DC': 'u',
    '\u01D8': 'u',
    '\u01D6': 'u',
    '\u01DA': 'u',
    '\u1EE7': 'u',
    '\u016F': 'u',
    '\u0171': 'u',
    '\u01D4': 'u',
    '\u0215': 'u',
    '\u0217': 'u',
    '\u01B0': 'u',
    '\u1EEB': 'u',
    '\u1EE9': 'u',
    '\u1EEF': 'u',
    '\u1EED': 'u',
    '\u1EF1': 'u',
    '\u1EE5': 'u',
    '\u1E73': 'u',
    '\u0173': 'u',
    '\u1E77': 'u',
    '\u1E75': 'u',
    '\u0289': 'u',
    '\u24E5': 'v',
    '\uFF56': 'v',
    '\u1E7D': 'v',
    '\u1E7F': 'v',
    '\u028B': 'v',
    '\uA75F': 'v',
    '\u028C': 'v',
    '\uA761': 'vy',
    '\u24E6': 'w',
    '\uFF57': 'w',
    '\u1E81': 'w',
    '\u1E83': 'w',
    '\u0175': 'w',
    '\u1E87': 'w',
    '\u1E85': 'w',
    '\u1E98': 'w',
    '\u1E89': 'w',
    '\u2C73': 'w',
    '\u24E7': 'x',
    '\uFF58': 'x',
    '\u1E8B': 'x',
    '\u1E8D': 'x',
    '\u24E8': 'y',
    '\uFF59': 'y',
    '\u1EF3': 'y',
    '\u00FD': 'y',
    '\u0177': 'y',
    '\u1EF9': 'y',
    '\u0233': 'y',
    '\u1E8F': 'y',
    '\u00FF': 'y',
    '\u1EF7': 'y',
    '\u1E99': 'y',
    '\u1EF5': 'y',
    '\u01B4': 'y',
    '\u024F': 'y',
    '\u1EFF': 'y',
    '\u24E9': 'z',
    '\uFF5A': 'z',
    '\u017A': 'z',
    '\u1E91': 'z',
    '\u017C': 'z',
    '\u017E': 'z',
    '\u1E93': 'z',
    '\u1E95': 'z',
    '\u01B6': 'z',
    '\u0225': 'z',
    '\u0240': 'z',
    '\u2C6C': 'z',
    '\uA763': 'z',
    '\u0386': '\u0391',
    '\u0388': '\u0395',
    '\u0389': '\u0397',
    '\u038A': '\u0399',
    '\u03AA': '\u0399',
    '\u038C': '\u039F',
    '\u038E': '\u03A5',
    '\u03AB': '\u03A5',
    '\u038F': '\u03A9',
    '\u03AC': '\u03B1',
    '\u03AD': '\u03B5',
    '\u03AE': '\u03B7',
    '\u03AF': '\u03B9',
    '\u03CA': '\u03B9',
    '\u0390': '\u03B9',
    '\u03CC': '\u03BF',
    '\u03CD': '\u03C5',
    '\u03CB': '\u03C5',
    '\u03B0': '\u03C5',
    '\u03CE': '\u03C9',
    '\u03C2': '\u03C3',
    '\u2019': '\''
  };

  return diacritics;
});

S2.define('select2/data/base',[
  '../utils'
], function (Utils) {
  function BaseAdapter ($element, options) {
    BaseAdapter.__super__.constructor.call(this);
  }

  Utils.Extend(BaseAdapter, Utils.Observable);

  BaseAdapter.prototype.current = function (callback) {
    throw new Error('The `current` method must be defined in child classes.');
  };

  BaseAdapter.prototype.query = function (params, callback) {
    throw new Error('The `query` method must be defined in child classes.');
  };

  BaseAdapter.prototype.bind = function (container, $container) {
    // Can be implemented in subclasses
  };

  BaseAdapter.prototype.destroy = function () {
    // Can be implemented in subclasses
  };

  BaseAdapter.prototype.generateResultId = function (container, data) {
    var id = container.id + '-result-';

    id += Utils.generateChars(4);

    if (data.id != null) {
      id += '-' + data.id.toString();
    } else {
      id += '-' + Utils.generateChars(4);
    }
    return id;
  };

  return BaseAdapter;
});

S2.define('select2/data/select',[
  './base',
  '../utils',
  'jquery'
], function (BaseAdapter, Utils, $) {
  function SelectAdapter ($element, options) {
    this.$element = $element;
    this.options = options;

    SelectAdapter.__super__.constructor.call(this);
  }

  Utils.Extend(SelectAdapter, BaseAdapter);

  SelectAdapter.prototype.current = function (callback) {
    var data = [];
    var self = this;

    this.$element.find(':selected').each(function () {
      var $option = $(this);

      var option = self.item($option);

      data.push(option);
    });

    callback(data);
  };

  SelectAdapter.prototype.select = function (data) {
    var self = this;

    data.selected = true;

    // If data.element is a DOM node, use it instead
    if ($(data.element).is('option')) {
      data.element.selected = true;

      this.$element.trigger('change');

      return;
    }

    if (this.$element.prop('multiple')) {
      this.current(function (currentData) {
        var val = [];

        data = [data];
        data.push.apply(data, currentData);

        for (var d = 0; d < data.length; d++) {
          var id = data[d].id;

          if ($.inArray(id, val) === -1) {
            val.push(id);
          }
        }

        self.$element.val(val);
        self.$element.trigger('change');
      });
    } else {
      var val = data.id;

      this.$element.val(val);
      this.$element.trigger('change');
    }
  };

  SelectAdapter.prototype.unselect = function (data) {
    var self = this;

    if (!this.$element.prop('multiple')) {
      return;
    }

    data.selected = false;

    if ($(data.element).is('option')) {
      data.element.selected = false;

      this.$element.trigger('change');

      return;
    }

    this.current(function (currentData) {
      var val = [];

      for (var d = 0; d < currentData.length; d++) {
        var id = currentData[d].id;

        if (id !== data.id && $.inArray(id, val) === -1) {
          val.push(id);
        }
      }

      self.$element.val(val);

      self.$element.trigger('change');
    });
  };

  SelectAdapter.prototype.bind = function (container, $container) {
    var self = this;

    this.container = container;

    container.on('select', function (params) {
      self.select(params.data);
    });

    container.on('unselect', function (params) {
      self.unselect(params.data);
    });
  };

  SelectAdapter.prototype.destroy = function () {
    // Remove anything added to child elements
    this.$element.find('*').each(function () {
      // Remove any custom data set by Select2
      Utils.RemoveData(this);
    });
  };

  SelectAdapter.prototype.query = function (params, callback) {
    var data = [];
    var self = this;

    var $options = this.$element.children();

    $options.each(function () {
      var $option = $(this);

      if (!$option.is('option') && !$option.is('optgroup')) {
        return;
      }

      var option = self.item($option);

      var matches = self.matches(params, option);

      if (matches !== null) {
        data.push(matches);
      }
    });

    callback({
      results: data
    });
  };

  SelectAdapter.prototype.addOptions = function ($options) {
    Utils.appendMany(this.$element, $options);
  };

  SelectAdapter.prototype.option = function (data) {
    var option;

    if (data.children) {
      option = document.createElement('optgroup');
      option.label = data.text;
    } else {
      option = document.createElement('option');

      if (option.textContent !== undefined) {
        option.textContent = data.text;
      } else {
        option.innerText = data.text;
      }
    }

    if (data.id !== undefined) {
      option.value = data.id;
    }

    if (data.disabled) {
      option.disabled = true;
    }

    if (data.selected) {
      option.selected = true;
    }

    if (data.title) {
      option.title = data.title;
    }

    var $option = $(option);

    var normalizedData = this._normalizeItem(data);
    normalizedData.element = option;

    // Override the option's data with the combined data
    Utils.StoreData(option, 'data', normalizedData);

    return $option;
  };

  SelectAdapter.prototype.item = function ($option) {
    var data = {};

    data = Utils.GetData($option[0], 'data');

    if (data != null) {
      return data;
    }

    if ($option.is('option')) {
      data = {
        id: $option.val(),
        text: $option.text(),
        disabled: $option.prop('disabled'),
        selected: $option.prop('selected'),
        title: $option.prop('title')
      };
    } else if ($option.is('optgroup')) {
      data = {
        text: $option.prop('label'),
        children: [],
        title: $option.prop('title')
      };

      var $children = $option.children('option');
      var children = [];

      for (var c = 0; c < $children.length; c++) {
        var $child = $($children[c]);

        var child = this.item($child);

        children.push(child);
      }

      data.children = children;
    }

    data = this._normalizeItem(data);
    data.element = $option[0];

    Utils.StoreData($option[0], 'data', data);

    return data;
  };

  SelectAdapter.prototype._normalizeItem = function (item) {
    if (item !== Object(item)) {
      item = {
        id: item,
        text: item
      };
    }

    item = $.extend({}, {
      text: ''
    }, item);

    var defaults = {
      selected: false,
      disabled: false
    };

    if (item.id != null) {
      item.id = item.id.toString();
    }

    if (item.text != null) {
      item.text = item.text.toString();
    }

    if (item._resultId == null && item.id && this.container != null) {
      item._resultId = this.generateResultId(this.container, item);
    }

    return $.extend({}, defaults, item);
  };

  SelectAdapter.prototype.matches = function (params, data) {
    var matcher = this.options.get('matcher');

    return matcher(params, data);
  };

  return SelectAdapter;
});

S2.define('select2/data/array',[
  './select',
  '../utils',
  'jquery'
], function (SelectAdapter, Utils, $) {
  function ArrayAdapter ($element, options) {
    this._dataToConvert = options.get('data') || [];

    ArrayAdapter.__super__.constructor.call(this, $element, options);
  }

  Utils.Extend(ArrayAdapter, SelectAdapter);

  ArrayAdapter.prototype.bind = function (container, $container) {
    ArrayAdapter.__super__.bind.call(this, container, $container);

    this.addOptions(this.convertToOptions(this._dataToConvert));
  };

  ArrayAdapter.prototype.select = function (data) {
    var $option = this.$element.find('option').filter(function (i, elm) {
      return elm.value == data.id.toString();
    });

    if ($option.length === 0) {
      $option = this.option(data);

      this.addOptions($option);
    }

    ArrayAdapter.__super__.select.call(this, data);
  };

  ArrayAdapter.prototype.convertToOptions = function (data) {
    var self = this;

    var $existing = this.$element.find('option');
    var existingIds = $existing.map(function () {
      return self.item($(this)).id;
    }).get();

    var $options = [];

    // Filter out all items except for the one passed in the argument
    function onlyItem (item) {
      return function () {
        return $(this).val() == item.id;
      };
    }

    for (var d = 0; d < data.length; d++) {
      var item = this._normalizeItem(data[d]);

      // Skip items which were pre-loaded, only merge the data
      if ($.inArray(item.id, existingIds) >= 0) {
        var $existingOption = $existing.filter(onlyItem(item));

        var existingData = this.item($existingOption);
        var newData = $.extend(true, {}, item, existingData);

        var $newOption = this.option(newData);

        $existingOption.replaceWith($newOption);

        continue;
      }

      var $option = this.option(item);

      if (item.children) {
        var $children = this.convertToOptions(item.children);

        Utils.appendMany($option, $children);
      }

      $options.push($option);
    }

    return $options;
  };

  return ArrayAdapter;
});

S2.define('select2/data/ajax',[
  './array',
  '../utils',
  'jquery'
], function (ArrayAdapter, Utils, $) {
  function AjaxAdapter ($element, options) {
    this.ajaxOptions = this._applyDefaults(options.get('ajax'));

    if (this.ajaxOptions.processResults != null) {
      this.processResults = this.ajaxOptions.processResults;
    }

    AjaxAdapter.__super__.constructor.call(this, $element, options);
  }

  Utils.Extend(AjaxAdapter, ArrayAdapter);

  AjaxAdapter.prototype._applyDefaults = function (options) {
    var defaults = {
      data: function (params) {
        return $.extend({}, params, {
          q: params.term
        });
      },
      transport: function (params, success, failure) {
        var $request = $.ajax(params);

        $request.then(success);
        $request.fail(failure);

        return $request;
      }
    };

    return $.extend({}, defaults, options, true);
  };

  AjaxAdapter.prototype.processResults = function (results) {
    return results;
  };

  AjaxAdapter.prototype.query = function (params, callback) {
    var matches = [];
    var self = this;

    if (this._request != null) {
      // JSONP requests cannot always be aborted
      if ($.isFunction(this._request.abort)) {
        this._request.abort();
      }

      this._request = null;
    }

    var options = $.extend({
      type: 'GET'
    }, this.ajaxOptions);

    if (typeof options.url === 'function') {
      options.url = options.url.call(this.$element, params);
    }

    if (typeof options.data === 'function') {
      options.data = options.data.call(this.$element, params);
    }

    function request () {
      var $request = options.transport(options, function (data) {
        var results = self.processResults(data, params);

        if (self.options.get('debug') && window.console && console.error) {
          // Check to make sure that the response included a `results` key.
          if (!results || !results.results || !$.isArray(results.results)) {
            console.error(
              'Select2: The AJAX results did not return an array in the ' +
              '`results` key of the response.'
            );
          }
        }

        callback(results);
      }, function () {
        // Attempt to detect if a request was aborted
        // Only works if the transport exposes a status property
        if ('status' in $request &&
            ($request.status === 0 || $request.status === '0')) {
          return;
        }

        self.trigger('results:message', {
          message: 'errorLoading'
        });
      });

      self._request = $request;
    }

    if (this.ajaxOptions.delay && params.term != null) {
      if (this._queryTimeout) {
        window.clearTimeout(this._queryTimeout);
      }

      this._queryTimeout = window.setTimeout(request, this.ajaxOptions.delay);
    } else {
      request();
    }
  };

  return AjaxAdapter;
});

S2.define('select2/data/tags',[
  'jquery'
], function ($) {
  function Tags (decorated, $element, options) {
    var tags = options.get('tags');

    var createTag = options.get('createTag');

    if (createTag !== undefined) {
      this.createTag = createTag;
    }

    var insertTag = options.get('insertTag');

    if (insertTag !== undefined) {
        this.insertTag = insertTag;
    }

    decorated.call(this, $element, options);

    if ($.isArray(tags)) {
      for (var t = 0; t < tags.length; t++) {
        var tag = tags[t];
        var item = this._normalizeItem(tag);

        var $option = this.option(item);

        this.$element.append($option);
      }
    }
  }

  Tags.prototype.query = function (decorated, params, callback) {
    var self = this;

    this._removeOldTags();

    if (params.term == null || params.page != null) {
      decorated.call(this, params, callback);
      return;
    }

    function wrapper (obj, child) {
      var data = obj.results;

      for (var i = 0; i < data.length; i++) {
        var option = data[i];

        var checkChildren = (
          option.children != null &&
          !wrapper({
            results: option.children
          }, true)
        );

        var optionText = (option.text || '').toUpperCase();
        var paramsTerm = (params.term || '').toUpperCase();

        var checkText = optionText === paramsTerm;

        if (checkText || checkChildren) {
          if (child) {
            return false;
          }

          obj.data = data;
          callback(obj);

          return;
        }
      }

      if (child) {
        return true;
      }

      var tag = self.createTag(params);

      if (tag != null) {
        var $option = self.option(tag);
        $option.attr('data-select2-tag', true);

        self.addOptions([$option]);

        self.insertTag(data, tag);
      }

      obj.results = data;

      callback(obj);
    }

    decorated.call(this, params, wrapper);
  };

  Tags.prototype.createTag = function (decorated, params) {
    var term = $.trim(params.term);

    if (term === '') {
      return null;
    }

    return {
      id: term,
      text: term
    };
  };

  Tags.prototype.insertTag = function (_, data, tag) {
    data.unshift(tag);
  };

  Tags.prototype._removeOldTags = function (_) {
    var $options = this.$element.find('option[data-select2-tag]');

    $options.each(function () {
      if (this.selected) {
        return;
      }

      $(this).remove();
    });
  };

  return Tags;
});

S2.define('select2/data/tokenizer',[
  'jquery'
], function ($) {
  function Tokenizer (decorated, $element, options) {
    var tokenizer = options.get('tokenizer');

    if (tokenizer !== undefined) {
      this.tokenizer = tokenizer;
    }

    decorated.call(this, $element, options);
  }

  Tokenizer.prototype.bind = function (decorated, container, $container) {
    decorated.call(this, container, $container);

    this.$search =  container.dropdown.$search || container.selection.$search ||
      $container.find('.select2-search__field');
  };

  Tokenizer.prototype.query = function (decorated, params, callback) {
    var self = this;

    function createAndSelect (data) {
      // Normalize the data object so we can use it for checks
      var item = self._normalizeItem(data);

      // Check if the data object already exists as a tag
      // Select it if it doesn't
      var $existingOptions = self.$element.find('option').filter(function () {
        return $(this).val() === item.id;
      });

      // If an existing option wasn't found for it, create the option
      if (!$existingOptions.length) {
        var $option = self.option(item);
        $option.attr('data-select2-tag', true);

        self._removeOldTags();
        self.addOptions([$option]);
      }

      // Select the item, now that we know there is an option for it
      select(item);
    }

    function select (data) {
      self.trigger('select', {
        data: data
      });
    }

    params.term = params.term || '';

    var tokenData = this.tokenizer(params, this.options, createAndSelect);

    if (tokenData.term !== params.term) {
      // Replace the search term if we have the search box
      if (this.$search.length) {
        this.$search.val(tokenData.term);
        this.$search.trigger('focus');
      }

      params.term = tokenData.term;
    }

    decorated.call(this, params, callback);
  };

  Tokenizer.prototype.tokenizer = function (_, params, options, callback) {
    var separators = options.get('tokenSeparators') || [];
    var term = params.term;
    var i = 0;

    var createTag = this.createTag || function (params) {
      return {
        id: params.term,
        text: params.term
      };
    };

    while (i < term.length) {
      var termChar = term[i];

      if ($.inArray(termChar, separators) === -1) {
        i++;

        continue;
      }

      var part = term.substr(0, i);
      var partParams = $.extend({}, params, {
        term: part
      });

      var data = createTag(partParams);

      if (data == null) {
        i++;
        continue;
      }

      callback(data);

      // Reset the term to not include the tokenized portion
      term = term.substr(i + 1) || '';
      i = 0;
    }

    return {
      term: term
    };
  };

  return Tokenizer;
});

S2.define('select2/data/minimumInputLength',[

], function () {
  function MinimumInputLength (decorated, $e, options) {
    this.minimumInputLength = options.get('minimumInputLength');

    decorated.call(this, $e, options);
  }

  MinimumInputLength.prototype.query = function (decorated, params, callback) {
    params.term = params.term || '';

    if (params.term.length < this.minimumInputLength) {
      this.trigger('results:message', {
        message: 'inputTooShort',
        args: {
          minimum: this.minimumInputLength,
          input: params.term,
          params: params
        }
      });

      return;
    }

    decorated.call(this, params, callback);
  };

  return MinimumInputLength;
});

S2.define('select2/data/maximumInputLength',[

], function () {
  function MaximumInputLength (decorated, $e, options) {
    this.maximumInputLength = options.get('maximumInputLength');

    decorated.call(this, $e, options);
  }

  MaximumInputLength.prototype.query = function (decorated, params, callback) {
    params.term = params.term || '';

    if (this.maximumInputLength > 0 &&
        params.term.length > this.maximumInputLength) {
      this.trigger('results:message', {
        message: 'inputTooLong',
        args: {
          maximum: this.maximumInputLength,
          input: params.term,
          params: params
        }
      });

      return;
    }

    decorated.call(this, params, callback);
  };

  return MaximumInputLength;
});

S2.define('select2/data/maximumSelectionLength',[

], function (){
  function MaximumSelectionLength (decorated, $e, options) {
    this.maximumSelectionLength = options.get('maximumSelectionLength');

    decorated.call(this, $e, options);
  }

  MaximumSelectionLength.prototype.bind =
    function (decorated, container, $container) {
      var self = this;

      decorated.call(this, container, $container);

      container.on('select', function () {
        self._checkIfMaximumSelected();
      });
  };

  MaximumSelectionLength.prototype.query =
    function (decorated, params, callback) {
      var self = this;

      this._checkIfMaximumSelected(function () {
        decorated.call(self, params, callback);
      });
  };

  MaximumSelectionLength.prototype._checkIfMaximumSelected =
    function (_, successCallback) {
      var self = this;

      this.current(function (currentData) {
        var count = currentData != null ? currentData.length : 0;
        if (self.maximumSelectionLength > 0 &&
          count >= self.maximumSelectionLength) {
          self.trigger('results:message', {
            message: 'maximumSelected',
            args: {
              maximum: self.maximumSelectionLength
            }
          });
          return;
        }

        if (successCallback) {
          successCallback();
        }
      });
  };

  return MaximumSelectionLength;
});

S2.define('select2/dropdown',[
  'jquery',
  './utils'
], function ($, Utils) {
  function Dropdown ($element, options) {
    this.$element = $element;
    this.options = options;

    Dropdown.__super__.constructor.call(this);
  }

  Utils.Extend(Dropdown, Utils.Observable);

  Dropdown.prototype.render = function () {
    var $dropdown = $(
      '<span class="select2-dropdown">' +
        '<span class="select2-results"></span>' +
      '</span>'
    );

    $dropdown.attr('dir', this.options.get('dir'));

    this.$dropdown = $dropdown;

    return $dropdown;
  };

  Dropdown.prototype.bind = function () {
    // Should be implemented in subclasses
  };

  Dropdown.prototype.position = function ($dropdown, $container) {
    // Should be implemented in subclasses
  };

  Dropdown.prototype.destroy = function () {
    // Remove the dropdown from the DOM
    this.$dropdown.remove();
  };

  return Dropdown;
});

S2.define('select2/dropdown/search',[
  'jquery',
  '../utils'
], function ($, Utils) {
  function Search () { }

  Search.prototype.render = function (decorated) {
    var $rendered = decorated.call(this);

    var $search = $(
      '<span class="select2-search select2-search--dropdown">' +
        '<label for="filterLabel" class="vh">Zoek specifieke filter</label>'+
        '<input id="filterLabel" class="select2-search__field" type="search" tabindex="-1"' +
        ' autocomplete="off" autocorrect="off" autocapitalize="none"' +
        ' spellcheck="false" role="searchbox" aria-autocomplete="list" />' +
      '</span>'
    );

    this.$searchContainer = $search;
    this.$search = $search.find('input');

    $rendered.prepend($search);

    return $rendered;
  };

  Search.prototype.bind = function (decorated, container, $container) {
    var self = this;

    var resultsId = container.id + '-results';

    decorated.call(this, container, $container);

    this.$search.on('keydown', function (evt) {
      self.trigger('keypress', evt);

      self._keyUpPrevented = evt.isDefaultPrevented();
    });

    // Workaround for browsers which do not support the `input` event
    // This will prevent double-triggering of events for browsers which support
    // both the `keyup` and `input` events.
    this.$search.on('input', function (evt) {
      // Unbind the duplicated `keyup` event
      $(this).off('keyup');
    });

    this.$search.on('keyup input', function (evt) {
      self.handleSearch(evt);
    });

    container.on('open', function () {
      self.$search.attr('tabindex', 0);
      self.$search.attr('aria-controls', resultsId);

      self.$search.trigger('focus');

      window.setTimeout(function () {
        self.$search.trigger('focus');
      }, 0);
    });

    container.on('close', function () {
      self.$search.attr('tabindex', -1);
      self.$search.removeAttr('aria-controls');
      self.$search.removeAttr('aria-activedescendant');

      self.$search.val('');
      self.$search.trigger('blur');
    });

    container.on('focus', function () {
      if (!container.isOpen()) {
        self.$search.trigger('focus');
      }
    });

    container.on('results:all', function (params) {
      if (params.query.term == null || params.query.term === '') {
        var showSearch = self.showSearch(params);

        if (showSearch) {
          self.$searchContainer.removeClass('select2-search--hide');
        } else {
          self.$searchContainer.addClass('select2-search--hide');
        }
      }
    });

    container.on('results:focus', function (params) {
      if (params.data._resultId) {
        self.$search.attr('aria-activedescendant', params.data._resultId);
      } else {
        self.$search.removeAttr('aria-activedescendant');
      }
    });
  };

  Search.prototype.handleSearch = function (evt) {
    if (!this._keyUpPrevented) {
      var input = this.$search.val();

      this.trigger('query', {
        term: input
      });
    }

    this._keyUpPrevented = false;
  };

  Search.prototype.showSearch = function (_, params) {
    return true;
  };

  return Search;
});

S2.define('select2/dropdown/hidePlaceholder',[

], function () {
  function HidePlaceholder (decorated, $element, options, dataAdapter) {
    this.placeholder = this.normalizePlaceholder(options.get('placeholder'));

    decorated.call(this, $element, options, dataAdapter);
  }

  HidePlaceholder.prototype.append = function (decorated, data) {
    data.results = this.removePlaceholder(data.results);

    decorated.call(this, data);
  };

  HidePlaceholder.prototype.normalizePlaceholder = function (_, placeholder) {
    if (typeof placeholder === 'string') {
      placeholder = {
        id: '',
        text: placeholder
      };
    }

    return placeholder;
  };

  HidePlaceholder.prototype.removePlaceholder = function (_, data) {
    var modifiedData = data.slice(0);

    for (var d = data.length - 1; d >= 0; d--) {
      var item = data[d];

      if (this.placeholder.id === item.id) {
        modifiedData.splice(d, 1);
      }
    }

    return modifiedData;
  };

  return HidePlaceholder;
});

S2.define('select2/dropdown/infiniteScroll',[
  'jquery'
], function ($) {
  function InfiniteScroll (decorated, $element, options, dataAdapter) {
    this.lastParams = {};

    decorated.call(this, $element, options, dataAdapter);

    this.$loadingMore = this.createLoadingMore();
    this.loading = false;
  }

  InfiniteScroll.prototype.append = function (decorated, data) {
    this.$loadingMore.remove();
    this.loading = false;

    decorated.call(this, data);

    if (this.showLoadingMore(data)) {
      this.$results.append(this.$loadingMore);
      this.loadMoreIfNeeded();
    }
  };

  InfiniteScroll.prototype.bind = function (decorated, container, $container) {
    var self = this;

    decorated.call(this, container, $container);

    container.on('query', function (params) {
      self.lastParams = params;
      self.loading = true;
    });

    container.on('query:append', function (params) {
      self.lastParams = params;
      self.loading = true;
    });

    this.$results.on('scroll', this.loadMoreIfNeeded.bind(this));
  };

  InfiniteScroll.prototype.loadMoreIfNeeded = function () {
    var isLoadMoreVisible = $.contains(
      document.documentElement,
      this.$loadingMore[0]
    );

    if (this.loading || !isLoadMoreVisible) {
      return;
    }

    var currentOffset = this.$results.offset().top +
      this.$results.outerHeight(false);
    var loadingMoreOffset = this.$loadingMore.offset().top +
      this.$loadingMore.outerHeight(false);

    if (currentOffset + 50 >= loadingMoreOffset) {
      this.loadMore();
    }
  };

  InfiniteScroll.prototype.loadMore = function () {
    this.loading = true;

    var params = $.extend({}, {page: 1}, this.lastParams);

    params.page++;

    this.trigger('query:append', params);
  };

  InfiniteScroll.prototype.showLoadingMore = function (_, data) {
    return data.pagination && data.pagination.more;
  };

  InfiniteScroll.prototype.createLoadingMore = function () {
    var $option = $(
      '<li ' +
      'class="select2-results__option select2-results__option--load-more"' +
      'role="option" aria-disabled="true"></li>'
    );

    var message = this.options.get('translations').get('loadingMore');

    $option.html(message(this.lastParams));

    return $option;
  };

  return InfiniteScroll;
});

S2.define('select2/dropdown/attachBody',[
  'jquery',
  '../utils'
], function ($, Utils) {
  function AttachBody (decorated, $element, options) {
    this.$dropdownParent = $(options.get('dropdownParent') || document.body);

    decorated.call(this, $element, options);
  }

  AttachBody.prototype.bind = function (decorated, container, $container) {
    var self = this;

    decorated.call(this, container, $container);

    container.on('open', function () {
      self._showDropdown();
      self._attachPositioningHandler(container);

      // Must bind after the results handlers to ensure correct sizing
      self._bindContainerResultHandlers(container);
    });

    container.on('close', function () {
      self._hideDropdown();
      self._detachPositioningHandler(container);
    });

    this.$dropdownContainer.on('mousedown', function (evt) {
      evt.stopPropagation();
    });
  };

  AttachBody.prototype.destroy = function (decorated) {
    decorated.call(this);

    this.$dropdownContainer.remove();
  };

  AttachBody.prototype.position = function (decorated, $dropdown, $container) {
    // Clone all of the container classes
    $dropdown.attr('class', $container.attr('class'));

    $dropdown.removeClass('select2');
    $dropdown.addClass('select2-container--open');

    $dropdown.css({
      position: 'absolute',
      top: -999999
    });

    this.$container = $container;
  };

  AttachBody.prototype.render = function (decorated) {
    var $container = $('<span></span>');

    var $dropdown = decorated.call(this);
    $container.append($dropdown);

    this.$dropdownContainer = $container;

    return $container;
  };

  AttachBody.prototype._hideDropdown = function (decorated) {
    this.$dropdownContainer.detach();
  };

  AttachBody.prototype._bindContainerResultHandlers =
      function (decorated, container) {

    // These should only be bound once
    if (this._containerResultsHandlersBound) {
      return;
    }

    var self = this;

    container.on('results:all', function () {
      self._positionDropdown();
      self._resizeDropdown();
    });

    container.on('results:append', function () {
      self._positionDropdown();
      self._resizeDropdown();
    });

    container.on('results:message', function () {
      self._positionDropdown();
      self._resizeDropdown();
    });

    container.on('select', function () {
      self._positionDropdown();
      self._resizeDropdown();
    });

    container.on('unselect', function () {
      self._positionDropdown();
      self._resizeDropdown();
    });

    this._containerResultsHandlersBound = true;
  };

  AttachBody.prototype._attachPositioningHandler =
      function (decorated, container) {
    var self = this;

    var scrollEvent = 'scroll.select2.' + container.id;
    var resizeEvent = 'resize.select2.' + container.id;
    var orientationEvent = 'orientationchange.select2.' + container.id;

    var $watchers = this.$container.parents().filter(Utils.hasScroll);
    $watchers.each(function () {
      Utils.StoreData(this, 'select2-scroll-position', {
        x: $(this).scrollLeft(),
        y: $(this).scrollTop()
      });
    });

    $watchers.on(scrollEvent, function (ev) {
      var position = Utils.GetData(this, 'select2-scroll-position');
      $(this).scrollTop(position.y);
    });

    $(window).on(scrollEvent + ' ' + resizeEvent + ' ' + orientationEvent,
      function (e) {
      self._positionDropdown();
      self._resizeDropdown();
    });
  };

  AttachBody.prototype._detachPositioningHandler =
      function (decorated, container) {
    var scrollEvent = 'scroll.select2.' + container.id;
    var resizeEvent = 'resize.select2.' + container.id;
    var orientationEvent = 'orientationchange.select2.' + container.id;

    var $watchers = this.$container.parents().filter(Utils.hasScroll);
    $watchers.off(scrollEvent);

    $(window).off(scrollEvent + ' ' + resizeEvent + ' ' + orientationEvent);
  };

  AttachBody.prototype._positionDropdown = function () {
    var $window = $(window);

    var isCurrentlyAbove = this.$dropdown.hasClass('select2-dropdown--above');
    var isCurrentlyBelow = this.$dropdown.hasClass('select2-dropdown--below');

    var newDirection = null;

    var offset = this.$container.offset();

    offset.bottom = offset.top + this.$container.outerHeight(false);

    var container = {
      height: this.$container.outerHeight(false)
    };

    container.top = offset.top;
    container.bottom = offset.top + container.height;

    var dropdown = {
      height: this.$dropdown.outerHeight(false)
    };

    var viewport = {
      top: $window.scrollTop(),
      bottom: $window.scrollTop() + $window.height()
    };

    var enoughRoomAbove = viewport.top < (offset.top - dropdown.height);
    var enoughRoomBelow = viewport.bottom > (offset.bottom + dropdown.height);

    var css = {
      left: offset.left,
      top: container.bottom
    };

    // Determine what the parent element is to use for calculating the offset
    var $offsetParent = this.$dropdownParent;

    // For statically positioned elements, we need to get the element
    // that is determining the offset
    if ($offsetParent.css('position') === 'static') {
      $offsetParent = $offsetParent.offsetParent();
    }

    var parentOffset = {
      top: 0,
      left: 0
    };

    if (
      $.contains(document.body, $offsetParent[0]) ||
      $offsetParent[0].isConnected
      ) {
      parentOffset = $offsetParent.offset();
    }

    css.top -= parentOffset.top;
    css.left -= parentOffset.left;

    if (!isCurrentlyAbove && !isCurrentlyBelow) {
      newDirection = 'below';
    }

    if (!enoughRoomBelow && enoughRoomAbove && !isCurrentlyAbove) {
      newDirection = 'above';
    } else if (!enoughRoomAbove && enoughRoomBelow && isCurrentlyAbove) {
      newDirection = 'below';
    }

    if (newDirection == 'above' ||
      (isCurrentlyAbove && newDirection !== 'below')) {
      css.top = container.top - parentOffset.top - dropdown.height;
    }

    if (newDirection != null) {
      this.$dropdown
        .removeClass('select2-dropdown--below select2-dropdown--above')
        .addClass('select2-dropdown--' + newDirection);
      this.$container
        .removeClass('select2-container--below select2-container--above')
        .addClass('select2-container--' + newDirection);
    }

    this.$dropdownContainer.css(css);
  };

  AttachBody.prototype._resizeDropdown = function () {
    var css = {
      width: this.$container.outerWidth(false) + 'px'
    };

    if (this.options.get('dropdownAutoWidth')) {
      css.minWidth = css.width;
      css.position = 'relative';
      css.width = 'auto';
    }

    this.$dropdown.css(css);
  };

  AttachBody.prototype._showDropdown = function (decorated) {
    this.$dropdownContainer.appendTo(this.$dropdownParent);

    this._positionDropdown();
    this._resizeDropdown();
  };

  return AttachBody;
});

S2.define('select2/dropdown/minimumResultsForSearch',[

], function () {
  function countResults (data) {
    var count = 0;

    for (var d = 0; d < data.length; d++) {
      var item = data[d];

      if (item.children) {
        count += countResults(item.children);
      } else {
        count++;
      }
    }

    return count;
  }

  function MinimumResultsForSearch (decorated, $element, options, dataAdapter) {
    this.minimumResultsForSearch = options.get('minimumResultsForSearch');

    if (this.minimumResultsForSearch < 0) {
      this.minimumResultsForSearch = Infinity;
    }

    decorated.call(this, $element, options, dataAdapter);
  }

  MinimumResultsForSearch.prototype.showSearch = function (decorated, params) {
    if (countResults(params.data.results) < this.minimumResultsForSearch) {
      return false;
    }

    return decorated.call(this, params);
  };

  return MinimumResultsForSearch;
});

S2.define('select2/dropdown/selectOnClose',[
  '../utils'
], function (Utils) {
  function SelectOnClose () { }

  SelectOnClose.prototype.bind = function (decorated, container, $container) {
    var self = this;

    decorated.call(this, container, $container);

    container.on('close', function (params) {
      self._handleSelectOnClose(params);
    });
  };

  SelectOnClose.prototype._handleSelectOnClose = function (_, params) {
    if (params && params.originalSelect2Event != null) {
      var event = params.originalSelect2Event;

      // Don't select an item if the close event was triggered from a select or
      // unselect event
      if (event._type === 'select' || event._type === 'unselect') {
        return;
      }
    }

    var $highlightedResults = this.getHighlightedResults();

    // Only select highlighted results
    if ($highlightedResults.length < 1) {
      return;
    }

    var data = Utils.GetData($highlightedResults[0], 'data');

    // Don't re-select already selected resulte
    if (
      (data.element != null && data.element.selected) ||
      (data.element == null && data.selected)
    ) {
      return;
    }

    this.trigger('select', {
        data: data
    });
  };

  return SelectOnClose;
});

S2.define('select2/dropdown/closeOnSelect',[

], function () {
  function CloseOnSelect () { }

  CloseOnSelect.prototype.bind = function (decorated, container, $container) {
    var self = this;

    decorated.call(this, container, $container);

    container.on('select', function (evt) {
      self._selectTriggered(evt);
    });

    container.on('unselect', function (evt) {
      self._selectTriggered(evt);
    });
  };

  CloseOnSelect.prototype._selectTriggered = function (_, evt) {
    var originalEvent = evt.originalEvent;

    // Don't close if the control key is being held
    if (originalEvent && (originalEvent.ctrlKey || originalEvent.metaKey)) {
      return;
    }

    this.trigger('close', {
      originalEvent: originalEvent,
      originalSelect2Event: evt
    });
  };

  return CloseOnSelect;
});

S2.define('select2/i18n/en',[],function () {
  // English
  return {
    errorLoading: function () {
      return 'The results could not be loaded.';
    },
    inputTooLong: function (args) {
      var overChars = args.input.length - args.maximum;

      var message = 'Please delete ' + overChars + ' character';

      if (overChars != 1) {
        message += 's';
      }

      return message;
    },
    inputTooShort: function (args) {
      var remainingChars = args.minimum - args.input.length;

      var message = 'Please enter ' + remainingChars + ' or more characters';

      return message;
    },
    loadingMore: function () {
      return 'Loading more results…';
    },
    maximumSelected: function (args) {
      var message = 'You can only select ' + args.maximum + ' item';

      if (args.maximum != 1) {
        message += 's';
      }

      return message;
    },
    noResults: function () {
      return 'No results found';
    },
    searching: function () {
      return 'Searching…';
    },
    removeAllItems: function () {
      return 'Remove all items';
    }
  };
});

S2.define('select2/defaults',[
  'jquery',
  'require',

  './results',

  './selection/single',
  './selection/multiple',
  './selection/placeholder',
  './selection/allowClear',
  './selection/search',
  './selection/eventRelay',

  './utils',
  './translation',
  './diacritics',

  './data/select',
  './data/array',
  './data/ajax',
  './data/tags',
  './data/tokenizer',
  './data/minimumInputLength',
  './data/maximumInputLength',
  './data/maximumSelectionLength',

  './dropdown',
  './dropdown/search',
  './dropdown/hidePlaceholder',
  './dropdown/infiniteScroll',
  './dropdown/attachBody',
  './dropdown/minimumResultsForSearch',
  './dropdown/selectOnClose',
  './dropdown/closeOnSelect',

  './i18n/en'
], function ($, require,

             ResultsList,

             SingleSelection, MultipleSelection, Placeholder, AllowClear,
             SelectionSearch, EventRelay,

             Utils, Translation, DIACRITICS,

             SelectData, ArrayData, AjaxData, Tags, Tokenizer,
             MinimumInputLength, MaximumInputLength, MaximumSelectionLength,

             Dropdown, DropdownSearch, HidePlaceholder, InfiniteScroll,
             AttachBody, MinimumResultsForSearch, SelectOnClose, CloseOnSelect,

             EnglishTranslation) {
  function Defaults () {
    this.reset();
  }

  Defaults.prototype.apply = function (options) {
    options = $.extend(true, {}, this.defaults, options);

    if (options.dataAdapter == null) {
      if (options.ajax != null) {
        options.dataAdapter = AjaxData;
      } else if (options.data != null) {
        options.dataAdapter = ArrayData;
      } else {
        options.dataAdapter = SelectData;
      }

      if (options.minimumInputLength > 0) {
        options.dataAdapter = Utils.Decorate(
          options.dataAdapter,
          MinimumInputLength
        );
      }

      if (options.maximumInputLength > 0) {
        options.dataAdapter = Utils.Decorate(
          options.dataAdapter,
          MaximumInputLength
        );
      }

      if (options.maximumSelectionLength > 0) {
        options.dataAdapter = Utils.Decorate(
          options.dataAdapter,
          MaximumSelectionLength
        );
      }

      if (options.tags) {
        options.dataAdapter = Utils.Decorate(options.dataAdapter, Tags);
      }

      if (options.tokenSeparators != null || options.tokenizer != null) {
        options.dataAdapter = Utils.Decorate(
          options.dataAdapter,
          Tokenizer
        );
      }

      if (options.query != null) {
        var Query = require(options.amdBase + 'compat/query');

        options.dataAdapter = Utils.Decorate(
          options.dataAdapter,
          Query
        );
      }

      if (options.initSelection != null) {
        var InitSelection = require(options.amdBase + 'compat/initSelection');

        options.dataAdapter = Utils.Decorate(
          options.dataAdapter,
          InitSelection
        );
      }
    }

    if (options.resultsAdapter == null) {
      options.resultsAdapter = ResultsList;

      if (options.ajax != null) {
        options.resultsAdapter = Utils.Decorate(
          options.resultsAdapter,
          InfiniteScroll
        );
      }

      if (options.placeholder != null) {
        options.resultsAdapter = Utils.Decorate(
          options.resultsAdapter,
          HidePlaceholder
        );
      }

      if (options.selectOnClose) {
        options.resultsAdapter = Utils.Decorate(
          options.resultsAdapter,
          SelectOnClose
        );
      }
    }

    if (options.dropdownAdapter == null) {
      if (options.multiple) {
        options.dropdownAdapter = Dropdown;
      } else {
        var SearchableDropdown = Utils.Decorate(Dropdown, DropdownSearch);

        options.dropdownAdapter = SearchableDropdown;
      }

      if (options.minimumResultsForSearch !== 0) {
        options.dropdownAdapter = Utils.Decorate(
          options.dropdownAdapter,
          MinimumResultsForSearch
        );
      }

      if (options.closeOnSelect) {
        options.dropdownAdapter = Utils.Decorate(
          options.dropdownAdapter,
          CloseOnSelect
        );
      }

      if (
        options.dropdownCssClass != null ||
        options.dropdownCss != null ||
        options.adaptDropdownCssClass != null
      ) {
        var DropdownCSS = require(options.amdBase + 'compat/dropdownCss');

        options.dropdownAdapter = Utils.Decorate(
          options.dropdownAdapter,
          DropdownCSS
        );
      }

      options.dropdownAdapter = Utils.Decorate(
        options.dropdownAdapter,
        AttachBody
      );
    }

    if (options.selectionAdapter == null) {
      if (options.multiple) {
        options.selectionAdapter = MultipleSelection;
      } else {
        options.selectionAdapter = SingleSelection;
      }

      // Add the placeholder mixin if a placeholder was specified
      if (options.placeholder != null) {
        options.selectionAdapter = Utils.Decorate(
          options.selectionAdapter,
          Placeholder
        );
      }

      if (options.allowClear) {
        options.selectionAdapter = Utils.Decorate(
          options.selectionAdapter,
          AllowClear
        );
      }

      if (options.multiple) {
        options.selectionAdapter = Utils.Decorate(
          options.selectionAdapter,
          SelectionSearch
        );
      }

      if (
        options.containerCssClass != null ||
        options.containerCss != null ||
        options.adaptContainerCssClass != null
      ) {
        var ContainerCSS = require(options.amdBase + 'compat/containerCss');

        options.selectionAdapter = Utils.Decorate(
          options.selectionAdapter,
          ContainerCSS
        );
      }

      options.selectionAdapter = Utils.Decorate(
        options.selectionAdapter,
        EventRelay
      );
    }

    // If the defaults were not previously applied from an element, it is
    // possible for the language option to have not been resolved
    options.language = this._resolveLanguage(options.language);

    // Always fall back to English since it will always be complete
    options.language.push('en');

    var uniqueLanguages = [];

    for (var l = 0; l < options.language.length; l++) {
      var language = options.language[l];

      if (uniqueLanguages.indexOf(language) === -1) {
        uniqueLanguages.push(language);
      }
    }

    options.language = uniqueLanguages;

    options.translations = this._processTranslations(
      options.language,
      options.debug
    );

    return options;
  };

  Defaults.prototype.reset = function () {
    function stripDiacritics (text) {
      // Used 'uni range + named function' from http://jsperf.com/diacritics/18
      function match(a) {
        return DIACRITICS[a] || a;
      }

      return text.replace(/[^\u0000-\u007E]/g, match);
    }

    function matcher (params, data) {
      // Always return the object if there is nothing to compare
      if ($.trim(params.term) === '') {
        return data;
      }

      // Do a recursive check for options with children
      if (data.children && data.children.length > 0) {
        // Clone the data object if there are children
        // This is required as we modify the object to remove any non-matches
        var match = $.extend(true, {}, data);

        // Check each child of the option
        for (var c = data.children.length - 1; c >= 0; c--) {
          var child = data.children[c];

          var matches = matcher(params, child);

          // If there wasn't a match, remove the object in the array
          if (matches == null) {
            match.children.splice(c, 1);
          }
        }

        // If any children matched, return the new object
        if (match.children.length > 0) {
          return match;
        }

        // If there were no matching children, check just the plain object
        return matcher(params, match);
      }

      var original = stripDiacritics(data.text).toUpperCase();
      var term = stripDiacritics(params.term).toUpperCase();

      // Check if the text contains the term
      if (original.indexOf(term) > -1) {
        return data;
      }

      // If it doesn't contain the term, don't return anything
      return null;
    }

    this.defaults = {
      amdBase: './',
      amdLanguageBase: './i18n/',
      closeOnSelect: true,
      debug: false,
      dropdownAutoWidth: false,
      escapeMarkup: Utils.escapeMarkup,
      language: {},
      matcher: matcher,
      minimumInputLength: 0,
      maximumInputLength: 0,
      maximumSelectionLength: 0,
      minimumResultsForSearch: 0,
      selectOnClose: false,
      scrollAfterSelect: false,
      sorter: function (data) {
        return data;
      },
      templateResult: function (result) {
        return result.text;
      },
      templateSelection: function (selection) {
        return selection.text;
      },
      theme: 'default',
      width: 'resolve'
    };
  };

  Defaults.prototype.applyFromElement = function (options, $element) {
    var optionLanguage = options.language;
    var defaultLanguage = this.defaults.language;
    var elementLanguage = $element.prop('lang');
    var parentLanguage = $element.closest('[lang]').prop('lang');

    var languages = Array.prototype.concat.call(
      this._resolveLanguage(elementLanguage),
      this._resolveLanguage(optionLanguage),
      this._resolveLanguage(defaultLanguage),
      this._resolveLanguage(parentLanguage)
    );

    options.language = languages;

    return options;
  };

  Defaults.prototype._resolveLanguage = function (language) {
    if (!language) {
      return [];
    }

    if ($.isEmptyObject(language)) {
      return [];
    }

    if ($.isPlainObject(language)) {
      return [language];
    }

    var languages;

    if (!$.isArray(language)) {
      languages = [language];
    } else {
      languages = language;
    }

    var resolvedLanguages = [];

    for (var l = 0; l < languages.length; l++) {
      resolvedLanguages.push(languages[l]);

      if (typeof languages[l] === 'string' && languages[l].indexOf('-') > 0) {
        // Extract the region information if it is included
        var languageParts = languages[l].split('-');
        var baseLanguage = languageParts[0];

        resolvedLanguages.push(baseLanguage);
      }
    }

    return resolvedLanguages;
  };

  Defaults.prototype._processTranslations = function (languages, debug) {
    var translations = new Translation();

    for (var l = 0; l < languages.length; l++) {
      var languageData = new Translation();

      var language = languages[l];

      if (typeof language === 'string') {
        try {
          // Try to load it with the original name
          languageData = Translation.loadPath(language);
        } catch (e) {
          try {
            // If we couldn't load it, check if it wasn't the full path
            language = this.defaults.amdLanguageBase + language;
            languageData = Translation.loadPath(language);
          } catch (ex) {
            // The translation could not be loaded at all. Sometimes this is
            // because of a configuration problem, other times this can be
            // because of how Select2 helps load all possible translation files
            if (debug && window.console && console.warn) {
              console.warn(
                'Select2: The language file for "' + language + '" could ' +
                'not be automatically loaded. A fallback will be used instead.'
              );
            }
          }
        }
      } else if ($.isPlainObject(language)) {
        languageData = new Translation(language);
      } else {
        languageData = language;
      }

      translations.extend(languageData);
    }

    return translations;
  };

  Defaults.prototype.set = function (key, value) {
    var camelKey = $.camelCase(key);

    var data = {};
    data[camelKey] = value;

    var convertedData = Utils._convertData(data);

    $.extend(true, this.defaults, convertedData);
  };

  var defaults = new Defaults();

  return defaults;
});

S2.define('select2/options',[
  'require',
  'jquery',
  './defaults',
  './utils'
], function (require, $, Defaults, Utils) {
  function Options (options, $element) {
    this.options = options;

    if ($element != null) {
      this.fromElement($element);
    }

    if ($element != null) {
      this.options = Defaults.applyFromElement(this.options, $element);
    }

    this.options = Defaults.apply(this.options);

    if ($element && $element.is('input')) {
      var InputCompat = require(this.get('amdBase') + 'compat/inputData');

      this.options.dataAdapter = Utils.Decorate(
        this.options.dataAdapter,
        InputCompat
      );
    }
  }

  Options.prototype.fromElement = function ($e) {
    var excludedData = ['select2'];

    if (this.options.multiple == null) {
      this.options.multiple = $e.prop('multiple');
    }

    if (this.options.disabled == null) {
      this.options.disabled = $e.prop('disabled');
    }

    if (this.options.dir == null) {
      if ($e.prop('dir')) {
        this.options.dir = $e.prop('dir');
      } else if ($e.closest('[dir]').prop('dir')) {
        this.options.dir = $e.closest('[dir]').prop('dir');
      } else {
        this.options.dir = 'ltr';
      }
    }

    $e.prop('disabled', this.options.disabled);
    $e.prop('multiple', this.options.multiple);

    if (Utils.GetData($e[0], 'select2Tags')) {
      if (this.options.debug && window.console && console.warn) {
        console.warn(
          'Select2: The `data-select2-tags` attribute has been changed to ' +
          'use the `data-data` and `data-tags="true"` attributes and will be ' +
          'removed in future versions of Select2.'
        );
      }

      Utils.StoreData($e[0], 'data', Utils.GetData($e[0], 'select2Tags'));
      Utils.StoreData($e[0], 'tags', true);
    }

    if (Utils.GetData($e[0], 'ajaxUrl')) {
      if (this.options.debug && window.console && console.warn) {
        console.warn(
          'Select2: The `data-ajax-url` attribute has been changed to ' +
          '`data-ajax--url` and support for the old attribute will be removed' +
          ' in future versions of Select2.'
        );
      }

      $e.attr('ajax--url', Utils.GetData($e[0], 'ajaxUrl'));
      Utils.StoreData($e[0], 'ajax-Url', Utils.GetData($e[0], 'ajaxUrl'));
    }

    var dataset = {};

    function upperCaseLetter(_, letter) {
      return letter.toUpperCase();
    }

    // Pre-load all of the attributes which are prefixed with `data-`
    for (var attr = 0; attr < $e[0].attributes.length; attr++) {
      var attributeName = $e[0].attributes[attr].name;
      var prefix = 'data-';

      if (attributeName.substr(0, prefix.length) == prefix) {
        // Get the contents of the attribute after `data-`
        var dataName = attributeName.substring(prefix.length);

        // Get the data contents from the consistent source
        // This is more than likely the jQuery data helper
        var dataValue = Utils.GetData($e[0], dataName);

        // camelCase the attribute name to match the spec
        var camelDataName = dataName.replace(/-([a-z])/g, upperCaseLetter);

        // Store the data attribute contents into the dataset since
        dataset[camelDataName] = dataValue;
      }
    }

    // Prefer the element's `dataset` attribute if it exists
    // jQuery 1.x does not correctly handle data attributes with multiple dashes
    if ($.fn.jquery && $.fn.jquery.substr(0, 2) == '1.' && $e[0].dataset) {
      dataset = $.extend(true, {}, $e[0].dataset, dataset);
    }

    // Prefer our internal data cache if it exists
    var data = $.extend(true, {}, Utils.GetData($e[0]), dataset);

    data = Utils._convertData(data);

    for (var key in data) {
      if ($.inArray(key, excludedData) > -1) {
        continue;
      }

      if ($.isPlainObject(this.options[key])) {
        $.extend(this.options[key], data[key]);
      } else {
        this.options[key] = data[key];
      }
    }

    return this;
  };

  Options.prototype.get = function (key) {
    return this.options[key];
  };

  Options.prototype.set = function (key, val) {
    this.options[key] = val;
  };

  return Options;
});

S2.define('select2/core',[
  'jquery',
  './options',
  './utils',
  './keys'
], function ($, Options, Utils, KEYS) {
  var Select2 = function ($element, options) {
    if (Utils.GetData($element[0], 'select2') != null) {
      Utils.GetData($element[0], 'select2').destroy();
    }

    this.$element = $element;

    this.id = this._generateId($element);

    options = options || {};

    this.options = new Options(options, $element);

    Select2.__super__.constructor.call(this);

    // Set up the tabindex

    var tabindex = $element.attr('tabindex') || 0;
    Utils.StoreData($element[0], 'old-tabindex', tabindex);
    $element.attr('tabindex', '-1');

    // Set up containers and adapters

    var DataAdapter = this.options.get('dataAdapter');
    this.dataAdapter = new DataAdapter($element, this.options);

    var $container = this.render();

    this._placeContainer($container);

    var SelectionAdapter = this.options.get('selectionAdapter');
    this.selection = new SelectionAdapter($element, this.options);
    this.$selection = this.selection.render();

    this.selection.position(this.$selection, $container);

    var DropdownAdapter = this.options.get('dropdownAdapter');
    this.dropdown = new DropdownAdapter($element, this.options);
    this.$dropdown = this.dropdown.render();

    this.dropdown.position(this.$dropdown, $container);

    var ResultsAdapter = this.options.get('resultsAdapter');
    this.results = new ResultsAdapter($element, this.options, this.dataAdapter);
    this.$results = this.results.render();

    this.results.position(this.$results, this.$dropdown);

    // Bind events

    var self = this;

    // Bind the container to all of the adapters
    this._bindAdapters();

    // Register any DOM event handlers
    this._registerDomEvents();

    // Register any internal event handlers
    this._registerDataEvents();
    this._registerSelectionEvents();
    this._registerDropdownEvents();
    this._registerResultsEvents();
    this._registerEvents();

    // Set the initial state
    this.dataAdapter.current(function (initialData) {
      self.trigger('selection:update', {
        data: initialData
      });
    });

    // Hide the original select
    $element.addClass('select2-hidden-accessible');
    $element.attr('aria-hidden', 'true');

    // Synchronize any monitored attributes
    this._syncAttributes();

    Utils.StoreData($element[0], 'select2', this);

    // Ensure backwards compatibility with $element.data('select2').
    $element.data('select2', this);
  };

  Utils.Extend(Select2, Utils.Observable);

  Select2.prototype._generateId = function ($element) {
    var id = '';

    if ($element.attr('id') != null) {
      id = $element.attr('id');
    } else if ($element.attr('name') != null) {
      id = $element.attr('name') + '-' + Utils.generateChars(2);
    } else {
      id = Utils.generateChars(4);
    }

    id = id.replace(/(:|\.|\[|\]|,)/g, '');
    id = 'select2-' + id;

    return id;
  };

  Select2.prototype._placeContainer = function ($container) {
    $container.insertAfter(this.$element);

    var width = this._resolveWidth(this.$element, this.options.get('width'));

    if (width != null) {
      $container.css('width', width);
    }
  };

  Select2.prototype._resolveWidth = function ($element, method) {
    var WIDTH = /^width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/i;

    if (method == 'resolve') {
      var styleWidth = this._resolveWidth($element, 'style');

      if (styleWidth != null) {
        return styleWidth;
      }

      return this._resolveWidth($element, 'element');
    }

    if (method == 'element') {
      var elementWidth = $element.outerWidth(false);

      if (elementWidth <= 0) {
        return 'auto';
      }

      return elementWidth + 'px';
    }

    if (method == 'style') {
      var style = $element.attr('style');

      if (typeof(style) !== 'string') {
        return null;
      }

      var attrs = style.split(';');

      for (var i = 0, l = attrs.length; i < l; i = i + 1) {
        var attr = attrs[i].replace(/\s/g, '');
        var matches = attr.match(WIDTH);

        if (matches !== null && matches.length >= 1) {
          return matches[1];
        }
      }

      return null;
    }

    if (method == 'computedstyle') {
      var computedStyle = window.getComputedStyle($element[0]);

      return computedStyle.width;
    }

    return method;
  };

  Select2.prototype._bindAdapters = function () {
    this.dataAdapter.bind(this, this.$container);
    this.selection.bind(this, this.$container);

    this.dropdown.bind(this, this.$container);
    this.results.bind(this, this.$container);
  };

  Select2.prototype._registerDomEvents = function () {
    var self = this;

    this.$element.on('change.select2', function () {
      self.dataAdapter.current(function (data) {
        self.trigger('selection:update', {
          data: data
        });
      });
    });

    this.$element.on('focus.select2', function (evt) {
      self.trigger('focus', evt);
    });

    this._syncA = Utils.bind(this._syncAttributes, this);
    this._syncS = Utils.bind(this._syncSubtree, this);

    if (this.$element[0].attachEvent) {
      this.$element[0].attachEvent('onpropertychange', this._syncA);
    }

    var observer = window.MutationObserver ||
      window.WebKitMutationObserver ||
      window.MozMutationObserver
    ;

    if (observer != null) {
      this._observer = new observer(function (mutations) {
        $.each(mutations, self._syncA);
        $.each(mutations, self._syncS);
      });
      this._observer.observe(this.$element[0], {
        attributes: true,
        childList: true,
        subtree: false
      });
    } else if (this.$element[0].addEventListener) {
      this.$element[0].addEventListener(
        'DOMAttrModified',
        self._syncA,
        false
      );
      this.$element[0].addEventListener(
        'DOMNodeInserted',
        self._syncS,
        false
      );
      this.$element[0].addEventListener(
        'DOMNodeRemoved',
        self._syncS,
        false
      );
    }
  };

  Select2.prototype._registerDataEvents = function () {
    var self = this;

    this.dataAdapter.on('*', function (name, params) {
      self.trigger(name, params);
    });
  };

  Select2.prototype._registerSelectionEvents = function () {
    var self = this;
    var nonRelayEvents = ['toggle', 'focus'];

    this.selection.on('toggle', function () {
      self.toggleDropdown();
    });

    this.selection.on('focus', function (params) {
      self.focus(params);
    });

    this.selection.on('*', function (name, params) {
      if ($.inArray(name, nonRelayEvents) !== -1) {
        return;
      }

      self.trigger(name, params);
    });
  };

  Select2.prototype._registerDropdownEvents = function () {
    var self = this;

    this.dropdown.on('*', function (name, params) {
      self.trigger(name, params);
    });
  };

  Select2.prototype._registerResultsEvents = function () {
    var self = this;

    this.results.on('*', function (name, params) {
      self.trigger(name, params);
    });
  };

  Select2.prototype._registerEvents = function () {
    var self = this;

    this.on('open', function () {
      self.$container.addClass('select2-container--open');
    });

    this.on('close', function () {
      self.$container.removeClass('select2-container--open');
    });

    this.on('enable', function () {
      self.$container.removeClass('select2-container--disabled');
    });

    this.on('disable', function () {
      self.$container.addClass('select2-container--disabled');
    });

    this.on('blur', function () {
      self.$container.removeClass('select2-container--focus');
    });

    this.on('query', function (params) {
      if (!self.isOpen()) {
        self.trigger('open', {});
      }

      this.dataAdapter.query(params, function (data) {
        self.trigger('results:all', {
          data: data,
          query: params
        });
      });
    });

    this.on('query:append', function (params) {
      this.dataAdapter.query(params, function (data) {
        self.trigger('results:append', {
          data: data,
          query: params
        });
      });
    });

    this.on('keypress', function (evt) {
      var key = evt.which;

      if (self.isOpen()) {
        if (key === KEYS.ESC || key === KEYS.TAB ||
            (key === KEYS.UP && evt.altKey)) {
          self.close();

          evt.preventDefault();
        } else if (key === KEYS.ENTER) {
          self.trigger('results:select', {});

          evt.preventDefault();
        } else if ((key === KEYS.SPACE && evt.ctrlKey)) {
          self.trigger('results:toggle', {});

          evt.preventDefault();
        } else if (key === KEYS.UP) {
          self.trigger('results:previous', {});

          evt.preventDefault();
        } else if (key === KEYS.DOWN) {
          self.trigger('results:next', {});

          evt.preventDefault();
        }
      } else {
        if (key === KEYS.ENTER || key === KEYS.SPACE ||
            (key === KEYS.DOWN && evt.altKey)) {
          self.open();

          evt.preventDefault();
        }
      }
    });
  };

  Select2.prototype._syncAttributes = function () {
    this.options.set('disabled', this.$element.prop('disabled'));

    if (this.options.get('disabled')) {
      if (this.isOpen()) {
        this.close();
      }

      this.trigger('disable', {});
    } else {
      this.trigger('enable', {});
    }
  };

  Select2.prototype._syncSubtree = function (evt, mutations) {
    var changed = false;
    var self = this;

    // Ignore any mutation events raised for elements that aren't options or
    // optgroups. This handles the case when the select element is destroyed
    if (
      evt && evt.target && (
        evt.target.nodeName !== 'OPTION' && evt.target.nodeName !== 'OPTGROUP'
      )
    ) {
      return;
    }

    if (!mutations) {
      // If mutation events aren't supported, then we can only assume that the
      // change affected the selections
      changed = true;
    } else if (mutations.addedNodes && mutations.addedNodes.length > 0) {
      for (var n = 0; n < mutations.addedNodes.length; n++) {
        var node = mutations.addedNodes[n];

        if (node.selected) {
          changed = true;
        }
      }
    } else if (mutations.removedNodes && mutations.removedNodes.length > 0) {
      changed = true;
    }

    // Only re-pull the data if we think there is a change
    if (changed) {
      this.dataAdapter.current(function (currentData) {
        self.trigger('selection:update', {
          data: currentData
        });
      });
    }
  };

  /**
   * Override the trigger method to automatically trigger pre-events when
   * there are events that can be prevented.
   */
  Select2.prototype.trigger = function (name, args) {
    var actualTrigger = Select2.__super__.trigger;
    var preTriggerMap = {
      'open': 'opening',
      'close': 'closing',
      'select': 'selecting',
      'unselect': 'unselecting',
      'clear': 'clearing'
    };

    if (args === undefined) {
      args = {};
    }

    if (name in preTriggerMap) {
      var preTriggerName = preTriggerMap[name];
      var preTriggerArgs = {
        prevented: false,
        name: name,
        args: args
      };

      actualTrigger.call(this, preTriggerName, preTriggerArgs);

      if (preTriggerArgs.prevented) {
        args.prevented = true;

        return;
      }
    }

    actualTrigger.call(this, name, args);
  };

  Select2.prototype.toggleDropdown = function () {
    if (this.options.get('disabled')) {
      return;
    }

    if (this.isOpen()) {
      this.close();
    } else {
      this.open();
    }
  };

  Select2.prototype.open = function () {
    if (this.isOpen()) {
      return;
    }

    this.trigger('query', {});
  };

  Select2.prototype.close = function () {
    if (!this.isOpen()) {
      return;
    }

    this.trigger('close', {});
  };

  Select2.prototype.isOpen = function () {
    return this.$container.hasClass('select2-container--open');
  };

  Select2.prototype.hasFocus = function () {
    return this.$container.hasClass('select2-container--focus');
  };

  Select2.prototype.focus = function (data) {
    // No need to re-trigger focus events if we are already focused
    if (this.hasFocus()) {
      return;
    }

    this.$container.addClass('select2-container--focus');
    this.trigger('focus', {});
  };

  Select2.prototype.enable = function (args) {
    if (this.options.get('debug') && window.console && console.warn) {
      console.warn(
        'Select2: The `select2("enable")` method has been deprecated and will' +
        ' be removed in later Select2 versions. Use $element.prop("disabled")' +
        ' instead.'
      );
    }

    if (args == null || args.length === 0) {
      args = [true];
    }

    var disabled = !args[0];

    this.$element.prop('disabled', disabled);
  };

  Select2.prototype.data = function () {
    if (this.options.get('debug') &&
        arguments.length > 0 && window.console && console.warn) {
      console.warn(
        'Select2: Data can no longer be set using `select2("data")`. You ' +
        'should consider setting the value instead using `$element.val()`.'
      );
    }

    var data = [];

    this.dataAdapter.current(function (currentData) {
      data = currentData;
    });

    return data;
  };

  Select2.prototype.val = function (args) {
    if (this.options.get('debug') && window.console && console.warn) {
      console.warn(
        'Select2: The `select2("val")` method has been deprecated and will be' +
        ' removed in later Select2 versions. Use $element.val() instead.'
      );
    }

    if (args == null || args.length === 0) {
      return this.$element.val();
    }

    var newVal = args[0];

    if ($.isArray(newVal)) {
      newVal = $.map(newVal, function (obj) {
        return obj.toString();
      });
    }

    this.$element.val(newVal).trigger('change');
  };

  Select2.prototype.destroy = function () {
    this.$container.remove();

    if (this.$element[0].detachEvent) {
      this.$element[0].detachEvent('onpropertychange', this._syncA);
    }

    if (this._observer != null) {
      this._observer.disconnect();
      this._observer = null;
    } else if (this.$element[0].removeEventListener) {
      this.$element[0]
        .removeEventListener('DOMAttrModified', this._syncA, false);
      this.$element[0]
        .removeEventListener('DOMNodeInserted', this._syncS, false);
      this.$element[0]
        .removeEventListener('DOMNodeRemoved', this._syncS, false);
    }

    this._syncA = null;
    this._syncS = null;

    this.$element.off('.select2');
    this.$element.attr('tabindex',
    Utils.GetData(this.$element[0], 'old-tabindex'));

    this.$element.removeClass('select2-hidden-accessible');
    this.$element.attr('aria-hidden', 'false');
    Utils.RemoveData(this.$element[0]);
    this.$element.removeData('select2');

    this.dataAdapter.destroy();
    this.selection.destroy();
    this.dropdown.destroy();
    this.results.destroy();

    this.dataAdapter = null;
    this.selection = null;
    this.dropdown = null;
    this.results = null;
  };

  Select2.prototype.render = function () {
    var $container = $(
      '<span class="select2 select2-container">' +
        '<span class="selection"></span>' +
        '<span class="dropdown-wrapper" aria-hidden="true"></span>' +
      '</span>'
    );

    $container.attr('dir', this.options.get('dir'));

    this.$container = $container;

    this.$container.addClass('select2-container--' + this.options.get('theme'));

    Utils.StoreData($container[0], 'element', this.$element);

    return $container;
  };

  return Select2;
});

S2.define('jquery-mousewheel',[
  'jquery'
], function ($) {
  // Used to shim jQuery.mousewheel for non-full builds.
  return $;
});

S2.define('jquery.select2',[
  'jquery',
  'jquery-mousewheel',

  './select2/core',
  './select2/defaults',
  './select2/utils'
], function ($, _, Select2, Defaults, Utils) {
  if ($.fn.select2 == null) {
    // All methods that should return the element
    var thisMethods = ['open', 'close', 'destroy'];

    $.fn.select2 = function (options) {
      options = options || {};

      if (typeof options === 'object') {
        this.each(function () {
          var instanceOptions = $.extend(true, {}, options);

          var instance = new Select2($(this), instanceOptions);
        });

        return this;
      } else if (typeof options === 'string') {
        var ret;
        var args = Array.prototype.slice.call(arguments, 1);

        this.each(function () {
          var instance = Utils.GetData(this, 'select2');

          if (instance == null && window.console && console.error) {
            console.error(
              'The select2(\'' + options + '\') method was called on an ' +
              'element that is not using Select2.'
            );
          }

          ret = instance[options].apply(instance, args);
        });

        // Check if we should be returning `this`
        if ($.inArray(options, thisMethods) > -1) {
          return this;
        }

        return ret;
      } else {
        throw new Error('Invalid arguments for Select2: ' + options);
      }
    };
  }

  if ($.fn.select2.defaults == null) {
    $.fn.select2.defaults = Defaults;
  }

  return Select2;
});

  // Return the AMD loader configuration so it can be used outside of this file
  return {
    define: S2.define,
    require: S2.require
  };
}());

  // Autoload the jQuery bindings
  // We know that all of the modules exist above this, so we're safe
  var select2 = S2.require('jquery.select2');

  // Hold the AMD module references on the jQuery function that was just loaded
  // This allows Select2 to use the internal loader outside of this file, such
  // as in the language files.
  jQuery.fn.select2.amd = S2;

  // Return the Select2 instance for anyone who is importing it.
  return select2;
}));
;
/*  
    
    Name:     slick
    Version:  1.8.0
    Url:      https://github.com/kenwheeler/slick/

    <section class="js-carousel carousel__wrapper">
        <article class="carousel__item">212121</article>
        <article class="carousel__item">321312321</article>
    </section>

    <script src="/scripts/perplex/slick.js"></script>
    <script>
        $(".js-carousel").slick({

            // https://github.com/kenwheeler/slick/#settings

            infinite: true,
            centerMode: false,
            dots: true,
            
            // responsive
            
            responsive: [{
                breakpoint: 1024,
                settings: {slidesToShow: 3, infinite: true}
            }, {
                breakpoint: 600,
                settings: {slidesToShow: 2, dots: true}
            }]
        });
    </script>

*/


/* global window, document, define, jQuery, setInterval, clearInterval */
;(function(factory) {
    'use strict';
    if (typeof define === 'function' && define.amd) {
        define(['jquery'], factory);
    } else if (typeof exports !== 'undefined') {
        module.exports = factory(require('jquery'));
    } else {
        factory(jQuery);
    }

}(function($) {
    'use strict';
    var Slick = window.Slick || {};

    Slick = (function() {

        var instanceUid = 0;

        function Slick(element, settings) {

            var _ = this, dataSettings;

            _.defaults = {
                accessibility: true,
                adaptiveHeight: false,
                appendArrows: $(element),
                appendDots: $(element),
                arrows: true,
                asNavFor: null,
                prevArrow: '<button class="slick-prev" aria-label="Previous" type="button">Previous</button>',
                nextArrow: '<button class="slick-next" aria-label="Next" type="button">Next</button>',
                autoplay: false,
                autoplaySpeed: 3000,
                centerMode: false,
                centerPadding: '50px',
                cssEase: 'ease',
                customPaging: function(slider, i) {
                    return $('<button type="button" />').text(i + 1);
                },
                dots: false,
                dotsClass: 'slick-dots',
                draggable: true,
                easing: 'linear',
                edgeFriction: 0.35,
                fade: false,
                focusOnSelect: false,
                focusOnChange: false,
                infinite: true,
                initialSlide: 0,
                lazyLoad: 'ondemand',
                mobileFirst: false,
                pauseOnHover: true,
                pauseOnFocus: true,
                pauseOnDotsHover: false,
                respondTo: 'window',
                responsive: null,
                rows: 1,
                rtl: false,
                slide: '',
                slidesPerRow: 1,
                slidesToShow: 1,
                slidesToScroll: 1,
                speed: 500,
                swipe: true,
                swipeToSlide: false,
                touchMove: true,
                touchThreshold: 5,
                useCSS: true,
                useTransform: true,
                variableWidth: false,
                vertical: false,
                verticalSwiping: false,
                waitForAnimate: true,
                zIndex: 1000
            };

            _.initials = {
                animating: false,
                dragging: false,
                autoPlayTimer: null,
                currentDirection: 0,
                currentLeft: null,
                currentSlide: 0,
                direction: 1,
                $dots: null,
                listWidth: null,
                listHeight: null,
                loadIndex: 0,
                $nextArrow: null,
                $prevArrow: null,
                scrolling: false,
                slideCount: null,
                slideWidth: null,
                $slideTrack: null,
                $slides: null,
                sliding: false,
                slideOffset: 0,
                swipeLeft: null,
                swiping: false,
                $list: null,
                touchObject: {},
                transformsEnabled: false,
                unslicked: false
            };

            $.extend(_, _.initials);

            _.activeBreakpoint = null;
            _.animType = null;
            _.animProp = null;
            _.breakpoints = [];
            _.breakpointSettings = [];
            _.cssTransitions = false;
            _.focussed = false;
            _.interrupted = false;
            _.hidden = 'hidden';
            _.paused = true;
            _.positionProp = null;
            _.respondTo = null;
            _.rowCount = 1;
            _.shouldClick = true;
            _.$slider = $(element);
            _.$slidesCache = null;
            _.transformType = null;
            _.transitionType = null;
            _.visibilityChange = 'visibilitychange';
            _.windowWidth = 0;
            _.windowTimer = null;

            dataSettings = $(element).data('slick') || {};

            _.options = $.extend({}, _.defaults, settings, dataSettings);

            _.currentSlide = _.options.initialSlide;

            _.originalSettings = _.options;

            if (typeof document.mozHidden !== 'undefined') {
                _.hidden = 'mozHidden';
                _.visibilityChange = 'mozvisibilitychange';
            } else if (typeof document.webkitHidden !== 'undefined') {
                _.hidden = 'webkitHidden';
                _.visibilityChange = 'webkitvisibilitychange';
            }

            _.autoPlay = $.proxy(_.autoPlay, _);
            _.autoPlayClear = $.proxy(_.autoPlayClear, _);
            _.autoPlayIterator = $.proxy(_.autoPlayIterator, _);
            _.changeSlide = $.proxy(_.changeSlide, _);
            _.clickHandler = $.proxy(_.clickHandler, _);
            _.selectHandler = $.proxy(_.selectHandler, _);
            _.setPosition = $.proxy(_.setPosition, _);
            _.swipeHandler = $.proxy(_.swipeHandler, _);
            _.dragHandler = $.proxy(_.dragHandler, _);
            _.keyHandler = $.proxy(_.keyHandler, _);

            _.instanceUid = instanceUid++;

            // A simple way to check for HTML strings
            // Strict HTML recognition (must start with <)
            // Extracted from jQuery v1.11 source
            _.htmlExpr = /^(?:\s*(<[\w\W]+>)[^>]*)$/;


            _.registerBreakpoints();
            _.init(true);

        }

        return Slick;

    }());

    Slick.prototype.activateADA = function() {
        var _ = this;

        _.$slideTrack.find('.slick-active').attr({
            'aria-hidden': 'false'
        }).find('a, input, button, select').attr({
            'tabindex': '0'
        });

    };

    Slick.prototype.addSlide = Slick.prototype.slickAdd = function(markup, index, addBefore) {

        var _ = this;

        if (typeof(index) === 'boolean') {
            addBefore = index;
            index = null;
        } else if (index < 0 || (index >= _.slideCount)) {
            return false;
        }

        _.unload();

        if (typeof(index) === 'number') {
            if (index === 0 && _.$slides.length === 0) {
                $(markup).appendTo(_.$slideTrack);
            } else if (addBefore) {
                $(markup).insertBefore(_.$slides.eq(index));
            } else {
                $(markup).insertAfter(_.$slides.eq(index));
            }
        } else {
            if (addBefore === true) {
                $(markup).prependTo(_.$slideTrack);
            } else {
                $(markup).appendTo(_.$slideTrack);
            }
        }

        _.$slides = _.$slideTrack.children(this.options.slide);

        _.$slideTrack.children(this.options.slide).detach();

        _.$slideTrack.append(_.$slides);

        _.$slides.each(function(index, element) {
            $(element).attr('data-slick-index', index);
        });

        _.$slidesCache = _.$slides;

        _.reinit();

    };

    Slick.prototype.animateHeight = function() {
        var _ = this;
        if (_.options.slidesToShow === 1 && _.options.adaptiveHeight === true && _.options.vertical === false) {
            var targetHeight = _.$slides.eq(_.currentSlide).outerHeight(true);
            _.$list.animate({
                height: targetHeight
            }, _.options.speed);
        }
    };

    Slick.prototype.animateSlide = function(targetLeft, callback) {

        var animProps = {},
            _ = this;

        _.animateHeight();

        if (_.options.rtl === true && _.options.vertical === false) {
            targetLeft = -targetLeft;
        }
        if (_.transformsEnabled === false) {
            if (_.options.vertical === false) {
                _.$slideTrack.animate({
                    left: targetLeft
                }, _.options.speed, _.options.easing, callback);
            } else {
                _.$slideTrack.animate({
                    top: targetLeft
                }, _.options.speed, _.options.easing, callback);
            }

        } else {

            if (_.cssTransitions === false) {
                if (_.options.rtl === true) {
                    _.currentLeft = -(_.currentLeft);
                }
                $({
                    animStart: _.currentLeft
                }).animate({
                    animStart: targetLeft
                }, {
                    duration: _.options.speed,
                    easing: _.options.easing,
                    step: function(now) {
                        now = Math.ceil(now);
                        if (_.options.vertical === false) {
                            animProps[_.animType] = 'translate(' +
                                now + 'px, 0px)';
                            _.$slideTrack.css(animProps);
                        } else {
                            animProps[_.animType] = 'translate(0px,' +
                                now + 'px)';
                            _.$slideTrack.css(animProps);
                        }
                    },
                    complete: function() {
                        if (callback) {
                            callback.call();
                        }
                    }
                });

            } else {

                _.applyTransition();
                targetLeft = Math.ceil(targetLeft);

                if (_.options.vertical === false) {
                    animProps[_.animType] = 'translate3d(' + targetLeft + 'px, 0px, 0px)';
                } else {
                    animProps[_.animType] = 'translate3d(0px,' + targetLeft + 'px, 0px)';
                }
                _.$slideTrack.css(animProps);

                if (callback) {
                    setTimeout(function() {

                        _.disableTransition();

                        callback.call();
                    }, _.options.speed);
                }

            }

        }

    };

    Slick.prototype.getNavTarget = function() {

        var _ = this,
            asNavFor = _.options.asNavFor;

        if ( asNavFor && asNavFor !== null ) {
            asNavFor = $(asNavFor).not(_.$slider);
        }

        return asNavFor;

    };

    Slick.prototype.asNavFor = function(index) {

        var _ = this,
            asNavFor = _.getNavTarget();

        if ( asNavFor !== null && typeof asNavFor === 'object' ) {
            asNavFor.each(function() {
                var target = $(this).slick('getSlick');
                if(!target.unslicked) {
                    target.slideHandler(index, true);
                }
            });
        }

    };

    Slick.prototype.applyTransition = function(slide) {

        var _ = this,
            transition = {};

        if (_.options.fade === false) {
            transition[_.transitionType] = _.transformType + ' ' + _.options.speed + 'ms ' + _.options.cssEase;
        } else {
            transition[_.transitionType] = 'opacity ' + _.options.speed + 'ms ' + _.options.cssEase;
        }

        if (_.options.fade === false) {
            _.$slideTrack.css(transition);
        } else {
            _.$slides.eq(slide).css(transition);
        }

    };

    Slick.prototype.autoPlay = function() {

        var _ = this;

        _.autoPlayClear();

        if ( _.slideCount > _.options.slidesToShow ) {
            _.autoPlayTimer = setInterval( _.autoPlayIterator, _.options.autoplaySpeed );
        }

    };

    Slick.prototype.autoPlayClear = function() {

        var _ = this;

        if (_.autoPlayTimer) {
            clearInterval(_.autoPlayTimer);
        }

    };

    Slick.prototype.autoPlayIterator = function() {

        var _ = this,
            slideTo = _.currentSlide + _.options.slidesToScroll;

        if ( !_.paused && !_.interrupted && !_.focussed ) {

            if ( _.options.infinite === false ) {

                if ( _.direction === 1 && ( _.currentSlide + 1 ) === ( _.slideCount - 1 )) {
                    _.direction = 0;
                }

                else if ( _.direction === 0 ) {

                    slideTo = _.currentSlide - _.options.slidesToScroll;

                    if ( _.currentSlide - 1 === 0 ) {
                        _.direction = 1;
                    }

                }

            }

            _.slideHandler( slideTo );

        }

    };

    Slick.prototype.buildArrows = function() {

        var _ = this;

        if (_.options.arrows === true ) {

            _.$prevArrow = $(_.options.prevArrow).addClass('slick-arrow');
            _.$nextArrow = $(_.options.nextArrow).addClass('slick-arrow');

            if( _.slideCount > _.options.slidesToShow ) {

                _.$prevArrow.removeClass('slick-hidden').removeAttr('aria-hidden tabindex');
                _.$nextArrow.removeClass('slick-hidden').removeAttr('aria-hidden tabindex');

                if (_.htmlExpr.test(_.options.prevArrow)) {
                    _.$prevArrow.prependTo(_.options.appendArrows);
                }

                if (_.htmlExpr.test(_.options.nextArrow)) {
                    _.$nextArrow.appendTo(_.options.appendArrows);
                }

                if (_.options.infinite !== true) {
                    _.$prevArrow
                        .addClass('slick-disabled')
                        .attr('aria-disabled', 'true');
                }

            } else {

                _.$prevArrow.add( _.$nextArrow )

                    .addClass('slick-hidden')
                    .attr({
                        'aria-disabled': 'true',
                        'tabindex': '-1'
                    });

            }

        }

    };

    Slick.prototype.buildDots = function() {

        var _ = this,
            i, dot;

        if (_.options.dots === true && _.slideCount > _.options.slidesToShow) {

            _.$slider.addClass('slick-dotted');

            dot = $('<ul />').addClass(_.options.dotsClass);

            for (i = 0; i <= _.getDotCount(); i += 1) {
                dot.append($('<li />').append(_.options.customPaging.call(this, _, i)));
            }

            _.$dots = dot.appendTo(_.options.appendDots);

            _.$dots.find('li').first().addClass('slick-active');

        }

    };

    Slick.prototype.buildOut = function() {

        var _ = this;

        _.$slides =
            _.$slider
                .children( _.options.slide + ':not(.slick-cloned)')
                .addClass('slick-slide');

        _.slideCount = _.$slides.length;

        _.$slides.each(function(index, element) {
            $(element)
                .attr('data-slick-index', index)
                .data('originalStyling', $(element).attr('style') || '');
        });

        _.$slider.addClass('slick-slider');

        _.$slideTrack = (_.slideCount === 0) ?
            $('<div class="slick-track"/>').appendTo(_.$slider) :
            _.$slides.wrapAll('<div class="slick-track"/>').parent();

        _.$list = _.$slideTrack.wrap(
            '<div class="slick-list"/>').parent();
        _.$slideTrack.css('opacity', 0);

        if (_.options.centerMode === true || _.options.swipeToSlide === true) {
            _.options.slidesToScroll = 1;
        }

        $('img[data-lazy]', _.$slider).not('[src]').addClass('slick-loading');

        _.setupInfinite();

        _.buildArrows();

        _.buildDots();

        _.updateDots();


        _.setSlideClasses(typeof _.currentSlide === 'number' ? _.currentSlide : 0);

        if (_.options.draggable === true) {
            _.$list.addClass('draggable');
        }

    };

    Slick.prototype.buildRows = function() {

        var _ = this, a, b, c, newSlides, numOfSlides, originalSlides,slidesPerSection;

        newSlides = document.createDocumentFragment();
        originalSlides = _.$slider.children();

        if(_.options.rows > 0) {

            slidesPerSection = _.options.slidesPerRow * _.options.rows;
            numOfSlides = Math.ceil(
                originalSlides.length / slidesPerSection
            );

            for(a = 0; a < numOfSlides; a++){
                var slide = document.createElement('div');
                for(b = 0; b < _.options.rows; b++) {
                    var row = document.createElement('div');
                    for(c = 0; c < _.options.slidesPerRow; c++) {
                        var target = (a * slidesPerSection + ((b * _.options.slidesPerRow) + c));
                        if (originalSlides.get(target)) {
                            row.appendChild(originalSlides.get(target));
                        }
                    }
                    slide.appendChild(row);
                }
                newSlides.appendChild(slide);
            }

            _.$slider.empty().append(newSlides);
            _.$slider.children().children().children()
                .css({
                    'width':(100 / _.options.slidesPerRow) + '%',
                    'display': 'inline-block'
                });

        }

    };

    Slick.prototype.checkResponsive = function(initial, forceUpdate) {

        var _ = this,
            breakpoint, targetBreakpoint, respondToWidth, triggerBreakpoint = false;
        var sliderWidth = _.$slider.width();
        var windowWidth = window.innerWidth || $(window).width();

        if (_.respondTo === 'window') {
            respondToWidth = windowWidth;
        } else if (_.respondTo === 'slider') {
            respondToWidth = sliderWidth;
        } else if (_.respondTo === 'min') {
            respondToWidth = Math.min(windowWidth, sliderWidth);
        }

        if ( _.options.responsive &&
            _.options.responsive.length &&
            _.options.responsive !== null) {

            targetBreakpoint = null;

            for (breakpoint in _.breakpoints) {
                if (_.breakpoints.hasOwnProperty(breakpoint)) {
                    if (_.originalSettings.mobileFirst === false) {
                        if (respondToWidth < _.breakpoints[breakpoint]) {
                            targetBreakpoint = _.breakpoints[breakpoint];
                        }
                    } else {
                        if (respondToWidth > _.breakpoints[breakpoint]) {
                            targetBreakpoint = _.breakpoints[breakpoint];
                        }
                    }
                }
            }

            if (targetBreakpoint !== null) {
                if (_.activeBreakpoint !== null) {
                    if (targetBreakpoint !== _.activeBreakpoint || forceUpdate) {
                        _.activeBreakpoint =
                            targetBreakpoint;
                        if (_.breakpointSettings[targetBreakpoint] === 'unslick') {
                            _.unslick(targetBreakpoint);
                        } else {
                            _.options = $.extend({}, _.originalSettings,
                                _.breakpointSettings[
                                    targetBreakpoint]);
                            if (initial === true) {
                                _.currentSlide = _.options.initialSlide;
                            }
                            _.refresh(initial);
                        }
                        triggerBreakpoint = targetBreakpoint;
                    }
                } else {
                    _.activeBreakpoint = targetBreakpoint;
                    if (_.breakpointSettings[targetBreakpoint] === 'unslick') {
                        _.unslick(targetBreakpoint);
                    } else {
                        _.options = $.extend({}, _.originalSettings,
                            _.breakpointSettings[
                                targetBreakpoint]);
                        if (initial === true) {
                            _.currentSlide = _.options.initialSlide;
                        }
                        _.refresh(initial);
                    }
                    triggerBreakpoint = targetBreakpoint;
                }
            } else {
                if (_.activeBreakpoint !== null) {
                    _.activeBreakpoint = null;
                    _.options = _.originalSettings;
                    if (initial === true) {
                        _.currentSlide = _.options.initialSlide;
                    }
                    _.refresh(initial);
                    triggerBreakpoint = targetBreakpoint;
                }
            }

            // only trigger breakpoints during an actual break. not on initialize.
            if( !initial && triggerBreakpoint !== false ) {
                _.$slider.trigger('breakpoint', [_, triggerBreakpoint]);
            }
        }

    };

    Slick.prototype.changeSlide = function(event, dontAnimate) {

        var _ = this,
            $target = $(event.currentTarget),
            indexOffset, slideOffset, unevenOffset;

        // If target is a link, prevent default action.
        if($target.is('a')) {
            event.preventDefault();
        }

        // If target is not the <li> element (ie: a child), find the <li>.
        if(!$target.is('li')) {
            $target = $target.closest('li');
        }

        unevenOffset = (_.slideCount % _.options.slidesToScroll !== 0);
        indexOffset = unevenOffset ? 0 : (_.slideCount - _.currentSlide) % _.options.slidesToScroll;

        switch (event.data.message) {

            case 'previous':
                slideOffset = indexOffset === 0 ? _.options.slidesToScroll : _.options.slidesToShow - indexOffset;
                if (_.slideCount > _.options.slidesToShow) {
                    _.slideHandler(_.currentSlide - slideOffset, false, dontAnimate);
                }
                break;

            case 'next':
                slideOffset = indexOffset === 0 ? _.options.slidesToScroll : indexOffset;
                if (_.slideCount > _.options.slidesToShow) {
                    _.slideHandler(_.currentSlide + slideOffset, false, dontAnimate);
                }
                break;

            case 'index':
                var index = event.data.index === 0 ? 0 :
                    event.data.index || $target.index() * _.options.slidesToScroll;

                _.slideHandler(_.checkNavigable(index), false, dontAnimate);
                $target.children().trigger('focus');
                break;

            default:
                return;
        }

    };

    Slick.prototype.checkNavigable = function(index) {

        var _ = this,
            navigables, prevNavigable;

        navigables = _.getNavigableIndexes();
        prevNavigable = 0;
        if (index > navigables[navigables.length - 1]) {
            index = navigables[navigables.length - 1];
        } else {
            for (var n in navigables) {
                if (index < navigables[n]) {
                    index = prevNavigable;
                    break;
                }
                prevNavigable = navigables[n];
            }
        }

        return index;
    };

    Slick.prototype.cleanUpEvents = function() {

        var _ = this;

        if (_.options.dots && _.$dots !== null) {

            $('li', _.$dots)
                .off('click.slick', _.changeSlide)
                .off('mouseenter.slick', $.proxy(_.interrupt, _, true))
                .off('mouseleave.slick', $.proxy(_.interrupt, _, false));

            if (_.options.accessibility === true) {
                _.$dots.off('keydown.slick', _.keyHandler);
            }
        }

        _.$slider.off('focus.slick blur.slick');

        if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) {
            _.$prevArrow && _.$prevArrow.off('click.slick', _.changeSlide);
            _.$nextArrow && _.$nextArrow.off('click.slick', _.changeSlide);

            if (_.options.accessibility === true) {
                _.$prevArrow && _.$prevArrow.off('keydown.slick', _.keyHandler);
                _.$nextArrow && _.$nextArrow.off('keydown.slick', _.keyHandler);
            }
        }

        _.$list.off('touchstart.slick mousedown.slick', _.swipeHandler);
        _.$list.off('touchmove.slick mousemove.slick', _.swipeHandler);
        _.$list.off('touchend.slick mouseup.slick', _.swipeHandler);
        _.$list.off('touchcancel.slick mouseleave.slick', _.swipeHandler);

        _.$list.off('click.slick', _.clickHandler);

        $(document).off(_.visibilityChange, _.visibility);

        _.cleanUpSlideEvents();

        if (_.options.accessibility === true) {
            _.$list.off('keydown.slick', _.keyHandler);
        }

        if (_.options.focusOnSelect === true) {
            $(_.$slideTrack).children().off('click.slick', _.selectHandler);
        }

        $(window).off('orientationchange.slick.slick-' + _.instanceUid, _.orientationChange);

        $(window).off('resize.slick.slick-' + _.instanceUid, _.resize);

        $('[draggable!=true]', _.$slideTrack).off('dragstart', _.preventDefault);

        $(window).off('load.slick.slick-' + _.instanceUid, _.setPosition);

    };

    Slick.prototype.cleanUpSlideEvents = function() {

        var _ = this;

        _.$list.off('mouseenter.slick', $.proxy(_.interrupt, _, true));
        _.$list.off('mouseleave.slick', $.proxy(_.interrupt, _, false));

    };

    Slick.prototype.cleanUpRows = function() {

        var _ = this, originalSlides;

        if(_.options.rows > 0) {
            originalSlides = _.$slides.children().children();
            originalSlides.removeAttr('style');
            _.$slider.empty().append(originalSlides);
        }

    };

    Slick.prototype.clickHandler = function(event) {

        var _ = this;

        if (_.shouldClick === false) {
            event.stopImmediatePropagation();
            event.stopPropagation();
            event.preventDefault();
        }

    };

    Slick.prototype.destroy = function(refresh) {

        var _ = this;

        _.autoPlayClear();

        _.touchObject = {};

        _.cleanUpEvents();

        $('.slick-cloned', _.$slider).detach();

        if (_.$dots) {
            _.$dots.remove();
        }

        if ( _.$prevArrow && _.$prevArrow.length ) {

            _.$prevArrow
                .removeClass('slick-disabled slick-arrow slick-hidden')
                .removeAttr('aria-hidden aria-disabled tabindex')
                .css('display','');

            if ( _.htmlExpr.test( _.options.prevArrow )) {
                _.$prevArrow.remove();
            }
        }

        if ( _.$nextArrow && _.$nextArrow.length ) {

            _.$nextArrow
                .removeClass('slick-disabled slick-arrow slick-hidden')
                .removeAttr('aria-hidden aria-disabled tabindex')
                .css('display','');

            if ( _.htmlExpr.test( _.options.nextArrow )) {
                _.$nextArrow.remove();
            }
        }


        if (_.$slides) {

            _.$slides
                .removeClass('slick-slide slick-active slick-center slick-visible slick-current')
                .removeAttr('aria-hidden')
                .removeAttr('data-slick-index')
                .each(function(){
                    $(this).attr('style', $(this).data('originalStyling'));
                });

            _.$slideTrack.children(this.options.slide).detach();

            _.$slideTrack.detach();

            _.$list.detach();

            _.$slider.append(_.$slides);
        }

        _.cleanUpRows();

        _.$slider.removeClass('slick-slider');
        _.$slider.removeClass('slick-initialized');
        _.$slider.removeClass('slick-dotted');

        _.unslicked = true;

        if(!refresh) {
            _.$slider.trigger('destroy', [_]);
        }

    };

    Slick.prototype.disableTransition = function(slide) {

        var _ = this,
            transition = {};

        transition[_.transitionType] = '';

        if (_.options.fade === false) {
            _.$slideTrack.css(transition);
        } else {
            _.$slides.eq(slide).css(transition);
        }

    };

    Slick.prototype.fadeSlide = function(slideIndex, callback) {

        var _ = this;

        if (_.cssTransitions === false) {

            _.$slides.eq(slideIndex).css({
                zIndex: _.options.zIndex
            });

            _.$slides.eq(slideIndex).animate({
                opacity: 1
            }, _.options.speed, _.options.easing, callback);

        } else {

            _.applyTransition(slideIndex);

            _.$slides.eq(slideIndex).css({
                opacity: 1,
                zIndex: _.options.zIndex
            });

            if (callback) {
                setTimeout(function() {

                    _.disableTransition(slideIndex);

                    callback.call();
                }, _.options.speed);
            }

        }

    };

    Slick.prototype.fadeSlideOut = function(slideIndex) {

        var _ = this;

        if (_.cssTransitions === false) {

            _.$slides.eq(slideIndex).animate({
                opacity: 0,
                zIndex: _.options.zIndex - 2
            }, _.options.speed, _.options.easing);

        } else {

            _.applyTransition(slideIndex);

            _.$slides.eq(slideIndex).css({
                opacity: 0,
                zIndex: _.options.zIndex - 2
            });

        }

    };

    Slick.prototype.filterSlides = Slick.prototype.slickFilter = function(filter) {

        var _ = this;

        if (filter !== null) {

            _.$slidesCache = _.$slides;

            _.unload();

            _.$slideTrack.children(this.options.slide).detach();

            _.$slidesCache.filter(filter).appendTo(_.$slideTrack);

            _.reinit();

        }

    };

    Slick.prototype.focusHandler = function() {

        var _ = this;

        _.$slider
            .off('focus.slick blur.slick')
            .on('focus.slick blur.slick', '*', function(event) {

            event.stopImmediatePropagation();
            var $sf = $(this);

            setTimeout(function() {

                if( _.options.pauseOnFocus ) {
                    _.focussed = $sf.is(':focus');
                    _.autoPlay();
                }

            }, 0);

        });
    };

    Slick.prototype.getCurrent = Slick.prototype.slickCurrentSlide = function() {

        var _ = this;
        return _.currentSlide;

    };

    Slick.prototype.getDotCount = function() {

        var _ = this;

        var breakPoint = 0;
        var counter = 0;
        var pagerQty = 0;

        if (_.options.infinite === true) {
            if (_.slideCount <= _.options.slidesToShow) {
                 ++pagerQty;
            } else {
                while (breakPoint < _.slideCount) {
                    ++pagerQty;
                    breakPoint = counter + _.options.slidesToScroll;
                    counter += _.options.slidesToScroll <= _.options.slidesToShow ? _.options.slidesToScroll : _.options.slidesToShow;
                }
            }
        } else if (_.options.centerMode === true) {
            pagerQty = _.slideCount;
        } else if(!_.options.asNavFor) {
            pagerQty = 1 + Math.ceil((_.slideCount - _.options.slidesToShow) / _.options.slidesToScroll);
        }else {
            while (breakPoint < _.slideCount) {
                ++pagerQty;
                breakPoint = counter + _.options.slidesToScroll;
                counter += _.options.slidesToScroll <= _.options.slidesToShow ? _.options.slidesToScroll : _.options.slidesToShow;
            }
        }

        return pagerQty - 1;

    };

    Slick.prototype.getLeft = function(slideIndex) {

        var _ = this,
            targetLeft,
            verticalHeight,
            verticalOffset = 0,
            targetSlide,
            coef;

        _.slideOffset = 0;
        verticalHeight = _.$slides.first().outerHeight(true);

        if (_.options.infinite === true) {
            if (_.slideCount > _.options.slidesToShow) {
                _.slideOffset = (_.slideWidth * _.options.slidesToShow) * -1;
                coef = -1

                if (_.options.vertical === true && _.options.centerMode === true) {
                    if (_.options.slidesToShow === 2) {
                        coef = -1.5;
                    } else if (_.options.slidesToShow === 1) {
                        coef = -2
                    }
                }
                verticalOffset = (verticalHeight * _.options.slidesToShow) * coef;
            }
            if (_.slideCount % _.options.slidesToScroll !== 0) {
                if (slideIndex + _.options.slidesToScroll > _.slideCount && _.slideCount > _.options.slidesToShow) {
                    if (slideIndex > _.slideCount) {
                        _.slideOffset = ((_.options.slidesToShow - (slideIndex - _.slideCount)) * _.slideWidth) * -1;
                        verticalOffset = ((_.options.slidesToShow - (slideIndex - _.slideCount)) * verticalHeight) * -1;
                    } else {
                        _.slideOffset = ((_.slideCount % _.options.slidesToScroll) * _.slideWidth) * -1;
                        verticalOffset = ((_.slideCount % _.options.slidesToScroll) * verticalHeight) * -1;
                    }
                }
            }
        } else {
            if (slideIndex + _.options.slidesToShow > _.slideCount) {
                _.slideOffset = ((slideIndex + _.options.slidesToShow) - _.slideCount) * _.slideWidth;
                verticalOffset = ((slideIndex + _.options.slidesToShow) - _.slideCount) * verticalHeight;
            }
        }

        if (_.slideCount <= _.options.slidesToShow) {
            _.slideOffset = 0;
            verticalOffset = 0;
        }

        if (_.options.centerMode === true && _.slideCount <= _.options.slidesToShow) {
            _.slideOffset = ((_.slideWidth * Math.floor(_.options.slidesToShow)) / 2) - ((_.slideWidth * _.slideCount) / 2);
        } else if (_.options.centerMode === true && _.options.infinite === true) {
            _.slideOffset += _.slideWidth * Math.floor(_.options.slidesToShow / 2) - _.slideWidth;
        } else if (_.options.centerMode === true) {
            _.slideOffset = 0;
            _.slideOffset += _.slideWidth * Math.floor(_.options.slidesToShow / 2);
        }

        if (_.options.vertical === false) {
            targetLeft = ((slideIndex * _.slideWidth) * -1) + _.slideOffset;
        } else {
            targetLeft = ((slideIndex * verticalHeight) * -1) + verticalOffset;
        }

        if (_.options.variableWidth === true) {

            if (_.slideCount <= _.options.slidesToShow || _.options.infinite === false) {
                targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex);
            } else {
                targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex + _.options.slidesToShow);
            }

            if (_.options.rtl === true) {
                if (targetSlide[0]) {
                    targetLeft = (_.$slideTrack.width() - targetSlide[0].offsetLeft - targetSlide.width()) * -1;
                } else {
                    targetLeft =  0;
                }
            } else {
                targetLeft = targetSlide[0] ? targetSlide[0].offsetLeft * -1 : 0;
            }

            if (_.options.centerMode === true) {
                if (_.slideCount <= _.options.slidesToShow || _.options.infinite === false) {
                    targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex);
                } else {
                    targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex + _.options.slidesToShow + 1);
                }

                if (_.options.rtl === true) {
                    if (targetSlide[0]) {
                        targetLeft = (_.$slideTrack.width() - targetSlide[0].offsetLeft - targetSlide.width()) * -1;
                    } else {
                        targetLeft =  0;
                    }
                } else {
                    targetLeft = targetSlide[0] ? targetSlide[0].offsetLeft * -1 : 0;
                }

                targetLeft += (_.$list.width() - targetSlide.outerWidth()) / 2;
            }
        }

        return targetLeft;

    };

    Slick.prototype.getOption = Slick.prototype.slickGetOption = function(option) {

        var _ = this;

        return _.options[option];

    };

    Slick.prototype.getNavigableIndexes = function() {

        var _ = this,
            breakPoint = 0,
            counter = 0,
            indexes = [],
            max;

        if (_.options.infinite === false) {
            max = _.slideCount;
        } else {
            breakPoint = _.options.slidesToScroll * -1;
            counter = _.options.slidesToScroll * -1;
            max = _.slideCount * 2;
        }

        while (breakPoint < max) {
            indexes.push(breakPoint);
            breakPoint = counter + _.options.slidesToScroll;
            counter += _.options.slidesToScroll <= _.options.slidesToShow ? _.options.slidesToScroll : _.options.slidesToShow;
        }

        return indexes;

    };

    Slick.prototype.getSlick = function() {

        return this;

    };

    Slick.prototype.getSlideCount = function() {

        var _ = this,
            slidesTraversed, swipedSlide, centerOffset;

        centerOffset = _.options.centerMode === true ? _.slideWidth * Math.floor(_.options.slidesToShow / 2) : 0;

        if (_.options.swipeToSlide === true) {
            _.$slideTrack.find('.slick-slide').each(function(index, slide) {
                if (slide.offsetLeft - centerOffset + ($(slide).outerWidth() / 2) > (_.swipeLeft * -1)) {
                    swipedSlide = slide;
                    return false;
                }
            });

            slidesTraversed = Math.abs($(swipedSlide).attr('data-slick-index') - _.currentSlide) || 1;

            return slidesTraversed;

        } else {
            return _.options.slidesToScroll;
        }

    };

    Slick.prototype.goTo = Slick.prototype.slickGoTo = function(slide, dontAnimate) {

        var _ = this;

        _.changeSlide({
            data: {
                message: 'index',
                index: parseInt(slide)
            }
        }, dontAnimate);

    };

    Slick.prototype.init = function(creation) {

        var _ = this;

        if (!$(_.$slider).hasClass('slick-initialized')) {

            $(_.$slider).addClass('slick-initialized');

            _.buildRows();
            _.buildOut();
            _.setProps();
            _.startLoad();
            _.loadSlider();
            _.initializeEvents();
            _.updateArrows();
            _.updateDots();
            _.checkResponsive(true);
            _.focusHandler();

        }

        if (creation) {
            _.$slider.trigger('init', [_]);
        }

        if (_.options.accessibility === true) {
            _.initADA();
        }

        if ( _.options.autoplay ) {

            _.paused = false;
            _.autoPlay();

        }

    };

    Slick.prototype.initADA = function() {
        var _ = this,
                numDotGroups = Math.ceil(_.slideCount / _.options.slidesToShow),
                tabControlIndexes = _.getNavigableIndexes().filter(function(val) {
                    return (val >= 0) && (val < _.slideCount);
                });

        _.$slides.add(_.$slideTrack.find('.slick-cloned')).attr({
            'aria-hidden': 'true',
            'tabindex': '-1'
        }).find('a, input, button, select').attr({
            'tabindex': '-1'
        });

        if (_.$dots !== null) {
            _.$slides.not(_.$slideTrack.find('.slick-cloned')).each(function(i) {
                var slideControlIndex = tabControlIndexes.indexOf(i);

                $(this).attr({
                    'role': 'tabpanel',
                    'id': 'slick-slide' + _.instanceUid + i,
                    'tabindex': -1
                });

                if (slideControlIndex !== -1) {
                   var ariaButtonControl = 'slick-slide-control' + _.instanceUid + slideControlIndex
                   if ($('#' + ariaButtonControl).length) {
                     $(this).attr({
                         'aria-describedby': ariaButtonControl
                     });
                   }
                }
            });

            _.$dots.attr('role', 'tablist').find('li').each(function(i) {
                var mappedSlideIndex = tabControlIndexes[i];

                $(this).attr({
                    'role': 'presentation'
                });

                $(this).find('button').first().attr({
                    'role': 'tab',
                    'id': 'slick-slide-control' + _.instanceUid + i,
                    'aria-controls': 'slick-slide' + _.instanceUid + mappedSlideIndex,
                    'aria-label': (i + 1) + ' of ' + numDotGroups,
                    'aria-selected': null,
                    'tabindex': '-1'
                });

            }).eq(_.currentSlide).find('button').attr({
                'aria-selected': 'true',
                'tabindex': '0'
            }).end();
        }

        for (var i=_.currentSlide, max=i+_.options.slidesToShow; i < max; i++) {
          if (_.options.focusOnChange) {
            _.$slides.eq(i).attr({'tabindex': '0'});
          } else {
            _.$slides.eq(i).removeAttr('tabindex');
          }
        }

        _.activateADA();

    };

    Slick.prototype.initArrowEvents = function() {

        var _ = this;

        if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) {
            _.$prevArrow
               .off('click.slick')
               .on('click.slick', {
                    message: 'previous'
               }, _.changeSlide);
            _.$nextArrow
               .off('click.slick')
               .on('click.slick', {
                    message: 'next'
               }, _.changeSlide);

            if (_.options.accessibility === true) {
                _.$prevArrow.on('keydown.slick', _.keyHandler);
                _.$nextArrow.on('keydown.slick', _.keyHandler);
            }
        }

    };

    Slick.prototype.initDotEvents = function() {

        var _ = this;

        if (_.options.dots === true && _.slideCount > _.options.slidesToShow) {
            $('li', _.$dots).on('click.slick', {
                message: 'index'
            }, _.changeSlide);

            if (_.options.accessibility === true) {
                _.$dots.on('keydown.slick', _.keyHandler);
            }
        }

        if (_.options.dots === true && _.options.pauseOnDotsHover === true && _.slideCount > _.options.slidesToShow) {

            $('li', _.$dots)
                .on('mouseenter.slick', $.proxy(_.interrupt, _, true))
                .on('mouseleave.slick', $.proxy(_.interrupt, _, false));

        }

    };

    Slick.prototype.initSlideEvents = function() {

        var _ = this;

        if ( _.options.pauseOnHover ) {

            _.$list.on('mouseenter.slick', $.proxy(_.interrupt, _, true));
            _.$list.on('mouseleave.slick', $.proxy(_.interrupt, _, false));

        }

    };

    Slick.prototype.initializeEvents = function() {

        var _ = this;

        _.initArrowEvents();

        _.initDotEvents();
        _.initSlideEvents();

        _.$list.on('touchstart.slick mousedown.slick', {
            action: 'start'
        }, _.swipeHandler);
        _.$list.on('touchmove.slick mousemove.slick', {
            action: 'move'
        }, _.swipeHandler);
        _.$list.on('touchend.slick mouseup.slick', {
            action: 'end'
        }, _.swipeHandler);
        _.$list.on('touchcancel.slick mouseleave.slick', {
            action: 'end'
        }, _.swipeHandler);

        _.$list.on('click.slick', _.clickHandler);

        $(document).on(_.visibilityChange, $.proxy(_.visibility, _));

        if (_.options.accessibility === true) {
            _.$list.on('keydown.slick', _.keyHandler);
        }

        if (_.options.focusOnSelect === true) {
            $(_.$slideTrack).children().on('click.slick', _.selectHandler);
        }

        $(window).on('orientationchange.slick.slick-' + _.instanceUid, $.proxy(_.orientationChange, _));

        $(window).on('resize.slick.slick-' + _.instanceUid, $.proxy(_.resize, _));

        $('[draggable!=true]', _.$slideTrack).on('dragstart', _.preventDefault);

        $(window).on('load.slick.slick-' + _.instanceUid, _.setPosition);
        $(_.setPosition);

    };

    Slick.prototype.initUI = function() {

        var _ = this;

        if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) {

            _.$prevArrow.show();
            _.$nextArrow.show();

        }

        if (_.options.dots === true && _.slideCount > _.options.slidesToShow) {

            _.$dots.show();

        }

    };

    Slick.prototype.keyHandler = function(event) {

        var _ = this;
         //Dont slide if the cursor is inside the form fields and arrow keys are pressed
        if(!event.target.tagName.match('TEXTAREA|INPUT|SELECT')) {
            if (event.keyCode === 37 && _.options.accessibility === true) {
                _.changeSlide({
                    data: {
                        message: _.options.rtl === true ? 'next' :  'previous'
                    }
                });
            } else if (event.keyCode === 39 && _.options.accessibility === true) {
                _.changeSlide({
                    data: {
                        message: _.options.rtl === true ? 'previous' : 'next'
                    }
                });
            }
        }

    };

    Slick.prototype.lazyLoad = function() {

        var _ = this,
            loadRange, cloneRange, rangeStart, rangeEnd;

        function loadImages(imagesScope) {

            $('img[data-lazy]', imagesScope).each(function() {

                var image = $(this),
                    imageSource = $(this).attr('data-lazy'),
                    imageSrcSet = $(this).attr('data-srcset'),
                    imageSizes  = $(this).attr('data-sizes') || _.$slider.attr('data-sizes'),
                    imageToLoad = document.createElement('img');

                imageToLoad.onload = function() {

                    image
                        .animate({ opacity: 0 }, 100, function() {

                            if (imageSrcSet) {
                                image
                                    .attr('srcset', imageSrcSet );

                                if (imageSizes) {
                                    image
                                        .attr('sizes', imageSizes );
                                }
                            }

                            image
                                .attr('src', imageSource)
                                .animate({ opacity: 1 }, 200, function() {
                                    image
                                        .removeAttr('data-lazy data-srcset data-sizes')
                                        .removeClass('slick-loading');
                                });
                            _.$slider.trigger('lazyLoaded', [_, image, imageSource]);
                        });

                };

                imageToLoad.onerror = function() {

                    image
                        .removeAttr( 'data-lazy' )
                        .removeClass( 'slick-loading' )
                        .addClass( 'slick-lazyload-error' );

                    _.$slider.trigger('lazyLoadError', [ _, image, imageSource ]);

                };

                imageToLoad.src = imageSource;

            });

        }

        if (_.options.centerMode === true) {
            if (_.options.infinite === true) {
                rangeStart = _.currentSlide + (_.options.slidesToShow / 2 + 1);
                rangeEnd = rangeStart + _.options.slidesToShow + 2;
            } else {
                rangeStart = Math.max(0, _.currentSlide - (_.options.slidesToShow / 2 + 1));
                rangeEnd = 2 + (_.options.slidesToShow / 2 + 1) + _.currentSlide;
            }
        } else {
            rangeStart = _.options.infinite ? _.options.slidesToShow + _.currentSlide : _.currentSlide;
            rangeEnd = Math.ceil(rangeStart + _.options.slidesToShow);
            if (_.options.fade === true) {
                if (rangeStart > 0) rangeStart--;
                if (rangeEnd <= _.slideCount) rangeEnd++;
            }
        }

        loadRange = _.$slider.find('.slick-slide').slice(rangeStart, rangeEnd);

        if (_.options.lazyLoad === 'anticipated') {
            var prevSlide = rangeStart - 1,
                nextSlide = rangeEnd,
                $slides = _.$slider.find('.slick-slide');

            for (var i = 0; i < _.options.slidesToScroll; i++) {
                if (prevSlide < 0) prevSlide = _.slideCount - 1;
                loadRange = loadRange.add($slides.eq(prevSlide));
                loadRange = loadRange.add($slides.eq(nextSlide));
                prevSlide--;
                nextSlide++;
            }
        }

        loadImages(loadRange);

        if (_.slideCount <= _.options.slidesToShow) {
            cloneRange = _.$slider.find('.slick-slide');
            loadImages(cloneRange);
        } else
        if (_.currentSlide >= _.slideCount - _.options.slidesToShow) {
            cloneRange = _.$slider.find('.slick-cloned').slice(0, _.options.slidesToShow);
            loadImages(cloneRange);
        } else if (_.currentSlide === 0) {
            cloneRange = _.$slider.find('.slick-cloned').slice(_.options.slidesToShow * -1);
            loadImages(cloneRange);
        }

    };

    Slick.prototype.loadSlider = function() {

        var _ = this;

        _.setPosition();

        _.$slideTrack.css({
            opacity: 1
        });

        _.$slider.removeClass('slick-loading');

        _.initUI();

        if (_.options.lazyLoad === 'progressive') {
            _.progressiveLazyLoad();
        }

    };

    Slick.prototype.next = Slick.prototype.slickNext = function() {

        var _ = this;

        _.changeSlide({
            data: {
                message: 'next'
            }
        });

    };

    Slick.prototype.orientationChange = function() {

        var _ = this;

        _.checkResponsive();
        _.setPosition();

    };

    Slick.prototype.pause = Slick.prototype.slickPause = function() {

        var _ = this;

        _.autoPlayClear();
        _.paused = true;

    };

    Slick.prototype.play = Slick.prototype.slickPlay = function() {

        var _ = this;

        _.autoPlay();
        _.options.autoplay = true;
        _.paused = false;
        _.focussed = false;
        _.interrupted = false;

    };

    Slick.prototype.postSlide = function(index) {

        var _ = this;

        if( !_.unslicked ) {

            _.$slider.trigger('afterChange', [_, index]);

            _.animating = false;

            if (_.slideCount > _.options.slidesToShow) {
                _.setPosition();
            }

            _.swipeLeft = null;

            if ( _.options.autoplay ) {
                _.autoPlay();
            }

            if (_.options.accessibility === true) {
                _.initADA();

                if (_.options.focusOnChange) {
                    var $currentSlide = $(_.$slides.get(_.currentSlide));
                    $currentSlide.attr('tabindex', 0).focus();
                }
            }

        }

    };

    Slick.prototype.prev = Slick.prototype.slickPrev = function() {

        var _ = this;

        _.changeSlide({
            data: {
                message: 'previous'
            }
        });

    };

    Slick.prototype.preventDefault = function(event) {

        event.preventDefault();

    };

    Slick.prototype.progressiveLazyLoad = function( tryCount ) {

        tryCount = tryCount || 1;

        var _ = this,
            $imgsToLoad = $( 'img[data-lazy]', _.$slider ),
            image,
            imageSource,
            imageSrcSet,
            imageSizes,
            imageToLoad;

        if ( $imgsToLoad.length ) {

            image = $imgsToLoad.first();
            imageSource = image.attr('data-lazy');
            imageSrcSet = image.attr('data-srcset');
            imageSizes  = image.attr('data-sizes') || _.$slider.attr('data-sizes');
            imageToLoad = document.createElement('img');

            imageToLoad.onload = function() {

                if (imageSrcSet) {
                    image
                        .attr('srcset', imageSrcSet );

                    if (imageSizes) {
                        image
                            .attr('sizes', imageSizes );
                    }
                }

                image
                    .attr( 'src', imageSource )
                    .removeAttr('data-lazy data-srcset data-sizes')
                    .removeClass('slick-loading');

                if ( _.options.adaptiveHeight === true ) {
                    _.setPosition();
                }

                _.$slider.trigger('lazyLoaded', [ _, image, imageSource ]);
                _.progressiveLazyLoad();

            };

            imageToLoad.onerror = function() {

                if ( tryCount < 3 ) {

                    /**
                     * try to load the image 3 times,
                     * leave a slight delay so we don't get
                     * servers blocking the request.
                     */
                    setTimeout( function() {
                        _.progressiveLazyLoad( tryCount + 1 );
                    }, 500 );

                } else {

                    image
                        .removeAttr( 'data-lazy' )
                        .removeClass( 'slick-loading' )
                        .addClass( 'slick-lazyload-error' );

                    _.$slider.trigger('lazyLoadError', [ _, image, imageSource ]);

                    _.progressiveLazyLoad();

                }

            };

            imageToLoad.src = imageSource;

        } else {

            _.$slider.trigger('allImagesLoaded', [ _ ]);

        }

    };

    Slick.prototype.refresh = function( initializing ) {

        var _ = this, currentSlide, lastVisibleIndex;

        lastVisibleIndex = _.slideCount - _.options.slidesToShow;

        // in non-infinite sliders, we don't want to go past the
        // last visible index.
        if( !_.options.infinite && ( _.currentSlide > lastVisibleIndex )) {
            _.currentSlide = lastVisibleIndex;
        }

        // if less slides than to show, go to start.
        if ( _.slideCount <= _.options.slidesToShow ) {
            _.currentSlide = 0;

        }

        currentSlide = _.currentSlide;

        _.destroy(true);

        $.extend(_, _.initials, { currentSlide: currentSlide });

        _.init();

        if( !initializing ) {

            _.changeSlide({
                data: {
                    message: 'index',
                    index: currentSlide
                }
            }, false);

        }

    };

    Slick.prototype.registerBreakpoints = function() {

        var _ = this, breakpoint, currentBreakpoint, l,
            responsiveSettings = _.options.responsive || null;

        if ( $.type(responsiveSettings) === 'array' && responsiveSettings.length ) {

            _.respondTo = _.options.respondTo || 'window';

            for ( breakpoint in responsiveSettings ) {

                l = _.breakpoints.length-1;

                if (responsiveSettings.hasOwnProperty(breakpoint)) {
                    currentBreakpoint = responsiveSettings[breakpoint].breakpoint;

                    // loop through the breakpoints and cut out any existing
                    // ones with the same breakpoint number, we don't want dupes.
                    while( l >= 0 ) {
                        if( _.breakpoints[l] && _.breakpoints[l] === currentBreakpoint ) {
                            _.breakpoints.splice(l,1);
                        }
                        l--;
                    }

                    _.breakpoints.push(currentBreakpoint);
                    _.breakpointSettings[currentBreakpoint] = responsiveSettings[breakpoint].settings;

                }

            }

            _.breakpoints.sort(function(a, b) {
                return ( _.options.mobileFirst ) ? a-b : b-a;
            });

        }

    };

    Slick.prototype.reinit = function() {

        var _ = this;

        _.$slides =
            _.$slideTrack
                .children(_.options.slide)
                .addClass('slick-slide');

        _.slideCount = _.$slides.length;

        if (_.currentSlide >= _.slideCount && _.currentSlide !== 0) {
            _.currentSlide = _.currentSlide - _.options.slidesToScroll;
        }

        if (_.slideCount <= _.options.slidesToShow) {
            _.currentSlide = 0;
        }

        _.registerBreakpoints();

        _.setProps();
        _.setupInfinite();
        _.buildArrows();
        _.updateArrows();
        _.initArrowEvents();
        _.buildDots();
        _.updateDots();
        _.initDotEvents();
        _.cleanUpSlideEvents();
        _.initSlideEvents();

        _.checkResponsive(false, true);

        if (_.options.focusOnSelect === true) {
            $(_.$slideTrack).children().on('click.slick', _.selectHandler);
        }

        _.setSlideClasses(typeof _.currentSlide === 'number' ? _.currentSlide : 0);

        _.setPosition();
        _.focusHandler();

        _.paused = !_.options.autoplay;
        _.autoPlay();

        _.$slider.trigger('reInit', [_]);

    };

    Slick.prototype.resize = function() {

        var _ = this;

        if ($(window).width() !== _.windowWidth) {
            clearTimeout(_.windowDelay);
            _.windowDelay = window.setTimeout(function() {
                _.windowWidth = $(window).width();
                _.checkResponsive();
                if( !_.unslicked ) { _.setPosition(); }
            }, 50);
        }
    };

    Slick.prototype.removeSlide = Slick.prototype.slickRemove = function(index, removeBefore, removeAll) {

        var _ = this;

        if (typeof(index) === 'boolean') {
            removeBefore = index;
            index = removeBefore === true ? 0 : _.slideCount - 1;
        } else {
            index = removeBefore === true ? --index : index;
        }

        if (_.slideCount < 1 || index < 0 || index > _.slideCount - 1) {
            return false;
        }

        _.unload();

        if (removeAll === true) {
            _.$slideTrack.children().remove();
        } else {
            _.$slideTrack.children(this.options.slide).eq(index).remove();
        }

        _.$slides = _.$slideTrack.children(this.options.slide);

        _.$slideTrack.children(this.options.slide).detach();

        _.$slideTrack.append(_.$slides);

        _.$slidesCache = _.$slides;

        _.reinit();

    };

    Slick.prototype.setCSS = function(position) {

        var _ = this,
            positionProps = {},
            x, y;

        if (_.options.rtl === true) {
            position = -position;
        }
        x = _.positionProp == 'left' ? Math.ceil(position) + 'px' : '0px';
        y = _.positionProp == 'top' ? Math.ceil(position) + 'px' : '0px';

        positionProps[_.positionProp] = position;

        if (_.transformsEnabled === false) {
            _.$slideTrack.css(positionProps);
        } else {
            positionProps = {};
            if (_.cssTransitions === false) {
                positionProps[_.animType] = 'translate(' + x + ', ' + y + ')';
                _.$slideTrack.css(positionProps);
            } else {
                positionProps[_.animType] = 'translate3d(' + x + ', ' + y + ', 0px)';
                _.$slideTrack.css(positionProps);
            }
        }

    };

    Slick.prototype.setDimensions = function() {

        var _ = this;

        if (_.options.vertical === false) {
            if (_.options.centerMode === true) {
                _.$list.css({
                    padding: ('0px ' + _.options.centerPadding)
                });
            }
        } else {
            _.$list.height(_.$slides.first().outerHeight(true) * _.options.slidesToShow);
            if (_.options.centerMode === true) {
                _.$list.css({
                    padding: (_.options.centerPadding + ' 0px')
                });
            }
        }

        _.listWidth = _.$list.width();
        _.listHeight = _.$list.height();


        if (_.options.vertical === false && _.options.variableWidth === false) {
            _.slideWidth = Math.ceil(_.listWidth / _.options.slidesToShow);
            _.$slideTrack.width(Math.ceil((_.slideWidth * _.$slideTrack.children('.slick-slide').length)));

        } else if (_.options.variableWidth === true) {
            _.$slideTrack.width(5000 * _.slideCount);
        } else {
            _.slideWidth = Math.ceil(_.listWidth);
            _.$slideTrack.height(Math.ceil((_.$slides.first().outerHeight(true) * _.$slideTrack.children('.slick-slide').length)));
        }

        var offset = _.$slides.first().outerWidth(true) - _.$slides.first().width();
        if (_.options.variableWidth === false) _.$slideTrack.children('.slick-slide').width(_.slideWidth - offset);

    };

    Slick.prototype.setFade = function() {

        var _ = this,
            targetLeft;

        _.$slides.each(function(index, element) {
            targetLeft = (_.slideWidth * index) * -1;
            if (_.options.rtl === true) {
                $(element).css({
                    position: 'relative',
                    right: targetLeft,
                    top: 0,
                    zIndex: _.options.zIndex - 2,
                    opacity: 0
                });
            } else {
                $(element).css({
                    position: 'relative',
                    left: targetLeft,
                    top: 0,
                    zIndex: _.options.zIndex - 2,
                    opacity: 0
                });
            }
        });

        _.$slides.eq(_.currentSlide).css({
            zIndex: _.options.zIndex - 1,
            opacity: 1
        });

    };

    Slick.prototype.setHeight = function() {

        var _ = this;

        if (_.options.slidesToShow === 1 && _.options.adaptiveHeight === true && _.options.vertical === false) {
            var targetHeight = _.$slides.eq(_.currentSlide).outerHeight(true);
            _.$list.css('height', targetHeight);
        }

    };

    Slick.prototype.setOption =
    Slick.prototype.slickSetOption = function() {

        /**
         * accepts arguments in format of:
         *
         *  - for changing a single option's value:
         *     .slick("setOption", option, value, refresh )
         *
         *  - for changing a set of responsive options:
         *     .slick("setOption", 'responsive', [{}, ...], refresh )
         *
         *  - for updating multiple values at once (not responsive)
         *     .slick("setOption", { 'option': value, ... }, refresh )
         */

        var _ = this, l, item, option, value, refresh = false, type;

        if( $.type( arguments[0] ) === 'object' ) {

            option =  arguments[0];
            refresh = arguments[1];
            type = 'multiple';

        } else if ( $.type( arguments[0] ) === 'string' ) {

            option =  arguments[0];
            value = arguments[1];
            refresh = arguments[2];

            if ( arguments[0] === 'responsive' && $.type( arguments[1] ) === 'array' ) {

                type = 'responsive';

            } else if ( typeof arguments[1] !== 'undefined' ) {

                type = 'single';

            }

        }

        if ( type === 'single' ) {

            _.options[option] = value;


        } else if ( type === 'multiple' ) {

            $.each( option , function( opt, val ) {

                _.options[opt] = val;

            });


        } else if ( type === 'responsive' ) {

            for ( item in value ) {

                if( $.type( _.options.responsive ) !== 'array' ) {

                    _.options.responsive = [ value[item] ];

                } else {

                    l = _.options.responsive.length-1;

                    // loop through the responsive object and splice out duplicates.
                    while( l >= 0 ) {

                        if( _.options.responsive[l].breakpoint === value[item].breakpoint ) {

                            _.options.responsive.splice(l,1);

                        }

                        l--;

                    }

                    _.options.responsive.push( value[item] );

                }

            }

        }

        if ( refresh ) {

            _.unload();
            _.reinit();

        }

    };

    Slick.prototype.setPosition = function() {

        var _ = this;

        _.setDimensions();

        _.setHeight();

        if (_.options.fade === false) {
            _.setCSS(_.getLeft(_.currentSlide));
        } else {
            _.setFade();
        }

        _.$slider.trigger('setPosition', [_]);

    };

    Slick.prototype.setProps = function() {

        var _ = this,
            bodyStyle = document.body.style;

        _.positionProp = _.options.vertical === true ? 'top' : 'left';

        if (_.positionProp === 'top') {
            _.$slider.addClass('slick-vertical');
        } else {
            _.$slider.removeClass('slick-vertical');
        }

        if (bodyStyle.WebkitTransition !== undefined ||
            bodyStyle.MozTransition !== undefined ||
            bodyStyle.msTransition !== undefined) {
            if (_.options.useCSS === true) {
                _.cssTransitions = true;
            }
        }

        if ( _.options.fade ) {
            if ( typeof _.options.zIndex === 'number' ) {
                if( _.options.zIndex < 3 ) {
                    _.options.zIndex = 3;
                }
            } else {
                _.options.zIndex = _.defaults.zIndex;
            }
        }

        if (bodyStyle.OTransform !== undefined) {
            _.animType = 'OTransform';
            _.transformType = '-o-transform';
            _.transitionType = 'OTransition';
            if (bodyStyle.perspectiveProperty === undefined && bodyStyle.webkitPerspective === undefined) _.animType = false;
        }
        if (bodyStyle.MozTransform !== undefined) {
            _.animType = 'MozTransform';
            _.transformType = '-moz-transform';
            _.transitionType = 'MozTransition';
            if (bodyStyle.perspectiveProperty === undefined && bodyStyle.MozPerspective === undefined) _.animType = false;
        }
        if (bodyStyle.webkitTransform !== undefined) {
            _.animType = 'webkitTransform';
            _.transformType = '-webkit-transform';
            _.transitionType = 'webkitTransition';
            if (bodyStyle.perspectiveProperty === undefined && bodyStyle.webkitPerspective === undefined) _.animType = false;
        }
        if (bodyStyle.msTransform !== undefined) {
            _.animType = 'msTransform';
            _.transformType = '-ms-transform';
            _.transitionType = 'msTransition';
            if (bodyStyle.msTransform === undefined) _.animType = false;
        }
        if (bodyStyle.transform !== undefined && _.animType !== false) {
            _.animType = 'transform';
            _.transformType = 'transform';
            _.transitionType = 'transition';
        }
        _.transformsEnabled = _.options.useTransform && (_.animType !== null && _.animType !== false);
    };


    Slick.prototype.setSlideClasses = function(index) {

        var _ = this,
            centerOffset, allSlides, indexOffset, remainder;

        allSlides = _.$slider
            .find('.slick-slide')
            .removeClass('slick-active slick-center slick-current')
            .attr('aria-hidden', 'true');

        _.$slides
            .eq(index)
            .addClass('slick-current');

        if (_.options.centerMode === true) {

            var evenCoef = _.options.slidesToShow % 2 === 0 ? 1 : 0;

            centerOffset = Math.floor(_.options.slidesToShow / 2);

            if (_.options.infinite === true) {

                if (index >= centerOffset && index <= (_.slideCount - 1) - centerOffset) {
                    _.$slides
                        .slice(index - centerOffset + evenCoef, index + centerOffset + 1)
                        .addClass('slick-active')
                        .attr('aria-hidden', 'false');

                } else {

                    indexOffset = _.options.slidesToShow + index;
                    allSlides
                        .slice(indexOffset - centerOffset + 1 + evenCoef, indexOffset + centerOffset + 2)
                        .addClass('slick-active')
                        .attr('aria-hidden', 'false');

                }

                if (index === 0) {

                    allSlides
                        .eq(allSlides.length - 1 - _.options.slidesToShow)
                        .addClass('slick-center');

                } else if (index === _.slideCount - 1) {

                    allSlides
                        .eq(_.options.slidesToShow)
                        .addClass('slick-center');

                }

            }

            _.$slides
                .eq(index)
                .addClass('slick-center');

        } else {

            if (index >= 0 && index <= (_.slideCount - _.options.slidesToShow)) {

                _.$slides
                    .slice(index, index + _.options.slidesToShow)
                    .addClass('slick-active')
                    .attr('aria-hidden', 'false');

            } else if (allSlides.length <= _.options.slidesToShow) {

                allSlides
                    .addClass('slick-active')
                    .attr('aria-hidden', 'false');

            } else {

                remainder = _.slideCount % _.options.slidesToShow;
                indexOffset = _.options.infinite === true ? _.options.slidesToShow + index : index;

                if (_.options.slidesToShow == _.options.slidesToScroll && (_.slideCount - index) < _.options.slidesToShow) {

                    allSlides
                        .slice(indexOffset - (_.options.slidesToShow - remainder), indexOffset + remainder)
                        .addClass('slick-active')
                        .attr('aria-hidden', 'false');

                } else {

                    allSlides
                        .slice(indexOffset, indexOffset + _.options.slidesToShow)
                        .addClass('slick-active')
                        .attr('aria-hidden', 'false');

                }

            }

        }

        if (_.options.lazyLoad === 'ondemand' || _.options.lazyLoad === 'anticipated') {
            _.lazyLoad();
        }
    };

    Slick.prototype.setupInfinite = function() {

        var _ = this,
            i, slideIndex, infiniteCount;

        if (_.options.fade === true) {
            _.options.centerMode = false;
        }

        if (_.options.infinite === true && _.options.fade === false) {

            slideIndex = null;

            if (_.slideCount > _.options.slidesToShow) {

                if (_.options.centerMode === true) {
                    infiniteCount = _.options.slidesToShow + 1;
                } else {
                    infiniteCount = _.options.slidesToShow;
                }

                for (i = _.slideCount; i > (_.slideCount -
                        infiniteCount); i -= 1) {
                    slideIndex = i - 1;
                    $(_.$slides[slideIndex]).clone(true).attr('id', '')
                        .attr('data-slick-index', slideIndex - _.slideCount)
                        .prependTo(_.$slideTrack).addClass('slick-cloned');
                }
                for (i = 0; i < infiniteCount  + _.slideCount; i += 1) {
                    slideIndex = i;
                    $(_.$slides[slideIndex]).clone(true).attr('id', '')
                        .attr('data-slick-index', slideIndex + _.slideCount)
                        .appendTo(_.$slideTrack).addClass('slick-cloned');
                }
                _.$slideTrack.find('.slick-cloned').find('[id]').each(function() {
                    $(this).attr('id', '');
                });

            }

        }

    };

    Slick.prototype.interrupt = function( toggle ) {

        var _ = this;

        if( !toggle ) {
            _.autoPlay();
        }
        _.interrupted = toggle;

    };

    Slick.prototype.selectHandler = function(event) {

        var _ = this;

        var targetElement =
            $(event.target).is('.slick-slide') ?
                $(event.target) :
                $(event.target).parents('.slick-slide');

        var index = parseInt(targetElement.attr('data-slick-index'));

        if (!index) index = 0;

        if (_.slideCount <= _.options.slidesToShow) {

            _.slideHandler(index, false, true);
            return;

        }

        _.slideHandler(index);

    };

    Slick.prototype.slideHandler = function(index, sync, dontAnimate) {

        var targetSlide, animSlide, oldSlide, slideLeft, targetLeft = null,
            _ = this, navTarget;

        sync = sync || false;

        if (_.animating === true && _.options.waitForAnimate === true) {
            return;
        }

        if (_.options.fade === true && _.currentSlide === index) {
            return;
        }

        if (sync === false) {
            _.asNavFor(index);
        }

        targetSlide = index;
        targetLeft = _.getLeft(targetSlide);
        slideLeft = _.getLeft(_.currentSlide);

        _.currentLeft = _.swipeLeft === null ? slideLeft : _.swipeLeft;

        if (_.options.infinite === false && _.options.centerMode === false && (index < 0 || index > _.getDotCount() * _.options.slidesToScroll)) {
            if (_.options.fade === false) {
                targetSlide = _.currentSlide;
                if (dontAnimate !== true && _.slideCount > _.options.slidesToShow) {
                    _.animateSlide(slideLeft, function() {
                        _.postSlide(targetSlide);
                    });
                } else {
                    _.postSlide(targetSlide);
                }
            }
            return;
        } else if (_.options.infinite === false && _.options.centerMode === true && (index < 0 || index > (_.slideCount - _.options.slidesToScroll))) {
            if (_.options.fade === false) {
                targetSlide = _.currentSlide;
                if (dontAnimate !== true && _.slideCount > _.options.slidesToShow) {
                    _.animateSlide(slideLeft, function() {
                        _.postSlide(targetSlide);
                    });
                } else {
                    _.postSlide(targetSlide);
                }
            }
            return;
        }

        if ( _.options.autoplay ) {
            clearInterval(_.autoPlayTimer);
        }

        if (targetSlide < 0) {
            if (_.slideCount % _.options.slidesToScroll !== 0) {
                animSlide = _.slideCount - (_.slideCount % _.options.slidesToScroll);
            } else {
                animSlide = _.slideCount + targetSlide;
            }
        } else if (targetSlide >= _.slideCount) {
            if (_.slideCount % _.options.slidesToScroll !== 0) {
                animSlide = 0;
            } else {
                animSlide = targetSlide - _.slideCount;
            }
        } else {
            animSlide = targetSlide;
        }

        _.animating = true;

        _.$slider.trigger('beforeChange', [_, _.currentSlide, animSlide]);

        oldSlide = _.currentSlide;
        _.currentSlide = animSlide;

        _.setSlideClasses(_.currentSlide);

        if ( _.options.asNavFor ) {

            navTarget = _.getNavTarget();
            navTarget = navTarget.slick('getSlick');

            if ( navTarget.slideCount <= navTarget.options.slidesToShow ) {
                navTarget.setSlideClasses(_.currentSlide);
            }

        }

        _.updateDots();
        _.updateArrows();

        if (_.options.fade === true) {
            if (dontAnimate !== true) {

                _.fadeSlideOut(oldSlide);

                _.fadeSlide(animSlide, function() {
                    _.postSlide(animSlide);
                });

            } else {
                _.postSlide(animSlide);
            }
            _.animateHeight();
            return;
        }

        if (dontAnimate !== true && _.slideCount > _.options.slidesToShow) {
            _.animateSlide(targetLeft, function() {
                _.postSlide(animSlide);
            });
        } else {
            _.postSlide(animSlide);
        }

    };

    Slick.prototype.startLoad = function() {

        var _ = this;

        if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) {

            _.$prevArrow.hide();
            _.$nextArrow.hide();

        }

        if (_.options.dots === true && _.slideCount > _.options.slidesToShow) {

            _.$dots.hide();

        }

        _.$slider.addClass('slick-loading');

    };

    Slick.prototype.swipeDirection = function() {

        var xDist, yDist, r, swipeAngle, _ = this;

        xDist = _.touchObject.startX - _.touchObject.curX;
        yDist = _.touchObject.startY - _.touchObject.curY;
        r = Math.atan2(yDist, xDist);

        swipeAngle = Math.round(r * 180 / Math.PI);
        if (swipeAngle < 0) {
            swipeAngle = 360 - Math.abs(swipeAngle);
        }

        if ((swipeAngle <= 45) && (swipeAngle >= 0)) {
            return (_.options.rtl === false ? 'left' : 'right');
        }
        if ((swipeAngle <= 360) && (swipeAngle >= 315)) {
            return (_.options.rtl === false ? 'left' : 'right');
        }
        if ((swipeAngle >= 135) && (swipeAngle <= 225)) {
            return (_.options.rtl === false ? 'right' : 'left');
        }
        if (_.options.verticalSwiping === true) {
            if ((swipeAngle >= 35) && (swipeAngle <= 135)) {
                return 'down';
            } else {
                return 'up';
            }
        }

        return 'vertical';

    };

    Slick.prototype.swipeEnd = function(event) {

        var _ = this,
            slideCount,
            direction;

        _.dragging = false;
        _.swiping = false;

        if (_.scrolling) {
            _.scrolling = false;
            return false;
        }

        _.interrupted = false;
        _.shouldClick = ( _.touchObject.swipeLength > 10 ) ? false : true;

        if ( _.touchObject.curX === undefined ) {
            return false;
        }

        if ( _.touchObject.edgeHit === true ) {
            _.$slider.trigger('edge', [_, _.swipeDirection() ]);
        }

        if ( _.touchObject.swipeLength >= _.touchObject.minSwipe ) {

            direction = _.swipeDirection();

            switch ( direction ) {

                case 'left':
                case 'down':

                    slideCount =
                        _.options.swipeToSlide ?
                            _.checkNavigable( _.currentSlide + _.getSlideCount() ) :
                            _.currentSlide + _.getSlideCount();

                    _.currentDirection = 0;

                    break;

                case 'right':
                case 'up':

                    slideCount =
                        _.options.swipeToSlide ?
                            _.checkNavigable( _.currentSlide - _.getSlideCount() ) :
                            _.currentSlide - _.getSlideCount();

                    _.currentDirection = 1;

                    break;

                default:


            }

            if( direction != 'vertical' ) {

                _.slideHandler( slideCount );
                _.touchObject = {};
                _.$slider.trigger('swipe', [_, direction ]);

            }

        } else {

            if ( _.touchObject.startX !== _.touchObject.curX ) {

                _.slideHandler( _.currentSlide );
                _.touchObject = {};

            }

        }

    };

    Slick.prototype.swipeHandler = function(event) {

        var _ = this;

        if ((_.options.swipe === false) || ('ontouchend' in document && _.options.swipe === false)) {
            return;
        } else if (_.options.draggable === false && event.type.indexOf('mouse') !== -1) {
            return;
        }

        _.touchObject.fingerCount = event.originalEvent && event.originalEvent.touches !== undefined ?
            event.originalEvent.touches.length : 1;

        _.touchObject.minSwipe = _.listWidth / _.options
            .touchThreshold;

        if (_.options.verticalSwiping === true) {
            _.touchObject.minSwipe = _.listHeight / _.options
                .touchThreshold;
        }

        switch (event.data.action) {

            case 'start':
                _.swipeStart(event);
                break;

            case 'move':
                _.swipeMove(event);
                break;

            case 'end':
                _.swipeEnd(event);
                break;

        }

    };

    Slick.prototype.swipeMove = function(event) {

        var _ = this,
            edgeWasHit = false,
            curLeft, swipeDirection, swipeLength, positionOffset, touches, verticalSwipeLength;

        touches = event.originalEvent !== undefined ? event.originalEvent.touches : null;

        if (!_.dragging || _.scrolling || touches && touches.length !== 1) {
            return false;
        }

        curLeft = _.getLeft(_.currentSlide);

        _.touchObject.curX = touches !== undefined ? touches[0].pageX : event.clientX;
        _.touchObject.curY = touches !== undefined ? touches[0].pageY : event.clientY;

        _.touchObject.swipeLength = Math.round(Math.sqrt(
            Math.pow(_.touchObject.curX - _.touchObject.startX, 2)));

        verticalSwipeLength = Math.round(Math.sqrt(
            Math.pow(_.touchObject.curY - _.touchObject.startY, 2)));

        if (!_.options.verticalSwiping && !_.swiping && verticalSwipeLength > 4) {
            _.scrolling = true;
            return false;
        }

        if (_.options.verticalSwiping === true) {
            _.touchObject.swipeLength = verticalSwipeLength;
        }

        swipeDirection = _.swipeDirection();

        if (event.originalEvent !== undefined && _.touchObject.swipeLength > 4) {
            _.swiping = true;
            event.preventDefault();
        }

        positionOffset = (_.options.rtl === false ? 1 : -1) * (_.touchObject.curX > _.touchObject.startX ? 1 : -1);
        if (_.options.verticalSwiping === true) {
            positionOffset = _.touchObject.curY > _.touchObject.startY ? 1 : -1;
        }


        swipeLength = _.touchObject.swipeLength;

        _.touchObject.edgeHit = false;

        if (_.options.infinite === false) {
            if ((_.currentSlide === 0 && swipeDirection === 'right') || (_.currentSlide >= _.getDotCount() && swipeDirection === 'left')) {
                swipeLength = _.touchObject.swipeLength * _.options.edgeFriction;
                _.touchObject.edgeHit = true;
            }
        }

        if (_.options.vertical === false) {
            _.swipeLeft = curLeft + swipeLength * positionOffset;
        } else {
            _.swipeLeft = curLeft + (swipeLength * (_.$list.height() / _.listWidth)) * positionOffset;
        }
        if (_.options.verticalSwiping === true) {
            _.swipeLeft = curLeft + swipeLength * positionOffset;
        }

        if (_.options.fade === true || _.options.touchMove === false) {
            return false;
        }

        if (_.animating === true) {
            _.swipeLeft = null;
            return false;
        }

        _.setCSS(_.swipeLeft);

    };

    Slick.prototype.swipeStart = function(event) {

        var _ = this,
            touches;

        _.interrupted = true;

        if (_.touchObject.fingerCount !== 1 || _.slideCount <= _.options.slidesToShow) {
            _.touchObject = {};
            return false;
        }

        if (event.originalEvent !== undefined && event.originalEvent.touches !== undefined) {
            touches = event.originalEvent.touches[0];
        }

        _.touchObject.startX = _.touchObject.curX = touches !== undefined ? touches.pageX : event.clientX;
        _.touchObject.startY = _.touchObject.curY = touches !== undefined ? touches.pageY : event.clientY;

        _.dragging = true;

    };

    Slick.prototype.unfilterSlides = Slick.prototype.slickUnfilter = function() {

        var _ = this;

        if (_.$slidesCache !== null) {

            _.unload();

            _.$slideTrack.children(this.options.slide).detach();

            _.$slidesCache.appendTo(_.$slideTrack);

            _.reinit();

        }

    };

    Slick.prototype.unload = function() {

        var _ = this;

        $('.slick-cloned', _.$slider).remove();

        if (_.$dots) {
            _.$dots.remove();
        }

        if (_.$prevArrow && _.htmlExpr.test(_.options.prevArrow)) {
            _.$prevArrow.remove();
        }

        if (_.$nextArrow && _.htmlExpr.test(_.options.nextArrow)) {
            _.$nextArrow.remove();
        }

        _.$slides
            .removeClass('slick-slide slick-active slick-visible slick-current')
            .attr('aria-hidden', 'true')
            .css('width', '');

    };

    Slick.prototype.unslick = function(fromBreakpoint) {

        var _ = this;
        _.$slider.trigger('unslick', [_, fromBreakpoint]);
        _.destroy();

    };

    Slick.prototype.updateArrows = function() {

        var _ = this,
            centerOffset;

        centerOffset = Math.floor(_.options.slidesToShow / 2);

        if ( _.options.arrows === true &&
            _.slideCount > _.options.slidesToShow &&
            !_.options.infinite ) {

            _.$prevArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');
            _.$nextArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');

            if (_.currentSlide === 0) {

                _.$prevArrow.addClass('slick-disabled').attr('aria-disabled', 'true');
                _.$nextArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');

            } else if (_.currentSlide >= _.slideCount - _.options.slidesToShow && _.options.centerMode === false) {

                _.$nextArrow.addClass('slick-disabled').attr('aria-disabled', 'true');
                _.$prevArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');

            } else if (_.currentSlide >= _.slideCount - 1 && _.options.centerMode === true) {

                _.$nextArrow.addClass('slick-disabled').attr('aria-disabled', 'true');
                _.$prevArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');

            }

        }

    };

    Slick.prototype.updateDots = function() {

        var _ = this;

        if (_.$dots !== null) {

            _.$dots
                .find('li')
                    .removeClass('slick-active')
                    .end();

            _.$dots
                .find('li')
                .eq(Math.floor(_.currentSlide / _.options.slidesToScroll))
                .addClass('slick-active');

        }

    };

    Slick.prototype.visibility = function() {

        var _ = this;

        if ( _.options.autoplay ) {

            if ( document[_.hidden] ) {

                _.interrupted = true;

            } else {

                _.interrupted = false;

            }

        }

    };

    $.fn.slick = function() {
        var _ = this,
            opt = arguments[0],
            args = Array.prototype.slice.call(arguments, 1),
            l = _.length,
            i,
            ret;
        for (i = 0; i < l; i++) {
            if (typeof opt == 'object' || typeof opt == 'undefined')
                _[i].slick = new Slick(_[i], opt);
            else
                ret = _[i].slick[opt].apply(_[i].slick, args);
            if (typeof ret != 'undefined') return ret;
        }
        return _;
    };

}));;
/*
 Sticky-kit v1.1.2 | WTFPL | Leaf Corcoran 2015 | http://leafo.net
*/
(function(){var b,f;b=this.jQuery||window.jQuery;f=b(window);b.fn.stick_in_parent=function(d){var A,w,J,n,B,K,p,q,k,E,t;null==d&&(d={});t=d.sticky_class;B=d.inner_scrolling;E=d.recalc_every;k=d.parent;q=d.offset_top;p=d.spacer;w=d.bottoming;null==q&&(q=0);null==k&&(k=void 0);null==B&&(B=!0);null==t&&(t="s-stuck");A=b(document);null==w&&(w=!0);J=function(a,d,n,C,F,u,r,G){var v,H,m,D,I,c,g,x,y,z,h,l;if(!a.data("sticky_kit")){a.data("sticky_kit",!0);I=A.height();g=a.parent();null!=k&&(g=g.closest(k));
if(!g.length)throw"failed to find stick parent";v=m=!1;(h=null!=p?p&&a.closest(p):b("<div />"))&&h.css("position",a.css("position"));x=function(){var c,f,e;if(!G&&(I=A.height(),c=parseInt(g.css("border-top-width"),10),f=parseInt(g.css("padding-top"),10),d=parseInt(g.css("padding-bottom"),10),n=g.offset().top+c+f,C=g.height(),m&&(v=m=!1,null==p&&(a.insertAfter(h),h.detach()),a.css({position:"",top:"",width:"",bottom:""}).removeClass(t),e=!0),F=a.offset().top-(parseInt(a.css("margin-top"),10)||0)-q,
u=a.outerHeight(!0),r=a.css("float"),h&&h.css({width:a.outerWidth(!0),height:u,display:a.css("display"),"vertical-align":a.css("vertical-align"),"float":r}),e))return l()};x();if(u!==C)return D=void 0,c=q,z=E,l=function(){var b,l,e,k;if(!G&&(e=!1,null!=z&&(--z,0>=z&&(z=E,x(),e=!0)),e||A.height()===I||x(),e=f.scrollTop(),null!=D&&(l=e-D),D=e,m?(w&&(k=e+u+c>C+n,v&&!k&&(v=!1,a.css({position:"fixed",bottom:"",top:c}).trigger("sticky_kit:unbottom"))),e<F&&(m=!1,c=q,null==p&&("left"!==r&&"right"!==r||a.insertAfter(h),
h.detach()),b={position:"",width:"",top:""},a.css(b).removeClass(t).trigger("sticky_kit:unstick")),B&&(b=f.height(),u+q>b&&!v&&(c-=l,c=Math.max(b-u,c),c=Math.min(q,c),m&&a.css({top:c+"px"})))):e>F&&(m=!0,b={position:"fixed",top:c},b.width="border-box"===a.css("box-sizing")?a.outerWidth()+"px":a.width()+"px",a.css(b).addClass(t),null==p&&(a.after(h),"left"!==r&&"right"!==r||h.append(a)),a.trigger("sticky_kit:stick")),m&&w&&(null==k&&(k=e+u+c>C+n),!v&&k)))return v=!0,"static"===g.css("position")&&g.css({position:"relative"}),
a.css({position:"absolute",bottom:d,top:"auto"}).trigger("sticky_kit:bottom")},y=function(){x();return l()},H=function(){G=!0;f.off("touchmove",l);f.off("scroll",l);f.off("resize",y);b(document.body).off("sticky_kit:recalc",y);a.off("sticky_kit:detach",H);a.removeData("sticky_kit");a.css({position:"",bottom:"",top:"",width:""});g.position("position","");if(m)return null==p&&("left"!==r&&"right"!==r||a.insertAfter(h),h.remove()),a.removeClass(t)},f.on("touchmove",l),f.on("scroll",l),f.on("resize",
y),b(document.body).on("sticky_kit:recalc",y),a.on("sticky_kit:detach",H),setTimeout(l,0)}};n=0;for(K=this.length;n<K;n++)d=this[n],J(b(d));return this}}).call(this);
;
/*!
 * @copyright Copyright (c) 2017 IcoMoon.io
 * @license   Licensed under MIT license
 *            See https://github.com/Keyamoon/svgxuse
 * @version   1.2.6
 */
/*jslint browser: true */
/*global XDomainRequest, MutationObserver, window */
(function () {
    "use strict";
    if (typeof window !== "undefined" && window.addEventListener) {
        var cache = Object.create(null); // holds xhr objects to prevent multiple requests
        var checkUseElems;
        var tid; // timeout id
        var debouncedCheck = function () {
            clearTimeout(tid);
            tid = setTimeout(checkUseElems, 100);
        };
        var unobserveChanges = function () {
            return;
        };
        var observeChanges = function () {
            var observer;
            window.addEventListener("resize", debouncedCheck, false);
            window.addEventListener("orientationchange", debouncedCheck, false);
            if (window.MutationObserver) {
                observer = new MutationObserver(debouncedCheck);
                observer.observe(document.documentElement, {
                    childList: true,
                    subtree: true,
                    attributes: true
                });
                unobserveChanges = function () {
                    try {
                        observer.disconnect();
                        window.removeEventListener("resize", debouncedCheck, false);
                        window.removeEventListener("orientationchange", debouncedCheck, false);
                    } catch (ignore) {}
                };
            } else {
                document.documentElement.addEventListener("DOMSubtreeModified", debouncedCheck, false);
                unobserveChanges = function () {
                    document.documentElement.removeEventListener("DOMSubtreeModified", debouncedCheck, false);
                    window.removeEventListener("resize", debouncedCheck, false);
                    window.removeEventListener("orientationchange", debouncedCheck, false);
                };
            }
        };
        var createRequest = function (url) {
            // In IE 9, cross origin requests can only be sent using XDomainRequest.
            // XDomainRequest would fail if CORS headers are not set.
            // Therefore, XDomainRequest should only be used with cross origin requests.
            function getOrigin(loc) {
                var a;
                if (loc.protocol !== undefined) {
                    a = loc;
                } else {
                    a = document.createElement("a");
                    a.href = loc;
                }
                return a.protocol.replace(/:/g, "") + a.host;
            }
            var Request;
            var origin;
            var origin2;
            if (window.XMLHttpRequest) {
                Request = new XMLHttpRequest();
                origin = getOrigin(location);
                origin2 = getOrigin(url);
                if (Request.withCredentials === undefined && origin2 !== "" && origin2 !== origin) {
                    Request = XDomainRequest || undefined;
                } else {
                    Request = XMLHttpRequest;
                }
            }
            return Request;
        };
        var xlinkNS = "http://www.w3.org/1999/xlink";
        checkUseElems = function () {
            var base;
            var bcr;
            var fallback = ""; // optional fallback URL in case no base path to SVG file was given and no symbol definition was found.
            var hash;
            var href;
            var i;
            var inProgressCount = 0;
            var isHidden;
            var Request;
            var url;
            var uses;
            var xhr;
            function observeIfDone() {
                // If done with making changes, start watching for chagnes in DOM again
                inProgressCount -= 1;
                if (inProgressCount === 0) { // if all xhrs were resolved
                    unobserveChanges(); // make sure to remove old handlers
                    observeChanges(); // watch for changes to DOM
                }
            }
            function attrUpdateFunc(spec) {
                return function () {
                    if (cache[spec.base] !== true) {
                        spec.useEl.setAttributeNS(xlinkNS, "xlink:href", "#" + spec.hash);
                        if (spec.useEl.hasAttribute("href")) {
                            spec.useEl.setAttribute("href", "#" + spec.hash);
                        }
                    }
                };
            }
            function onloadFunc(xhr) {
                return function () {
                    var body = document.body;
                    var x = document.createElement("x");
                    var svg;
                    xhr.onload = null;
                    x.innerHTML = xhr.responseText;
                    svg = x.getElementsByTagName("svg")[0];
                    if (svg) {
                        svg.setAttribute("aria-hidden", "true");
                        svg.style.position = "absolute";
                        svg.style.width = 0;
                        svg.style.height = 0;
                        svg.style.overflow = "hidden";
                        body.insertBefore(svg, body.firstChild);
                    }
                    observeIfDone();
                };
            }
            function onErrorTimeout(xhr) {
                return function () {
                    xhr.onerror = null;
                    xhr.ontimeout = null;
                    observeIfDone();
                };
            }
            unobserveChanges(); // stop watching for changes to DOM
            // find all use elements
            uses = document.getElementsByTagName("use");
            for (i = 0; i < uses.length; i += 1) {
                try {
                    bcr = uses[i].getBoundingClientRect();
                } catch (ignore) {
                    // failed to get bounding rectangle of the use element
                    bcr = false;
                }
                href = uses[i].getAttribute("href")
                        || uses[i].getAttributeNS(xlinkNS, "href")
                        || uses[i].getAttribute("xlink:href");
                if (href && href.split) {
                    url = href.split("#");
                } else {
                    url = ["", ""];
                }
                base = url[0];
                hash = url[1];
                isHidden = bcr && bcr.left === 0 && bcr.right === 0 && bcr.top === 0 && bcr.bottom === 0;
                if (bcr && bcr.width === 0 && bcr.height === 0 && !isHidden) {
                    // the use element is empty
                    // if there is a reference to an external SVG, try to fetch it
                    // use the optional fallback URL if there is no reference to an external SVG
                    if (fallback && !base.length && hash && !document.getElementById(hash)) {
                        base = fallback;
                    }
                    if (uses[i].hasAttribute("href")) {
                        uses[i].setAttributeNS(xlinkNS, "xlink:href", href);
                    }
                    if (base.length) {
                        // schedule updating xlink:href
                        xhr = cache[base];
                        if (xhr !== true) {
                            // true signifies that prepending the SVG was not required
                            setTimeout(attrUpdateFunc({
                                useEl: uses[i],
                                base: base,
                                hash: hash
                            }), 0);
                        }
                        if (xhr === undefined) {
                            Request = createRequest(base);
                            if (Request !== undefined) {
                                xhr = new Request();
                                cache[base] = xhr;
                                xhr.onload = onloadFunc(xhr);
                                xhr.onerror = onErrorTimeout(xhr);
                                xhr.ontimeout = onErrorTimeout(xhr);
                                xhr.open("GET", base);
                                xhr.send();
                                inProgressCount += 1;
                            }
                        }
                    }
                } else {
                    if (!isHidden) {
                        if (cache[base] === undefined) {
                            // remember this URL if the use element was not empty and no request was sent
                            cache[base] = true;
                        } else if (cache[base].onload) {
                            // if it turns out that prepending the SVG is not necessary,
                            // abort the in-progress xhr.
                            cache[base].abort();
                            delete cache[base].onload;
                            cache[base] = true;
                        }
                    } else if (base.length && cache[base]) {
                        setTimeout(attrUpdateFunc({
                            useEl: uses[i],
                            base: base,
                            hash: hash
                        }), 0);
                    }
                }
            }
            uses = "";
            inProgressCount += 1;
            observeIfDone();
        };
        var winLoad;
        winLoad = function () {
            window.removeEventListener("load", winLoad, false); // to prevent memory leaks
            tid = setTimeout(checkUseElems, 0);
        };
        if (document.readyState !== "complete") {
            // The load event fires when all resources have finished loading, which allows detecting whether SVG use elements are empty.
            window.addEventListener("load", winLoad, false);
        } else {
            // No need to add a listener if the document is already loaded, initialize immediately.
            winLoad();
        }
    }
}());;
/*

	Name:	  frend.co
	Version:  1.0
 	Url:	  https://github.com/frend/frend.co

	<section class="tabs__wrapper js-tabs">
		<ul class="tabs__list">
			<li class="tabs__item">
				<a class="tabs__link" id="tab1" href="#panel1">Tab 1 <span class="vh">(niet actief)</span> </a>
			</li>
			<li class="tabs__item">
				<a class="tabs__link" id="tab2" href="#panel2">Tab 2 <span class="vh">(niet actief)</span> </a>
			</li>
		</ul>
		<article class="tabs__panel" id="panel1">
			<h3>Tab panel 1</h3>
			<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
		</article>
		<article class="tabs__panel" id="panel2">
			<h3>Tab panel 2</h3>
			<p>Mauris rhoncus commodo sapien, eu porttitor libero gravida at. Maecenas a dapibus lorem.</p>
		</article>
	</section>

	<script src="/scripts/perplex/tabs.js"></script>
	<script>var myTabs = Tabs({selector:'.js-tabs'}); </script>

*/

'use strict';

// Polyfill matches as per https://github.com/jonathantneal/closest

Element.prototype.matches = Element.prototype.matches || Element.prototype.mozMatchesSelector || Element.prototype.msMatchesSelector || Element.prototype.oMatchesSelector || Element.prototype.webkitMatchesSelector;

/**
 * @param {object} options Object containing configuration overrides
 */
var Tabs = function Tabs() {
    var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
	    _ref$selector = _ref.selector,
	    selector = _ref$selector === undefined ? '.js-tabs' : _ref$selector,
	    _ref$tablistSelector = _ref.tablistSelector,
	    tablistSelector = _ref$tablistSelector === undefined ? '.tabs__list' : _ref$tablistSelector,
	    _ref$tabpanelSelector = _ref.tabpanelSelector,
	    tabpanelSelector = _ref$tabpanelSelector === undefined ? '.tabs__panel' : _ref$tabpanelSelector,
	    _ref$tabsReadyClass = _ref.tabsReadyClass,
	    tabsReadyClass = _ref$tabsReadyClass === undefined ? 'tabs--ready' : _ref$tabsReadyClass;

    // CONSTANTS
    var doc = document;
    var docEl = doc.documentElement;
    var _q = function _q(el) {
        var ctx = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : doc;
        return [].slice.call(ctx.querySelectorAll(el));
    };

    // SUPPORTS
    if (!('querySelector' in doc) || !('addEventListener' in window) || !docEl.classList) return;

    // SETUP
    // set tab element NodeList
    var tabContainers = _q(selector);

    //	UTILS
    function _closest(el, selector) {
        while (el) {
            if (el.matches(selector)) break;
            el = el.parentElement;
        }
        return el;
    }

    // A11Y
    function _addA11y(tabContainer) {
        // get tab elements
        var tabLists = _q(tablistSelector, tabContainer);
        var tabListItems = _q(tablistSelector + ' li', tabContainer);
        var tabs = _q(tablistSelector + ' a', tabContainer);
        var tabpanels = _q(tabpanelSelector, tabContainer);

        // add roles, properties, states
        tabLists.forEach(function (tabList) {
            tabList.setAttribute('role', 'tablist');
        });

        tabListItems.forEach(function (tabItem) {
            tabItem.setAttribute('role', 'presentation');
        });

        tabs.forEach(function (tab) {
            tab.setAttribute('role', 'tab');
            tab.setAttribute('aria-controls', tab.hash.substring(1));
        });

        tabpanels.forEach(function (tabpanel, i) {
            tabpanel.setAttribute('role', 'tabpanel');
            tabpanel.setAttribute('aria-labelledby', tabs[i].id);
            // make first child of tabpanel focusable if available
            tabpanel.setAttribute('tabindex', 0);
        });
    }
    function _removeA11y(tabContainer) {
        // get tab elements
        var tabLists = _q(tablistSelector, tabContainer);
        var tabListItems = _q(tablistSelector + ' li', tabContainer);
        var tabs = _q(tablistSelector + ' a', tabContainer);
        var tabpanels = _q(tabpanelSelector, tabContainer);

        // remove roles, properties, states
        tabLists.forEach(function (tabList) {
            tabList.removeAttribute('role');
        });

        tabListItems.forEach(function (tabItem) {
            tabItem.removeAttribute('role');
        });

        tabs.forEach(function (tab) {
            tab.removeAttribute('role');
            tab.removeAttribute('aria-controls');
            tab.removeAttribute('aria-selected');
            tab.removeAttribute('tabindex');
        });

        tabpanels.forEach(function (tabpanel) {
            tabpanel.removeAttribute('role');
            tabpanel.removeAttribute('aria-hidden');
            tabpanel.removeAttribute('aria-labelledby');
            // remove first child focusability if present
            tabpanel.removeAttribute('tabindex');
        });
    }

    // ACTIONS
    function _showTab(target) {
        var giveFocus = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;

        // get context of tab container
        var thisContainer = _closest(target, selector);
        var siblingTabs = _q(tablistSelector + ' a', thisContainer);
        var siblingTabpanels = _q(tabpanelSelector, thisContainer);

        // set inactives
        siblingTabs.forEach(function (tab) {
            tab.setAttribute('tabindex', -1);
            tab.removeAttribute('aria-selected');
        });
        siblingTabpanels.forEach(function (tabpanel) {
            tabpanel.setAttribute('aria-hidden', 'true');
        });

        // set actives and focus
        target.setAttribute('tabindex', 0);
        target.setAttribute('aria-selected', 'true');
        if (giveFocus) target.focus();
        doc.getElementById(target.getAttribute('aria-controls')).removeAttribute('aria-hidden');
    }

    // EVENTS
    function _eventTabClick(e) {
        _showTab(e.target);
        e.preventDefault(); // look into remove id/settimeout/reinstate id as an alternative to preventDefault
    }

    function _eventTabKeydown(e) {
        // collect tab targets, and their parents' prev/next (or first/last)
        var currentTab = e.currentTarget;
        var tablist = _closest(currentTab, tablistSelector);
        var previousTabItem = currentTab.parentNode.previousElementSibling || tablist.lastElementChild;
        var nextTabItem = currentTab.parentNode.nextElementSibling || tablist.firstElementChild;

        // don't catch key events when ⌘ or Alt modifier is present
        if (e.metaKey || e.altKey) return;

        // catch left/right and up/down arrow key events
        // if new next/prev tab available, show it by passing tab anchor to _showTab method
        switch (e.keyCode) {
            case 37:
            case 38:
                _showTab(_q('[role="tab"]', previousTabItem)[0]);
                e.preventDefault();
                break;
            case 39:
            case 40:
                _showTab(_q('[role="tab"]', nextTabItem)[0]);
                e.preventDefault();
                break;
            default:
                break;
        }
    }

    // BINDINGS
    function _bindTabsEvents(tabContainer) {
        var tabs = _q(tablistSelector + ' a', tabContainer);
        // bind all tab click and keydown events
        tabs.forEach(function (tab) {
            tab.addEventListener('click', _eventTabClick);
            tab.addEventListener('keydown', _eventTabKeydown);
        });
    }

    function _unbindTabsEvents(tabContainer) {
        var tabs = _q(tablistSelector + ' a', tabContainer);
        // unbind all tab click and keydown events
        tabs.forEach(function (tab) {
            tab.removeEventListener('click', _eventTabClick);
            tab.removeEventListener('keydown', _eventTabKeydown);
        });
    }

    // DESTROY
    function destroy() {
        tabContainers.forEach(function (tabContainer) {
            _removeA11y(tabContainer);
            _unbindTabsEvents(tabContainer);
            tabContainer.classList.remove(tabsReadyClass);
        });
    }

    // INIT
    function init() {
        if (tabContainers.length) {
            tabContainers.forEach(function (tabContainer) {
                _addA11y(tabContainer);
                _bindTabsEvents(tabContainer);
                // set all first tabs active on init
                _showTab(_q(tablistSelector + ' a', tabContainer)[0], false);
                // set ready style hook
                tabContainer.classList.add(tabsReadyClass);
            });
        }
    }
    init();

    // REVEAL API
    return {
        init: init,
        destroy: destroy
    };
};

$(function () {
    $('.tabs__item:first-child .tabs__link').addClass('tabs__link--active');
    $('.tabs__item:first-child .tabs__link').find('.vh').text('(actief)');
});

$('.tabs__link').click(function () {

    $('.tabs__link').removeClass('tabs__link--active');
    $('.tabs__link').find('.vh').text('(niet actief)');

    $(this).addClass('tabs__link--active');
    $(this).find('.vh').text('(actief)');
});;
var Perplex = Perplex || {};
Perplex.agenda = (function () {
    var agenda = {};
    var meerAgendaItemsOmTeTonen = true;
    var controlerenOpItems = true;

    agenda.Init = function () {
        loadData();

        $(window).on('scroll', function () { 
            var windscrolltop = $(window).scrollTop();
            var windscrollbottom = $(window).scrollTop() + $(window).height();
            var top = $('.js-agenda__container').first().offset().top;

            var bodyheight = $('body').height()
            var footertop = $('.c-footer').height() + 100;

            var footeroffset = bodyheight - footertop;

            if (windscrolltop >= top && windscrollbottom <= footeroffset) {
                $('.js-abc__btn').addClass('visible');
            } else {
                $('.js-abc__btn').removeClass('visible');
            }
        });
    }

    var searchTimeout = null;
    function loadData() {
        $(window).on('scroll', function () { 
            if (meerAgendaItemsOmTeTonen == true) {
                if ($(window).scrollTop() == $(document).height() - $(window).height()) {
                    getData();
                }
            }
        });
    }

    // Haalt data op van de opgegeven controller in url
    function getData() {
        if (controlerenOpItems == true) {
            controlerenOpItems = false;
            // Build url
            var queryObj = queryObj == undefined ? $("#js-itemsToSkip").val() : queryObj;
            var itemsToSkip = Number($("#js-itemsToSkip").val());
            var nodeId = $("#js-nodeId").val();
            var specialismeOfExpertise = $("#js-specialismeOfExpertise").val();
            var behandelingOfOnderzoek = $("#js-behandelingOfOnderzoek").val();
            // Request data
            $.ajax({
                url: '/umbraco/surface/agendaoverzicht/index',
                method: "Post",
                data: {
                    nodeId: nodeId,
                    skip: itemsToSkip,
                    specialismeOfExpertise: specialismeOfExpertise,
                    behandelingOfOnderzoek: behandelingOfOnderzoek
                },
            }).done(function (data) {
                $(data.results).appendTo('#js-agendawrapper');
                $("#js-itemsToSkip").val(itemsToSkip + data.items);

                if (data.items == 0) {
                    meerAgendaItemsOmTeTonen = false;
                } else {
                    $('.js-loader').addClass('js-loader--active');
                }
                controlerenOpItems = true;
                setTimeout(function () {
                    $('.js-loader').removeClass('js-loader--active');
                }, 300);
            }).fail(function () {
                $('.js-loader').removeClass('js-loader--active');
            });
        }
    }

    return agenda;
})();;
var Perplex = Perplex || {};

Perplex.abzBody = (function () {
    const abzBody = {};
    let $parent;
    let $header = 0;
    let $abcnav = 0;

    abzBody.Init = function () {
        scrollTo();
        stickInParent();
        activeLetter();

        $(window).bind('resize', () => {
            stickInParent();
        }).trigger('resize');

        // OFFSET VOOR DE HEADER ALS DIE GEVONDEN KAN WORDEN

        if ($('.js-header-container').length) {
            $header = $('.js-header-container').outerHeight();
        }
        if ($('.js-heading-anchors').length) {
            $abcnav = $('.js-abcNav').outerHeight();
        }

        scrollToLetterOrItem();

        window.addEventListener('hashchange', (e) => {
            scrollToLetterOrItem();
        });

        $(window).scroll(() => {
            const windscrolltop = $(window).scrollTop();
            const windscrollbottom = $(window).scrollTop() + $(window).height();

            const abcTopElement = $('.c-abc__results');

            if (abcTopElement.length > 0) {
                const abctop = abcTopElement.first().offset().top;

                const bodyheight = $('body').height();
                const footertop = $('.c-footer').height() + 100;

                const footeroffset = bodyheight - footertop;

                if (windscrolltop >= abctop && windscrollbottom <= footeroffset) {
                    $('.js-abc__btn').addClass('visible');
                } else {
                    $('.js-abc__btn').removeClass('visible');
                }
            }
        });
    };

    function scrollToLetterOrItem() {
        if (window.location.hash.indexOf('#abc-') >= 0) {
            const isLetter = window.location.hash.match('abc-[A-Z]$');

            if (isLetter != null && isLetter.length > 0) {
                $('html, body').animate({
                    scrollTop: $(`#${window.location.hash.substr(1)}`).offset().top - ($header + $abcnav + 77),
                }, 600);
            }
        }
        if (window.location.hash.indexOf('#abc-') >= 0) {
            const isItem = window.location.hash.match('(abc-[A-Z]-)(.*)');

            if (isItem != null && isItem.length > 2) {
                const item = $(`a[name='${window.location.hash.substr(1)}']`);

                $('.js-faq').removeClass('c-faq__item--active');
                item.next('.js-faq').addClass('c-faq__item--active');

                setTimeout(() => {
                    $('html, body').animate({
                        scrollTop: item.offset().top - ($header + $abcnav + 77),
                    }, 600);
                }, 300);
            }
        }
    }

    function stickInParent() {
        const headerHeight = $('.js-header-container').outerHeight();

        if (window.matchMedia('(min-width: 1024px)').matches) {
            // STICKY ABC
            $('.js-abcNav').stick_in_parent({ sticky_class: 's-fixed', offset_top: headerHeight });
        } else {
            $('.js-abcNav').trigger('sticky_kit:detach');
        }
    }

    // Scroll naar de gekozen letter toe
    function scrollTo() {
        // OFFSET VOOR DE HEADER ALS DIE GEVONDEN KAN WORDEN
        let $header = 0;
        let $abcnav = 0;

        if ($('.js-header-container').length) {
            $header = $('.js-header-container').outerHeight();
        }
        if ($('.js-heading-anchors').length) {
            $abcnav = $('.js-abcNav').outerHeight();
        }

        $('body').on('click', '.js-scrollTo', function () {
            const letter = $(this).text().trim();

            $('html, body').animate({
                scrollTop: $(`#abc-${letter}`).offset().top - ($header + $abcnav + 77),
            }, 600);
            window.location.hash = `abc-${letter}`;
        });
    }

    function activeLetter() {
        // Based on https://codepen.io/talmand/pen/dybmvZN
        const navbar = document.querySelector('.js-header-container');
        const abcNav = document.querySelector('.js-abcNav');
        const sections = document.querySelectorAll('.c-abc__results');
        let heightNavbar = '';
        const heightAbcNav = abcNav.offsetHeight;
        let totalOffsetHeight = heightAbcNav;
        let rootMarginExtra = '';

        const setValues = () => {
            if (navbar) {
                heightNavbar = navbar.offsetHeight;
                totalOffsetHeight = heightNavbar + heightAbcNav;
            }

            if (window.innerWidth < 1024) {
                rootMarginExtra = 5;
            } else {
                rootMarginExtra = 35;
            }
        };

        setValues();

        window.addEventListener('resize', () => {
            setValues();
        });

        const ioOptions = {
            // Somehow need to add 5px extra to make this work
            rootMargin: `${-1 * (totalOffsetHeight + rootMarginExtra)}px 0px 0px 0px`,
            threshold: [...Array(100).keys()].map((x) => x / 100),
        };

        const setActiveRibbonLetter = (id = 'A') => {
            const letter = document.getElementById(id);

            Array.from(document.querySelectorAll('.js-scrollTo')).forEach((item) => {
                item.classList.remove('s-active');
            });

            letter.classList.add('s-active');

            abcNav.scrollTo({
                left: letter.offsetLeft - 27,
                behavior: 'smooth',
            });
        };

        function onIntersect(entries) {
            entries.forEach((entry) => {
                const ratio = entry.intersectionRatio;
                const boundingRect = entry.boundingClientRect;
                const { intersectionRect } = entry;
                const letterID = entry.target.id.split('-').pop();

                if (ratio === 0) {
                    // console.log(letterID, 'outside');
                } else if (ratio < 1) {
                    if (boundingRect.top < intersectionRect.top) {
                        setActiveRibbonLetter(letterID);
                        // console.log(letterID, 'on the top');
                    } else {
                        // console.log(letterID, 'on the bottom');
                    }
                } else {
                    // console.log(letterID, 'inside');
                }
            });
        }

        const observer = new IntersectionObserver(onIntersect, ioOptions);

        sections.forEach((section) => {
            observer.observe(section);
        });
    }

    return abzBody;
}());
;
var Perplex = Perplex || {};
Perplex.Cookiemelding = (function () {
    var cookiemelding = {};

    var placeholderAttributeName = 'cookie-placeholder';
    var explicietAkkoordNodig;

    var $cookiemelding;
    var cookiename;

    cookiemelding.Init = function (_explicietAkkoordNodig, _cookiename) {
        explicietAkkoordNodig = _explicietAkkoordNodig;
        cookiename = _cookiename;
        $('.js-cookie__close').on('click', OnClose);
        $('.js-cookie__accept').on('click', OnAccept);
        $cookiemelding = $('section.c-cookies__container');
        Perplex.Analytics.TrackEvent('Cookiemelding', 'Getoond', 'Getoond', undefined, true);
    }

    function LoadPlaceholders() {
        // Replace any <iframe>'s src attribute with content of data-src
        var placeholders = $('[' + placeholderAttributeName + ']');
        for (var i = 0; i < placeholders.length; i++) {
            var placeholder = placeholders[i];
            // Maak een nieuwe Iframe aan met SRC
            var iframe = $('<iframe></iframe>');

            // Kopieer alle attributen
            var attributes = placeholder.attributes;
            $.each(attributes, function () {
                // Kopieer niet de style tag en het placeholder attribuut
                if (this.name !== placeholderAttributeName && this.name !== 'style')
                    iframe.attr(this.name, this.value);
            });

            // Instellen
            $(placeholder).replaceWith(iframe);
    }
    }

    function OnClose()
    {
        $cookiemelding.fadeOut();
        if (!explicietAkkoordNodig)
        {
            // Gelijk externe content inladen
            Perplex.Analytics.TrackEvent('Cookiemelding', 'Sluit', 'Cookies geaccepteerd', undefined, true);
            AcceptCookies();
        }
        else
        {
            Perplex.Analytics.TrackEvent('Cookiemelding', 'Sluit', 'Cookies niet geaccepteerd', undefined, true);
            // melding verbergen via cookie
            CloseCookieBar();
        }
    }

    function OnAccept() {
        $cookiemelding.fadeOut();
        Perplex.Analytics.TrackEvent('Cookiemelding', 'Accepteer', 'Cookies geaccepteerd', undefined, true);
        AcceptCookies();
    }

    function AcceptCookies()
    {
        LoadPlaceholders();

        // We doen een AJAX call zodat we de PerpexCookieApproval cookie
        // op HttpOnly kunnen laten staan. De browser handelt het opslaan van
        // de cookie verder af.
        $.ajax({
            url: '/umbraco/api/cookiesapi/acceptcookies',
            method: 'get'
        });
    }

    function CloseCookieBar() {
        $.ajax({
            url: '/umbraco/api/cookiesapi/closecookiebar',
            method: 'get'
        });
    }

    return cookiemelding;
})();
;
var Perplex = Perplex || {};
Perplex.headingAnchors = (function () {
    var headingAnchors = {};
    var headingAnchorsContainer = $('.js-heading-anchors');

    headingAnchors.Init = function () {
        if (headingAnchorsContainer.length == 0) { return; }

        $(window).scroll(function () {
            var windscroll = $(window).scrollTop();
            var navtop = $('.js-inpage__nav').position().top + $('.js-inpage__nav').outerHeight(true);

            if (windscroll >= navtop) {
                // Make anchro element  visible and calculate scroll depth
                $('.js-heading-anchors').addClass('visible');
                $('.rte h2[id^=sectie]').each(function (i) {
                    if ($(this).position().top - $('.js-heading-anchors').outerHeight(true) <= windscroll) {
                        var elementToMakeActive = headingAnchorsContainer.find('a').eq(i).first();
                        
                        // Only make item active if not already active (to prevent class blink effect)
                        if (!elementToMakeActive.is(headingAnchorsContainer.find('a.active:first'))) {
                            headingAnchorsContainer.find('a.active').removeClass('active');
                            elementToMakeActive.addClass('active');

                            // Only on mobile devices
                            if (window.matchMedia('(max-width: 1023px)').matches) {
                                var leftposition = elementToMakeActive.parent().position().left;
                                $('.js-heading-anchors ul').scrollLeft(leftposition);
                            }
                        }
                    }
                });
            } else {
                // Make first link active
                headingAnchorsContainer.find('a.active').removeClass('active');
                headingAnchorsContainer.find('a:first').addClass('active');
                $('.js-heading-anchors').removeClass('visible');
            }
        });
    };
    return headingAnchors;
})();;
/// <reference path="/Scripts/_references.js" />
var Perplex = Perplex || {};

Perplex.Members = (function () {
    var members = {};

    members.Login = (function () {
        var login = {};

        login.Init = function () {
            if (window.location.hash === "#forget") {
                $('.js-forgetpasswordwrapper').show(500).find('.form-group input').first().focus();
            }
        };

        $(document).on('click', '.js-wachtwoord-vergeten', function () { $('.js-forgetpasswordwrapper').show(500); Perplex.Analytics.TrackEvent('Memberlogin', 'Wachtwoord vergeten', 'Open'); });

        return login;
    })();

    members.Register = (function () {
        var register = {};

        register.Init = function () {
            // Postcode koppeling
            new Perplex.Util.PostcodeKoppeling({
                postcode: $(".js-postcode"),
                huisnummer: $(".js-huisnummer"),
                straat: $(".js-straat"),
                stad: $(".js-plaats")
            });
        }

        return register;
    })();

    return members;
})();;
var Perplex = Perplex || {};
Perplex.nieuwslanding = (function () {
    var nieuwslanding = {};
    var meerNieuwsItemsOmTeTonen = true;
    var controlerenOpItems = true;

    nieuwslanding.Init = function () {
        loadData();

        $(window).on('scroll', function () { 
            var windscrolltop = $(window).scrollTop();
            var windscrollbottom = $(window).scrollTop() + $(window).height();
            var top = $('.js-nieuws__container').first().offset().top;

            var bodyheight = $('body').height()
            var footertop = $('.c-footer').height() + 100;

            var footeroffset = bodyheight - footertop;

            if (windscrolltop >= top && windscrollbottom <= footeroffset) {
                $('.js-abc__btn').addClass('visible');
            } else {
                $('.js-abc__btn').removeClass('visible');
            }
        });
    }

    var searchTimeout = null;
    function loadData() {
        $(window).on('scroll', function () { 
            if (meerNieuwsItemsOmTeTonen == true) {
                if (($(window).scrollTop() + 250) >= $(document).height() - $(window).height()) {
                    getData();
                }
            }
        });
    }

    // Haalt data op van de opgegeven controller in url
    function getData() {
        if (controlerenOpItems == true) {
            controlerenOpItems = false;
            // Build url
            var queryObj = queryObj == undefined ? $("#js-itemsToSkip").val() : queryObj;
            var itemsToSkip = Number($("#js-itemsToSkip").val());
            var nodeId = $("#js-nodeId").val();
            var specialisme = $("#js-specialisme").val();
            // Request data
            $.ajax({
                url: '/umbraco/surface/nieuwslandingoverzicht/index',
                method: "Post",
                data: {
                    nodeId: nodeId,
                    skip: itemsToSkip,
                    specialismeOfExpertise: specialisme
                },
            }).done(function (data) {
                $(data.results).appendTo('#js-nieuwswrapper');
                $("#js-itemsToSkip").val(itemsToSkip + data.items);

                if (data.items == 0) {
                    meerNieuwsItemsOmTeTonen = false;
                } else {
                    $('.js-loader').addClass('js-loader--active');
                }
                controlerenOpItems = true;
                setTimeout(function () {
                    $('.js-loader').removeClass('js-loader--active');
                }, 300);
            }).fail(function () {
                $('.js-loader').removeClass('js-loader--active');
            });
        }
    }

    return nieuwslanding;
})();;
var Perplex = Perplex || {};
Perplex.nieuws = (function () {
    var nieuws = {};
    var meerNieuwsItemsOmTeTonen = true;
    var controlerenOpItems = true;

    nieuws.Init = function () {
        loadData();

        $(window).on('scroll', function () { 
            var windscrolltop = $(window).scrollTop();
            var windscrollbottom = $(window).scrollTop() + $(window).height();
            var top = $('.js-nieuws__container').first().offset().top;

            var bodyheight = $('body').height()
            var footertop = $('.c-footer').height() + 100;

            var footeroffset = bodyheight - footertop;

            if (windscrolltop >= top && windscrollbottom <= footeroffset) {
                $('.js-abc__btn').addClass('visible');
            } else {
                $('.js-abc__btn').removeClass('visible');
            }
        });
    }

    var searchTimeout = null;
    function loadData() {
        $(window).on('scroll', function () {  
            if (meerNieuwsItemsOmTeTonen == true) {
                if (($(window).scrollTop() + 250) >= $(document).height() - $(window).height()) {
                    getData();
                }
            }
        });
    }

    // Haalt data op van de opgegeven controller in url
    function getData() {
        if (controlerenOpItems == true) {
            controlerenOpItems = false;
            // Build url
            var queryObj = queryObj == undefined ? $("#js-itemsToSkip").val() : queryObj;
            var itemsToSkip = Number($("#js-itemsToSkip").val());
            var nodeId = $("#js-nodeId").val();
            var specialisme = $("#js-specialisme").val();
            var specialist = $("#js-specialist").val();
            // Request data
            $.ajax({
                url: '/umbraco/surface/nieuwsoverzicht/index',
                method: "Post",
                data: {
                    nodeId: nodeId,
                    skip: itemsToSkip,
                    specialismeOfExpertise: specialisme,
                    specialist: specialist
                },
            }).done(function (data) {
                $(data.results).appendTo('#js-nieuwswrapper');
                $("#js-itemsToSkip").val(itemsToSkip + data.items);

                if (data.items == 0) {
                    meerNieuwsItemsOmTeTonen = false;
                } else {
                    $('.js-loader').addClass('js-loader--active');
                }
                controlerenOpItems = true;
                setTimeout(function () {
                    $('.js-loader').removeClass('js-loader--active');
                }, 300);
            }).fail(function () {
                $('.js-loader').removeClass('js-loader--active');
            });
        }
    }

    return nieuws;
})();;
var Perplex = Perplex || {};

Perplex.Zoeken = (function () {
    const zoeken = {};
    let $parent;

    zoeken.Init = function () {
        $parent = $parent = $('#js-custom-search-result');
        $parent.html('');
        $searchInputSiteWide = $('.js-search-input.sitewide');
        $searchInput = $('.js-search-input');
        $container = $($searchInput.data('searchresults-container-id'));

        // Hide search popup when clicking outside searchbar
        $(document).on('click', (clickedElement) => {
            // als we klikken binnen een 'active' zoekelement, dan moeten we die niet meteen sluiten.
            const $clickedElement = $(clickedElement.target);

            if (!$clickedElement.hasClass('js-search-wrapper--active')) { return; }

            if ($('.js-search-wrapper--active').length === 0) {
                // Wanneer we een zoekbalk hebben en de resultaten direct tonen (bij overzichten) gaan we dit event niet afvuren
                return;
            }

            let label = 'Sluit zoekfunctie';

            if ($('.js-search-wrapper--active').find('.js-search-input').hasClass('sitewide')) {
                label += ' header';
            } else {
                label += ' homepage';
            }

            Perplex.Analytics.TrackEvent('Zoekfunctie', 'Klik', label, undefined, false);

            // Check if we are not clicking on an input field or a other inputfield is open
            if (!(clickedElement.target.classList.contains('js-search-input'))) {
                hideCustomSearch();

                $('.js-header-container').removeClass('z-high');
            } else {
                if ($('.js-search-wrapper.js-search-wrapper--active').length > 0) {
                    hideCustomSearch();
                }

                // No input open, so open a new one
                const searchWrapperId = $clickedElement.data('searchresults-container-id');
                const $searchResultsWrapper = $(searchWrapperId);

                showCustomSearch($searchResultsWrapper);
            }
        });

        // Show search popup when clicking inside
        $('.js-search-close').on('click', (e) => {
            e.preventDefault();
            hideCustomSearch();
            $('.js-header-container').removeClass('z-high');
        });

        $(document).keyup((e) => {
            if ((e.keyCode === 27) && ($('.c-search__wrapper--active').length)) {
                e.preventDefault();
                hideCustomSearch();
                $('.js-header-container').removeClass('z-high');
            }
        });

        // Search button clicked
        if ($searchInputSiteWide.length > 0) {
            $('.js-search-open').on('click', (e) => {
                const $searchResultsWrapper = $($searchInputSiteWide.data('searchresults-container-id'));

                e.preventDefault();
                e.stopImmediatePropagation();
                // Hide or show popup when clicking on search icon
                if ($('html').hasClass('is-locked')) {
                    hideCustomSearch();
                    // $searchInputSiteWide.closest('.js-search-wrapper').hide(); // hide sidewide searchbar
                } else {
                    $('html').addClass('is-locked');
                    $searchResultsWrapper.closest('.js-search-wrapper').addClass('js-search-wrapper--active c-search__wrapper--active');
                    showCustomSearch($searchResultsWrapper);
                }
            });
        }

        // Search after some time
        let searchTimeout = null;

        $searchInput.on('input', function () {
            const $inputEl = $(this);

            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(function () {
                const term = $inputEl.val();

                if (term.length > 2) {
                    updateCustomSearch(term, $inputEl);
                } else {
                    // Less than x characters; empty results
                    updateCustomSearch(term, $inputEl);
                    $(this).closest('.js-search-wrapper').find('.c-search__result__wrapper').removeClass('c-search__result__wrapper--active');
                }
            }, 500);
        });
        initToggleButton();
    };

    function initToggleButton() {
        // Example: <button class="js-toggle-class-button" alternativetekst="Minder resultaten tonen" toggleclass="topsearch__list--all" parentclass="topsearch__list">Meer resultaten tonen</button>
        $('.js-toggle-class-button').click(function () {
            const $this = $(this);
            const text = $this.text();
            const alternativetext = $this.attr('alternativetext');
            const toggleclass = $this.attr('toggleclass');
            const parentselector = $this.attr('parentselector');
            const $parent = $this.closest(parentselector);

            $('.topsearch__list').toggleClass(toggleclass);
            $this.text(alternativetext);
            $this.attr('alternativetext', text);
        });

        $('.js-toggle-moreresults').click(function () {
            $(this).hide();
            $('#moreresults').show();
            $('html,body').animate({ scrollTop: $('#moreresults').offset().top }, 800);
        });
    }

    function updateCustomSearch(q, $settings) {
        $('.js-loader').addClass('js-loader--active');
        const searchResultsWrapperId = $settings.data('searchresults-container-id');
        const homeId = $settings.data('homepageid');
        const showexternalsearchresults = $settings.data('showexternalsearchresults');
        const showRecommendations = $settings.data('showrecommendations');
        const showoverviewlink = $settings.data('showoverviewlink');
        const showEmptyGroups = $settings.data('showemptygroups');
        const url = '/umbraco/surface/zoeken/CustomSearch/'
            + `?HomeId=${homeId
            }&Q=${q
            }&ShowExternalSearchResults=${showexternalsearchresults
            }&ShowRecommendations=${showRecommendations
            }&ShowOverviewLink=${showoverviewlink
            }&ShowEmptyGroups=${showEmptyGroups}`;

        // Load searchresults and place them inside the wrapper
        const $searchResultsWrapper = $(searchResultsWrapperId);

        $searchResultsWrapper.closest('.js-search-wrapper').addClass('js-search-wrapper--active c-search__wrapper--active');
        $.get(url).then((html) => {
            if (html.indexOf('js-tracking-zoeken-noresults') > 0) {
                // we krijgen html terug maar geen resultaten (deze classe komt dan voor in html
                Perplex.Analytics.TrackEvent('Zoekfunctie', 'Auto aanvullen - Geen resultaten', q, undefined, true);
            } else {
                // We hebben wel resultaten
                let text = 'Zoekopdracht - ';
                const searchOpenedFromMenu = $('.js-search-wrapper--active').closest('.js-header-container').length;

                if (searchOpenedFromMenu == 1) {
                    text = 'Hoofdmenu';
                } else {
                    text = 'Header';
                }
                Perplex.Analytics.TrackEvent('Zoeken', text, q, undefined, true);
            }
            $searchResultsWrapper.html(html);
            showCustomSearch($searchResultsWrapper);
            $searchResultsWrapper.closest('.js-search-wrapper').find('.c-search__result__wrapper').addClass('c-search__result__wrapper--active');
            trackSearchResultClick();
        }).done(() => {
            $('.js-loader').removeClass('js-loader--active');
        }).fail(() => {
            $searchResultsWrapper.html('');
            $('.js-search-wrapper').removeClass('js-search-wrapper--active');
            hideCustomSearch();
            $('.js-search-wrapper').find('.js-search-input').val('');
        });
    }

    function trackSearchResultClick() {
        $('.js-searchresults-popup a').on('click', function () {
            const item = $(this);
            let text = 'Klik resultaat - ';
            const searchOpenedFromMenu = $('.js-search-wrapper--active').closest('.js-header-container').length;

            if (searchOpenedFromMenu == 1) {
                text += 'Hoofdmenu';
            } else {
                text += 'Header';
            }
            const searchterm = `${$('.js-search-input:visible').val()} - ${item.attr('href')}`;

            Perplex.Analytics.TrackEvent('Zoeken', text, searchterm, undefined, true);
        });
    }

    function showCustomSearch($searchResultsWrapper) {
        // Pupulate search wrapper with results
        $('.js-header-container').addClass('z-low');

        if ($searchResultsWrapper.closest('.js-search-wrapper').hasClass('js-search-wrapper--home')) {
            $('html,body').animate({ scrollTop: $('.js-search-wrapper--home').offset().top - 130 }, 800);
        }
        setTimeout(() => {
            $('.js-search-wrapper--active .js-search-input').focus();
        }, 80);
        // pas op met timeout van 80; wanneer het effect te lang duurt (de show actie van de wrapper) dan moet 80 dus ook opgehoogd worden

        let text = '';
        const searchOpenedFromMenu = $('.js-search-wrapper--active').closest('.js-header-container').length;

        if (searchOpenedFromMenu == 1) {
            text = 'Open - Hoofdmenu';
        } else {
            text = 'Uit focus - Header';
        }
        // Perplex.Analytics.TrackEvent('Zoeken', 'Klik', text, undefined, true);
    }

    function hideCustomSearch() {
        // Reset search wrapper (results) and input field to default state
        const searchOpenedFromMenu = $('.js-search-wrapper--active').closest('.js-header-container').length;

        if ($('html').hasClass('is-locked')) {
            // only run this code when the search bar is actually open!
            let text = '';

            if (searchOpenedFromMenu == 1) {
                text = 'Sluit - Hoofdmenu';
            } else {
                text = 'Uit focus - Header';
            }
            Perplex.Analytics.TrackEvent('Zoeken', 'Klik', text, undefined, true);
        }

        $('.js-search-wrapper').find('.c-search__result__wrapper').removeClass('c-search__result__wrapper--active');
        $('.js-search-wrapper').removeClass('js-search-wrapper--active c-search__wrapper--active');
        // $searchInputSiteWide.closest('.js-search-wrapper').hide(); // hide sidewide searchbar
        $searchInputSiteWide.closest('.js-search-wrapper').removeClass('c-search__wrapper--active'); // hide sidewide searchbar
        $('.js-search-wrapper').find('.js-search-input').val('');
        $('html').removeClass('is-locked');
        $('.js-header-container').removeClass('z-low');
    }

    return zoeken;
}());
;
var Perplex = Perplex || {};

Perplex.Accessibility = (function () {
    const accessibility = {};

    accessibility.Init = function () {
        // Translate page
        $(document).on('click', '.translatePage', function () {
            $('.c-translation__container').addClass('c-translation__container--active');
            $('.js-translate-popup').focus();
            $('.goToTranslateLink').attr('href', $(this).attr('url'));
        });

        $(document).on('click', '.c-translation__close', () => {
            $('.c-translation__container').removeClass('c-translation__container--active');
            // $('.c-translation__popup').blur();
        });
    };

    return accessibility;
}());
;
var Perplex = Perplex || {};

Perplex.Analytics = (function () {
    const analytics = {};

    // Extra UA accounts
    let additionalAccountNames = [];

    // @param {Array} additionalAccountNames - Array van 'name' parameters van alle extra UA accounts die zijn gekoppeld aan de website.
    // Op deze manier is er ondersteuning voor het meten van alle acties voor verschillende UA accounts.
    // De extra UA account is geregistreerd middels deze syntax:
    // ga('create', '<UA-CODE>', 'auto', '<NAME>');
    analytics.Init = function (_additionalAccountNames) {
        // Moet een Array zijn
        if (_additionalAccountNames != null && Object.prototype.toString.call(_additionalAccountNames) === '[object Array]') {
            additionalAccountNames = _additionalAccountNames;
        }

        // Standaard events / virtual page views voor <a href="..."> links
        trackLinks();

        // Scrolldiepte
        trackScrolldiepte();

        // YouTube
        trackYouTube();

        // Vimeo
        trackVimeo();

        // Engagement
        trackEngagement();

        // Form abandonment
        trackAdvancedForm();

        // Martini custom tracking
        MartiniTracking();
    };

    // Google Maps
    // Functie dient te worden aangeroepen met
    // google.maps.Map object
    analytics.TrackGoogleMaps = function (map) {
        if (typeof map !== 'object') { return; }

        // Zoom
        map.addListener('zoom_changed', () => {
            analytics.TrackEvent('Google Maps', 'Zoom', map.getZoom());
        });

        // Map Type (wegen / terrein / satelliet / hybride)
        map.addListener('maptypeid_changed', () => {
            switch (map.getMapTypeId()) {
            case google.maps.MapTypeId.ROADMAP:
                analytics.TrackEvent('Google Maps', 'Klik kaarttype', 'Kaart');
                break;

            case google.maps.MapTypeId.TERRAIN:
                analytics.TrackEvent('Google Maps', 'Klik kaarttype', 'Terrein');
                break;

            case google.maps.MapTypeId.SATELLITE:
                analytics.TrackEvent('Google Maps', 'Klik kaarttype', 'Satelliet');
                break;

            case google.maps.MapTypeId.HYBRID:
                analytics.TrackEvent('Google Maps', 'Klik kaarttype', 'Hybride');
                break;

            default: break;
            }
        });

        // StreetView
        const panorama = map.getStreetView();

        if (panorama != null) {
            panorama.addListener('visible_changed', () => {
                if (panorama.getVisible()) {
                    analytics.TrackEvent('Google Maps', 'Streetview');
                }
            });
        }
    };

    // Event
    analytics.TrackEvent = function (category, action, label, value, nonInteraction) {
        // Geen Analytics? Dan kunnen we niets doen
        if (typeof ga !== 'function') { return; }

        // Standaard account
        trackEvent(category, action, label, value, nonInteraction);

        // Eventuele extra accounts
        for (let i = 0; i < additionalAccountNames.length; i++) {
            const name = additionalAccountNames[i];

            trackEvent(category, action, label, value, nonInteraction, name);
        }
    };

    // Voor intern gebruik met extra 'name' parameter om meerdere accounts tegelijkertijd te ondersteunen
    function trackEvent(category, action, label, value, nonInteraction, name) {
        const command = createCommand('send', name);

        if (nonInteraction != null) {
            ga(command, 'event', category, action, label, value, { nonInteraction });
        } else {
            ga(command, 'event', category, action, label, value);
        }
    }

    // Pageview
    analytics.TrackPageview = function (url) {
        // Geen Analytics? Dan kunnen we niets doen
        if (typeof ga !== 'function') { return; }

        // Standaard account
        trackPageview(url);

        // Eventuele extra accounts
        for (let i = 0; i < additionalAccountNames.length; i++) {
            const name = additionalAccountNames[i];

            trackPageview(url, name);
        }
    };

    // Interne functie zodat we Pageviews ook voor extra accounts kunnen tracken
    function trackPageview(url, name) {
        const command = createCommand('send', name);

        ga(command, 'pageview', url);
    }

    // Levert een correct Analytics commando (create/send) etc. op, op basis
    // van de gegeven naam (optionele parameter)
    function createCommand(command, name) {
        // Voor een specifieke account wordt de syntax <name>.<command> ipv alleen <command>
        return (name ? `${name}.` : '') + command;
    }

    /*
        Standaard tracken van verschillende soorten <a href="..."> links. Standaard gebeurt dit niet in Google Analytics, maar door het toevoegen van deze events
        worden events afgevuurd als iemand op een linkje naar een andere website, naar een document (zoals .pdf, .doc, .docx), telefoon-links, mailto-links en interne links
    */
    function trackLinks() {
        $(document).on('click', "a[href^='http']", externalLinks);
        $(document).on('click', "a[href$='pdf'],a[href$='doc'],a[href$='docx']", externalDocumentLinks);
        $(document).on('click', "a[href^='tel:']", telephoneLinks);
        $(document).on('click', "a[href^='mailto:']", mailToLinks);
        $(document).on('click', "a[href^='#']", pageAnchors);

        /*
        * Clickhandler for external links that do not contain the current hostname
        * Sends its data to Univeral analytics or Google analytics, depending on the current configuration
        */
        function externalLinks(e) {
            const url = $(this).attr('href');

            // Detect if this is not the current hostname
            if (url.indexOf(`${location.protocol}//${location.hostname}`) !== 0) {
                // Send to Google
                analytics.TrackEvent('Microconversie', 'Klik out', url);

                // Set the target as blank for this current link
                $(this).attr('target', '_blank');
            }
        }

        /*
        * Clickhandler for documents that do not contain the current hostname
        * Sends its data to Univeral analytics or Google analytics, depending on the current configuration
        */
        function externalDocumentLinks() {
            const url = $(this).attr('href');

            // Detect if this is not the current hostname
            if (url.indexOf(`${location.protocol}//${location.hostname}`) !== 0) {
                // Send to Google
                // If url starts with a slash, do not add another one
                if (url.indexOf('/') === 0) {
                    analytics.TrackPageview(`/virtual/document${url}/`);
                } else {
                    analytics.TrackPageview(`/virtual/document/${url}/`);
                }

                // Set the target as blank for this current link
                $(this).attr('target', '_blank');
            }
        }

        /*
        * Clickhandler for tel links that do not contain the current hostname
        * Sends its data to Univeral analytics or Google analytics, depending on the current configuration
        */
        function telephoneLinks() {
            const url = $(this).attr('href');
            const phone = url.replace('tel:', '');

            analytics.TrackEvent('Microconversie', 'Klik tel', phone);
        }

        /*
        * Clickhandler for mailto links
        * Sends it`s data to Univeral analytics or Google analytics, depending on the current configuration
        */
        function mailToLinks() {
            const url = $(this).attr('href');
            const email = url.replace('mailto:', '');

            analytics.TrackEvent('Microconversie', 'Klik mailto', email);
        }

        /*
        * Clickhandler for page anchors
        * Sends its data to Univeral analytics or Google analytics, depending on the current configuration
        */
        function pageAnchors() {
            const url = $(this).attr('href');

            // Ignore literal "#" href used for JS links
            if (url === '#') return;

            analytics.TrackPageview(`/virtual/internal-link/${url}/`);
        }
    }

    /*
        Functie om de scrolldiepte op een pagina per 25% te meten. Er wordt eenmalig een event afgevuurd als je tot 25% van de pagina bent gescrolld. Dit geldt tevens voor 50, 75 en 100%.
        Bij alle events staat non-interaction op true.
    */
    function trackScrolldiepte() {
        // Boolean waardes zodat we slechts eenmaal een event sturen
        // voor 25%, 50%, 75%, en 100% scroll
        let scroll25 = false;
        let scroll50 = false;
        let scroll75 = false;
        let scroll100 = false;

        $(window).on('scroll', onScroll);

        // Berekent de scroll positie van de gebruiker
        function onScroll() {
            const documentHeight = $(document).height();
            const scrollPosition = $(document).scrollTop();
            const viewportHeight = $(window).height();
            const percentage = Math.ceil((scrollPosition / (documentHeight - viewportHeight)) * 100);

            // Categorie en actie zijn altijd hetzelfde
            const categorie = 'Scrolldiepte';
            const actie = 'Scroll';

            if (percentage >= 25 && percentage < 50 && !scroll25) {
                scroll25 = true;
                analytics.TrackEvent(categorie, actie, '25%', 25, true);
            }

            if (percentage >= 50 && percentage < 75 && !scroll50) {
                scroll50 = true;
                analytics.TrackEvent(categorie, actie, '50%', 50, true);
            }

            if (percentage >= 75 && percentage < 100 && !scroll75) {
                scroll75 = true;
                analytics.TrackEvent(categorie, actie, '75%', 75, true);
            }

            if (percentage === 100 && !scroll100) {
                scroll100 = true;
                analytics.TrackEvent(categorie, actie, '100%', 100, true);
            }
        }
    }

    /*
        Deze functie trackt het play, pause, stop van filmpjes die we laden vanuit YouTube.
    */
    function trackYouTube() {
        const youtubeUrlRegex = /youtube(?:-nocookie)?\.com\/embed/;

        // DK @ 2016-01-21
        // Deze functie laadt standaard een iframe_api JS bestand in,
        // waardoor er op Firefox cookies worden gezet,
        // ongeacht of er een YouTube IFrame op de pagina staat.
        // Indien er dus geen iframe is gaan we niet verder om dit te vermijden
        // DK @ 2016-01-28
        // Bij Gazelle (en in de toekomst wellicht meer projecten) wordt er gebruik gemaakt van
        // het data-src attribuut om de embeds wat later in te laden. Hier moeten we dus ook
        // rekening mee houden.
        if ($('iframe').filter(function () {
            const src = $(this).attr('src');
            const dataSrc = $(this).data('src');

            // Zit er een YouTube URL in een van beide?

            return youtubeUrlRegex.test(src) || youtubeUrlRegex.test(dataSrc);
        }).length === 0) // <- Geen YouTube iframes gevonden?
        {
            return;
        }

        // OPTIONAL: Enable JSAPI if it's not already on the URL
        // note: this will cause the Youtube player to "flash" on the page when reloading to enable the JS API
        // DK @ 2016-01-28
        // Ook hier dus testen op het data-src attribuut.
        for (let e = document.getElementsByTagName('iframe'), x = e.length; x--;) {
            // We checken eerst het src attribuut
            if (youtubeUrlRegex.test(e[x].src)) {
                if (e[x].src.indexOf('enablejsapi=') === -1) {
                    e[x].src += `${e[x].src.indexOf('?') === -1 ? '?' : '&'}enablejsapi=1`;
                }
            }

            // En nu het data-src attribuut
            if (e[x].dataset && youtubeUrlRegex.test(e[x].dataset.src)) {
                if (e[x].dataset.src.indexOf('enablejsapi=') === -1) {
                    e[x].dataset.src += `${e[x].dataset.src.indexOf('?') === -1 ? '?' : '&'}enablejsapi=1`;
                    // jQuery's .data lijkt niet te updaten als we de .dataset aanpassen, enigszins vreemd.
                    // Nog even expliciet doen

                    window.jQuery && window.jQuery(e[x]).data('src', e[x].dataset.src);
                }
            }
        }

        const gtmYTListeners = []; // support multiple players on the same page

        // attach our YT listener once the API is loaded
        // DK @ 2015-12-07: MOET op window gedefinieerd worden (globaal),
        // anders kan de YouTube JavaScript die we inladen er niet bij :)
        window.onYouTubeIframeAPIReady = function () {
            for (let e = document.getElementsByTagName('iframe'), x = e.length; x--;) {
                if (youtubeUrlRegex.test(e[x].src)
                    // TH: also check for data-src here
                    || (e[x].dataset && youtubeUrlRegex.test(e[x].dataset.src))) {
                    gtmYTListeners.push(new YT.Player(e[x], {
                        events: {
                            onStateChange: onPlayerStateChange,
                            onError: onPlayerError,
                        },
                    }));
                    YT.gtmLastAction = '';
                }
            }
        };

        // listen for play/pause, other states such as rewind and end could also be added
        // also report % played every second
        function onPlayerStateChange(e) {
            e.data == YT.PlayerState.PLAYING && setTimeout(onPlayerPercent, 1000, e.target);
            const video_data = e.target.getVideoData();
            const label = `${video_data.video_id}: ${video_data.title}`;

            // PLAYING
            if (e.data == YT.PlayerState.PLAYING) {
                // RESUME
                if (YT.gtmLastAction == 'p') {
                    analytics.TrackEvent('Video', 'Resume', label);
                    YT.gtmLastAction = '';
                } else if (YT.gtmLastAction == '') {
                    analytics.TrackEvent('Video', 'Play', label);
                    YT.gtmLastAction = '';
                }
            }

            // PAUSED
            else if (e.data == YT.PlayerState.PAUSED) {
                analytics.TrackEvent('Video', 'Pause', label);
                YT.gtmLastAction = 'p';
            }

            // STOPPED
            else if (e.data == YT.PlayerState.ENDED) {
                analytics.TrackEvent('Video', 'Stop', label);
            }
        }

        // catch all to report errors through the GTM data layer
        // once the error is exposed to GTM, it can be tracked in UA as an event!
        // refer to https://developers.google.com/youtube/js_api_reference#Events onError
        function onPlayerError(e) {
            analytics.TrackEvent('Video', 'Error', e);
        }

        // report the % played if it matches 0%, 25%, 50%, 75% or completed
        function onPlayerPercent(e) {
            if (e.getPlayerState() == YT.PlayerState.PLAYING) {
                const t = e.getDuration() - e.getCurrentTime() <= 1.5 ? 1 : (Math.floor(e.getCurrentTime() / e.getDuration() * 4) / 4).toFixed(2);

                if (!e.lastP || t > e.lastP) {
                    const video_data = e.getVideoData();
                    const label = `${video_data.video_id}: ${video_data.title}`;

                    e.lastP = t;

                    // Geen 0% sturen, niet echt zinnig
                    // Wordt blijkbaar "0.00", dus daarom even ==
                    // voor het geval het wellicht soms echt 0 is, of "0".
                    if (t == 0) { return; }

                    analytics.TrackEvent('Video', 'Played', `${t * 100}%`, t * 100);
                }
                e.lastP != 1 && setTimeout(onPlayerPercent, 1000, e);
            }
        }

        // load the Youtube JS api and get going
        const j = document.createElement('script');
        const f = document.getElementsByTagName('script')[0];

        j.src = 'https://www.youtube.com/iframe_api';
        j.async = true;
        f.parentNode.insertBefore(j, f);
    }

    /*
        Deze functie trackt het play, pause, stop van filmpjes die we laden vanuit Vimeo.
    */
    function trackVimeo() {
        /*!
         * vimeo.ga.js | v0.6
         * Based on modifications by LukasBeaton (https://github.com/LukasBeaton/vimeo.ga.js)
         * Copyright (c) 2015 Sander Heilbron (http://www.sanderheilbron.nl)
         * MIT licensed
         */

        let vimeoGAJS = (window.vimeoGAJS) ? window.vimeoGAJS : {};

        // Indien de iframe geen ID heeft, even toevoegen
        // Elk ID begint met deze tekst:
        const idTemplate = 'vimeo-player-';
        let idCounter = 1; // Indien we IDs genereren plakken we dit nummer erachter

        (function ($) {
            vimeoGAJS = {
                iframes: [],
                gaTracker: undefined,
                eventMarker: {},

                init() {
                    vimeoGAJS.iframes = $('iframe').filter(function () {
                        return /player\.vimeo/.test($(this).attr('src'));
                    });

                    $.each(vimeoGAJS.iframes, (index, iframe) => {
                        let iframeId = $(iframe).attr('id');
                        const src = $(iframe).attr('src');

                        // DK @ 2015-12-07
                        // Wat logica toegevoegd om de benodigde parameters (+ id en data-attributen)
                        // toe te voegen indien ze ontbreken
                        // Geen ID? Dan zelf genereren
                        if (iframeId == null) {
                            iframeId = idTemplate + (idCounter++);

                            $(iframe).attr('id', iframeId);
                        }

                        // api=1 querystring parameter toevoegen
                        if (src.indexOf('api=') === -1) {
                            iframe.src += `${iframe.src.indexOf('?') === -1 ? '?' : '&'}api=1`;
                        }

                        // player-id toevoegen
                        if (src.indexOf('player_id=') === -1) {
                            iframe.src += `${iframe.src.indexOf('?') === -1 ? '?' : '&'}player_id=${$(iframe).attr('id')}`;
                        }

                        // data-seek toevoegen
                        if ($(iframe).data('seek') == null) {
                            $(iframe).data('seek', true);
                        }

                        // data-progress toevoegen
                        if ($(iframe).data('progress') == null) {
                            $(iframe).data('progress', true);
                        }

                        vimeoGAJS.eventMarker[iframeId] = {
                            progress25: false,
                            progress50: false,
                            progress75: false,
                            videoPlayed: false,
                            videoPaused: false,
                            videoResumed: false,
                            videoSeeking: false,
                            videoCompleted: false,
                            timePercentComplete: 0,
                        };
                    });

                    // DK @ 2015-12-15
                    // We gebruiken altijd universal analytics
                    vimeoGAJS.gaTracker = 'ua';

                    // Listen for messages from the player
                    if (window.addEventListener) {
                        window.addEventListener('message', vimeoGAJS.onMessageReceived, false);
                    } else {
                        window.attachEvent('onmessage', vimeoGAJS.onMessageReceived, false);
                    }
                },

                // Handle messages received from the player
                onMessageReceived(e) {
                    if (e.origin.replace('https:', 'http:') !== 'http://player.vimeo.com' || typeof vimeoGAJS.gaTracker === 'undefined') {
                        // console.warn('Tracker is missing!');
                        return;
                    }

                    const data = JSON.parse(e.data);
                    const iframeEl = $(`#${data.player_id}`);
                    const iframeId = iframeEl.attr('id');

                    switch (data.event) {
                    case 'ready':
                        vimeoGAJS.onReady();
                        break;

                    case 'playProgress':
                        vimeoGAJS.onPlayProgress(data.data, iframeEl);
                        break;

                    case 'seek':
                        if (iframeEl.data('seek') && !vimeoGAJS.eventMarker[iframeId].videoSeeking) {
                            vimeoGAJS.sendEvent(iframeEl, 'Seek');
                            vimeoGAJS.eventMarker[iframeId].videoSeeking = true; // Avoid subsequent seek trackings

                            // DK @ 2015-12-15
                            // We willen wel gewoon elke keer dat er wordt geseeked meten
                            // Waarom zouden we niet willen weten of iemand 5x in een video seeked?
                            // We gaan het echter pas na een delay op false zetten, want de Seek
                            // lijkt 2x achter elkaar te triggeren, dat moeten we voorkomen.
                            setTimeout(() => {
                                vimeoGAJS.eventMarker[iframeId].videoSeeking = false;
                            }, 500);
                        }
                        break;

                    case 'play':
                        if (!vimeoGAJS.eventMarker[iframeId].videoPlayed) {
                            vimeoGAJS.sendEvent(iframeEl, 'Play');
                            vimeoGAJS.eventMarker[iframeId].videoPlayed = true; // Avoid subsequent play trackings
                        } else if (!vimeoGAJS.eventMarker[iframeId].videoResumed && vimeoGAJS.eventMarker[iframeId].videoPaused) {
                            vimeoGAJS.sendEvent(iframeEl, 'Resume');

                            // DK @ 2015-12-15
                            // We willen wel gewoon elke keer dat een video wordt hervat meten
                            // Waarom zouden we niet willen weten of iemand 5x een video hervat?
                            // vimeoGAJS.eventMarker[iframeId].videoResumed = true; // Avoid subsequent resume trackings

                            // En tevens de "Paused" boolean weer op false zetten, zodat we ook opnieuw een Pause gaan sturen
                            vimeoGAJS.eventMarker[iframeId].videoPaused = false;
                        }
                        break;

                    case 'pause':
                        vimeoGAJS.onPause(iframeEl);
                        break;

                    case 'finish':
                        if (!vimeoGAJS.eventMarker[iframeId].videoCompleted) {
                            vimeoGAJS.sendEvent(iframeEl, 'Stop');
                            vimeoGAJS.eventMarker[iframeId].videoCompleted = true; // Avoid subsequent finish trackings
                        }
                        break;
                    }
                },

                getLabel(iframeEl) {
                    const iframeSrc = iframeEl.attr('src').split('?')[0];
                    let label = iframeSrc;
                    let title = iframeEl.data('title');

                    if (title == null) {
                        title = iframeEl.attr('title');
                    }

                    if (title != null) {
                        label += `: ${title}`;
                    }

                    return label;
                },

                // Helper function for sending a message to the player
                post(action, value, iframe) {
                    const data = {
                        method: action,
                    };

                    if (value) {
                        data.value = value;
                    }

                    // Source URL
                    const iframeSrc = $(iframe).attr('src').split('?')[0];

                    iframe.contentWindow.postMessage(JSON.stringify(data), iframeSrc);
                },

                onReady() {
                    $.each(vimeoGAJS.iframes, (index, iframe) => {
                        vimeoGAJS.post('addEventListener', 'play', iframe);
                        vimeoGAJS.post('addEventListener', 'seek', iframe);
                        vimeoGAJS.post('addEventListener', 'pause', iframe);
                        vimeoGAJS.post('addEventListener', 'finish', iframe);
                        vimeoGAJS.post('addEventListener', 'playProgress', iframe);
                    });
                },

                onPause(iframeEl) {
                    const iframeId = iframeEl.attr('id');

                    if (vimeoGAJS.eventMarker[iframeId].timePercentComplete < 99 && !vimeoGAJS.eventMarker[iframeId].videoPaused) {
                        vimeoGAJS.sendEvent(iframeEl, 'Pause');
                        vimeoGAJS.eventMarker[iframeId].videoPaused = true; // Avoid subsequent pause trackings
                    }
                },

                // Tracking video progress
                onPlayProgress(data, iframeEl) {
                    const iframeId = iframeEl.attr('id');

                    vimeoGAJS.eventMarker[iframeId].timePercentComplete = Math.round((data.percent) * 100); // Round to a whole number

                    if (!iframeEl.data('progress')) {
                        return;
                    }

                    let percentage;

                    if (vimeoGAJS.eventMarker[iframeId].timePercentComplete > 24 && !vimeoGAJS.eventMarker[iframeId].progress25) {
                        percentage = 25;
                        vimeoGAJS.eventMarker[iframeId].progress25 = true;
                    }

                    if (vimeoGAJS.eventMarker[iframeId].timePercentComplete > 49 && !vimeoGAJS.eventMarker[iframeId].progress50) {
                        percentage = 50;
                        vimeoGAJS.eventMarker[iframeId].progress50 = true;
                    }

                    if (vimeoGAJS.eventMarker[iframeId].timePercentComplete > 74 && !vimeoGAJS.eventMarker[iframeId].progress75) {
                        percentage = 75;
                        vimeoGAJS.eventMarker[iframeId].progress75 = true;
                    }

                    if (percentage) {
                        vimeoGAJS.sendEvent(iframeEl, 'Played', `${percentage}%`, percentage);
                    }
                },

                // Send event to Classic Analytics, Universal Analytics or Google Tag Manager
                sendEvent(iframeEl, action, label, value) {
                    const bounce = iframeEl.data('bounce');
                    var label = label || vimeoGAJS.getLabel(iframeEl);
                    var value = value;

                    // DK @ 2015-12-07
                    // nonInteraction parameter ging op basis van een data-attribuut "bounce",
                    // maar deze logica is weggehaald. nonInteraction moet altijd false zijn (spelen van een filmpje = interactie).
                    analytics.TrackEvent('Video', action, label, value);
                },
            };

            vimeoGAJS.init();
        }(jQuery));
    }

    /*
        JS 24-07-2018

        Dit script stuurt tijdens interactie steeds een tijd mee naar Google Analytics in de variable 'Metric1'. Deze wordt later gebruikt om een betere 'Tijd op pagina' te
        bepalen. Let op: Hiervoor moet een internetmarketeer in Google Analytics nog wel een berekend veld toevoegen.

        Let daarnaast op dat je deze variable in Metric1 mag stoppen en deze is aangemaakt in Google Analytics. Als deze niet is aangemaakt is het niet zo erg, maar als
        deze ergens anders voor bedoeld is, dan raakt die variabele in Google Analytics wat in de war.

        Mostly copied from these blogs: https://www.traffic-builders.com/content-analyse-script en https://www.simoahava.com/analytics/track-content-engagement-via-gtm/ en
        https://www.traffic-builders.com/app/uploads/2018/01/Content-Engagement-Script.pdf
    */
    function trackEngagement() {
        (function () {
            let startEngage = new Date().getTime();
            let timeEngaged = 0;
            let idleTime = 0;
            let idle = true;
            let idleReport = false;
            let idleTimer; let
                reportTimer;
            /*  Set the user as idle, and calculate the time
                they were non-idle */
            const setIdle = function () {
                idleTime = new Date().getTime();
                timeEngaged += idleTime - startEngage;
                idle = true;
            };
            /*  Reset the 5 second idle timer.
                If the user was idle, start the non-idle timer */
            const pulse = function (evt) {
                if (idle) {
                    idle = false;
                    startEngage = new Date().getTime();
                    idleReport = false;
                }
                window.clearTimeout(idleTimer);
                idleTimer = window.setTimeout(setIdle, 5000);
            };
            //  Utility function for attaching listeners to the window
            const addListener = function (evt, cb) {
                if (window.addEventListener) {
                    window.addEventListener(evt, cb);
                } else if (window.attachEvent) {
                    window.attachEvent(`on${evt}`, cb);
                }
            };
            /* Push an event to dataLayer every 15 seconds
               unless the user is idle.
               Also, push an event when the user leaves the page */
            var report = function (evt) {
                if (!idle) {
                    timeEngaged += new Date().getTime() - startEngage;
                }
                // Push the payload to dataLayer, and only push valid time values
                if (!idleReport && timeEngaged > 0 && timeEngaged < 3600000) {
                    timeEngaged /= 1000;
                    if (ga !== undefined) {
                        ga('set', 'metric1', timeEngaged);
                    }
                    analytics.TrackEvent('Engaged time', window.location.pathname, `${timeEngaged}`, undefined, true);
                }
                if (idle) {
                    idleReport = true;
                }
                // Fix possible beforeunload duplication problem
                if (evt && evt.type === 'beforeunload') {
                    window.removeEventListener('beforeunload', report);
                }
                timeEngaged = 0;
                startEngage = new Date().getTime();
                reportTimer = window.setTimeout(report, 15000);
            };

            addListener('mousedown', pulse);
            addListener('keydown', pulse);
            addListener('scroll', pulse);
            addListener('mousemove', pulse);
            addListener('beforeunload', report);
            idleTimer = window.setTimeout(setIdle, 5000);
            reportTimer = window.setTimeout(report, 15000);
        }());
    }

    /*
        JS 24-07-2018

        Dit script zorgt er voor dat het eerste formulier op een pagina met meer dan drie velden doormeten. Als er foutmeldingen worden getriggerd worden deze
        doorgemeten, en ook als je het formulier verlaat worden deze doorgemeten.
    */
    function trackAdvancedForm() {
        const relativePath = window.location.pathname;
        // Label van het laatste veld waarin de gebruiker is geweest
        // Triggert op focus
        let lastField = '';
        const changedFields = [];
        let validator = null;
        // true indien form succesvol wordt gesubmit
        // Dit gebruiken we om te weten of we bij een page leave
        // wel of niet het formulier succesvol hebben gesubmit
        // Bij de submit event zetten we deze eerst op 'false',
        // zo kunnen we dus ook zien dat iemand wel op submit heeft gedrukt,
        // anders dan wanneer deze null blijft dus, dan heeft iemand nooit een poging gedaan
        let validFormSubmit = null;

        let timestart = null;
        let timeend = null;
        let timeToSubmitSent = false;

        // We zoeken het formulier met de meeste velden. Dit om te voorkomen dat als er meerdere formulieren op de pagina zitten we niet weten welke we moeten kiezen.
        // Stel je hebt ook een stukje filtering of een login-ding op de pagina, dan moet je wel het echte formulier kiezen
        // zolang het minstens 3 velden heeft (hidden niet meegeteld)
        const $form = $($('form').filter(function () {
            return $(this).find('input,textarea,select').not('input[type="hidden"]').not('input[type="button"]').length >= 3;
        }));

        let $formToTrack;
        let numberOfFieldsOnForm = 0;

        $form.each(function () {
            if ($(this).find('input,textarea,select').not('input[type="hidden"]').not('input[type="button"]').length > numberOfFieldsOnForm) {
                numberOfFieldsOnForm = $(this).find('input,textarea,select').not('input[type="hidden"]').not('input[type="button"]').length;
                $formToTrack = $(this);
            }
        });

        // Geen formulier?
        // Dan kunnen we helaas niets
        if (!$formToTrack || $formToTrack.length === 0) return;

        // Submit knop meet timing
        $formToTrack.find('input[type="submit"]:last').on('click', () => {
            if (timeToSubmitSent) return;

            if (timestart === null) return;

            if (timeend === null) {
                timeend = getTime();
            }

            const time = timeend - timestart;

            const category = getAnalyticsCategory();

            // ES: deze funtie bestaat (nog) niet?
            // Perplex.Analytics.TrackTiming(category, "Tijd tot verzenden", time);

            timeToSubmitSent = true;
        });

        validator = $formToTrack.validate();
        initShowErrors();

        // We houden bij welke velden door de gebruiker worden
        // gewijzigd. Momenteel simpelweg alle inputs afgaan
        const $fields = $formToTrack.find('input,textarea,select').not('input[type="hidden"]').not('input[type="button"]');

        $fields.on('change', fieldOnChange);
        $fields.on('focus', fieldOnFocus);
        $(window).on('beforeunload', leavingPage);

        // Levert de naam op van deze input
        // element moet een jQuery object zijn, en een ID attribuut hebben
        // In principe leveren we het label op dat bij dit element hoort,
        // als de <label> voor het element staat. Anders returnen we maar het ID zelf,
        // een iets minder leesbare naam over het algemeen, maar beter dan niets.
        function getName($element) {
            if ($element.length !== 1) return;

            // ID attribuut is nodig voor het vinden van de juiste
            // label, en als fallback voor de naam
            const id = $element.attr('id');

            if (!id) return;

            // Vind het label van dit veld
            const $lbl = $formToTrack.find(`label[for="${id}"]`);

            // Geen label? Dan maar het ID
            if ($lbl.length === 0) return id;

            return $.trim($lbl.text()); // Zeker Umbraco Forms wil nog wel eens een hele hoop white-space toevoegen
        }

        function getTime() {
            if (window.performance && typeof window.performance.now === 'function') {
                return window.performance.now();
            }

            return new Date().getTime();
        }

        function initShowErrors() {
            if (!validator) return;

            const showErrorsFn = validator.settings.showErrors;

            validator.settings.showErrors = function (errorMap, errorList) {
                if (typeof showErrorsFn === 'function') {
                    showErrorsFn.apply(this, errorMap, errorList);
                }

                // De category is altijd hetzelfde
                const category = getAnalyticsCategory();
                const action = 'Formulier fouten';

                for (let i = 0; i < errorList.length; i++) {
                    const error = errorList[i];
                    const name = getName($(error.element));

                    const label = `${name} - ${error.message}`;

                    Perplex.Analytics.TrackEvent(category, action, label);
                }

                // En er is geen valid form gesubmit
                if (errorList.length > 0) {
                    validFormSubmit = false;
                }

                this.defaultShowErrors();
            };
        }

        function fieldOnChange() {
            // Een veld is voor het eerst aangepast?
            if (timestart === null) {
                timestart = getTime();
            }

            const name = getName($(this));

            // Zonder naam kunnen we niet veel
            if (!name) return;

            changedFields.push(name);
            lastField = name;
        }

        function fieldOnFocus() {
            // We houden het laatst gefocusde veld ook bij
            const name = getName($(this));

            // Zonder naam kunnen we niets
            if (!name) return;

            lastField = name;
        }

        function leavingPage() {
            if (changedFields.length > 0) {
                const category = getAnalyticsCategory();

                // Form abandonment
                // Alleen indien niet succesvol gesubmit
                if (!validFormSubmit) {
                    var action = 'Formulier verlaten';
                    var label = lastField;

                    Perplex.Analytics.TrackEvent(category, action, label, undefined, true);

                    // Wel geprobeerd te submitten, maar niet succesvol
                    if (validFormSubmit === false) {
                        const numErrors = $('.field-validation-error').length;

                        action = 'Formulier mislukte verzending';
                        var value = numErrors;

                        Perplex.Analytics.TrackEvent(category, action, '', numErrors, true);
                    }
                }

                // Interaction history
                var action = validFormSubmit ? 'Formulier verzending - historie formuliervelden' : 'Formulier verlaten - historie formuliervelden';
                var label = changedFields.join(' > ');
                var value = changedFields.length;

                Perplex.Analytics.TrackEvent(category, action, label, undefined, true);
            }
        }

        /**
         * @description Levert de categorie op voor alle events van deze module
         * @returns {string} De category om naar analytics op te sturen
         */
        function getAnalyticsCategory() {
            return `Form - ${relativePath}`;
        }
    }

    function MartiniTracking() {
        $('.js-tracking-menu-link').on('click', function (e) {
            const link = $(this).attr('href');

            Perplex.Analytics.TrackEvent('Navigatie', 'Hoofdmenu - Klik', link, undefined, true);
        });

        $('.js-tracking-footer-link').on('click', function (e) {
            const link = $(this).attr('href');

            if (link == null) {
                // link zit niveau dieper
                link.find('a').attr('href');
            }
            Perplex.Analytics.TrackEvent('Navigatie', 'Footer - Klik', link, undefined, false);
        });

        $('.js-tracking-toptaken-klik').on('click', function (e) {
            const buttonText = $(this).find('.js-tracking-toptaken-titel').text();

            Perplex.Analytics.TrackEvent('Navigatie', 'Quick-links - Weergave', buttonText, undefined, false);
        });

        $('.js-tracking-toptaken-content a, .js-tracking-toptaken-content button').on('click', function (e) {
            const url = $(this).attr('href');

            Perplex.Analytics.TrackEvent('Navigatie', 'Quick-links - Klik', url, undefined, false);
        });

        $('.js-tracking-sidebar-link a').on('click', function (e) {
            const url = $(this).attr('href');

            Perplex.Analytics.TrackEvent('Navigatie', 'Subnavigatie - Klik', url, undefined, false);
        });

        $('.js-tracking-zoeken-home').on('click', () => {
            Perplex.Analytics.TrackEvent('Zoekfunctie', 'Klik', 'Focus zoekfunctie homepage', undefined, false);
        });

        $('.js-tracking-zoeken-button').on('click', () => {
            let label = 'zoekfunctie header';
            const popupIsActiveBeforeClicking = $('html').hasClass('is-locked');

            if (popupIsActiveBeforeClicking) {
                label = `Sluit ${label}`;
            } else {
                label = `Open ${label}`;
            }
            Perplex.Analytics.TrackEvent('Zoekfunctie', 'Klik', label, undefined, false);
        });

        $(document).on('click', '.js-tracking-zoeken-poliafdeling-link', function (e) {
            const $item = $(this);
            let label = 'Klik - Auto aanvullen';

            if ($item.closest('#js-searchresults-sitewide').length > 0) {
                label += ' - Vanuit header';
            } else {
                label += ' - Vanuit homepage';
            }
            const link = $item.attr('href');
            const value = `${$item.closest('.js-search-wrapper').find('.js-search-input').val()} - ${link}`;

            Perplex.Analytics.TrackEvent('Zoekfunctie', label, value, false);
        });

        $(document).on('click', '.js-tracking-abz-link', function (e) {
            const $link = $(this);

            $zoekbalkBehandelingOnderzoek = $('.js-tracking-zoeken-overzicht-behandelingenonderzoeken');
            $zoekbalkPoliAfdeling = $('.js-tracking-zoeken-overzicht-poliafdeling');
            $zoekbalkSpecialismenExpertises = $('.js-tracking-zoeken-overzicht-specialismenexpertises');
            $zoekbalkSpecialisten = $('.js-tracking-zoeken-overzicht-specialisten');

            let trackingKlik = false;
            let zoekwoord = '';
            let tekst = 'Klik - Auto aanvullen - ';

            if ($zoekbalkBehandelingOnderzoek != undefined && $zoekbalkBehandelingOnderzoek.length > 0) {
                tekst += 'Behandelingen';
                trackingKlik = true;
                zoekwoord = $zoekbalkBehandelingOnderzoek.val();
            }
            if ($zoekbalkPoliAfdeling != undefined && $zoekbalkPoliAfdeling.length > 0) {
                tekst += 'Poli & afdelingen';
                trackingKlik = true;
                zoekwoord = $zoekbalkPoliAfdeling.val();
            }
            if ($zoekbalkSpecialismenExpertises != undefined && $zoekbalkSpecialismenExpertises.length > 0) {
                tekst += 'Specialismen';
                trackingKlik = true;
                zoekwoord = $zoekbalkSpecialismenExpertises.val();
            }
            if ($zoekbalkSpecialisten != undefined && $zoekbalkSpecialisten.length > 0) {
                tekst += 'Behandelaars';
                trackingKlik = true;
                zoekwoord = $zoekbalkSpecialisten.val();
            }

            if (zoekwoord != '') {
                zoekwoord = `${zoekwoord} - ${$link.attr('href')}`;
            } else {
                zoekwoord = $link.attr('href');
            }
            if (trackingKlik) {
                Perplex.Analytics.TrackEvent('Zoekfunctie', tekst, zoekwoord, undefined, false);
            }
        });

        $(document).on('click', '.js-tracking-abc-klik', function (e) {
            const $link = $(this);

            $zoekbalkBehandelingOnderzoek = $('.js-tracking-zoeken-overzicht-behandelingenonderzoeken');
            $zoekbalkPoliAfdeling = $('.js-tracking-zoeken-overzicht-poliafdeling');
            $zoekbalkSpecialismenExpertises = $('.js-tracking-zoeken-overzicht-specialismenexpertises');
            $zoekbalkSpecialisten = $('.js-tracking-zoeken-overzicht-specialisten');

            let trackingKlik = false;
            let tekst = 'Klik - Letter - ';

            if ($zoekbalkBehandelingOnderzoek != undefined && $zoekbalkBehandelingOnderzoek.length > 0) {
                tekst += 'Behandelingen';
                trackingKlik = true;
            }
            if ($zoekbalkPoliAfdeling != undefined && $zoekbalkPoliAfdeling.length > 0) {
                tekst += 'Poli & afdelingen';
                trackingKlik = true;
            }
            if ($zoekbalkSpecialismenExpertises != undefined && $zoekbalkSpecialismenExpertises.length > 0) {
                tekst += 'Specialismen';
                trackingKlik = true;
            }
            if ($zoekbalkSpecialisten != undefined && $zoekbalkSpecialisten.length > 0) {
                tekst += 'Behandelaars';
                trackingKlik = true;
            }

            if (trackingKlik) {
                Perplex.Analytics.TrackEvent('Zoekfunctie', tekst, $link.text(), undefined, false);
            }
        });

        // Pagina 19
    }

    return analytics;
}());
;
var Perplex = Perplex || {};

Perplex.Constants = {

    keyCodeMap: {
        48: '0',
        49: '1',
        50: '2',
        51: '3',
        52: '4',
        53: '5',
        54: '6',
        55: '7',
        56: '8',
        57: '9',
        59: ';',
        65: 'a',
        66: 'b',
        67: 'c',
        68: 'd',
        69: 'e',
        70: 'f',
        71: 'g',
        72: 'h',
        73: 'i',
        74: 'j',
        75: 'k',
        76: 'l',
        77: 'm',
        78: 'n',
        79: 'o',
        80: 'p',
        81: 'q',
        82: 'r',
        83: 's',
        84: 't',
        85: 'u',
        86: 'v',
        87: 'w',
        88: 'x',
        89: 'y',
        90: 'z',
        96: '0',
        97: '1',
        98: '2',
        99: '3',
        100: '4',
        101: '5',
        102: '6',
        103: '7',
        104: '8',
        105: '9',
    },

    keyCode: {
        CANCEL: 3,
        HELP: 6,
        BACK_SPACE: 8,
        TAB: 9,
        CLEAR: 12,
        RETURN: 13,
        ENTER: 14,
        SHIFT: 16,
        CONTROL: 17,
        ALT: 18,
        PAUSE: 19,
        CAPS_LOCK: 20,
        ESCAPE: 27,
        SPACE: 32,
        PAGE_UP: 33,
        PAGE_DOWN: 34,
        END: 35,
        HOME: 36,
        LEFT: 37,
        UP: 38,
        RIGHT: 39,
        DOWN: 40,
        PRINTSCREEN: 44,
        INSERT: 45,
        DELETE: 46,
        0: 48,
        1: 49,
        2: 50,
        3: 51,
        4: 52,
        5: 53,
        6: 54,
        7: 55,
        8: 56,
        9: 57,
        SEMICOLON: 59,
        EQUALS: 61,
        A: 65,
        B: 66,
        C: 67,
        D: 68,
        E: 69,
        F: 70,
        G: 71,
        H: 72,
        I: 73,
        J: 74,
        K: 75,
        L: 76,
        M: 77,
        N: 78,
        O: 79,
        P: 80,
        Q: 81,
        R: 82,
        S: 83,
        T: 84,
        U: 85,
        V: 86,
        W: 87,
        X: 88,
        Y: 89,
        Z: 90,
        CONTEXT_MENU: 93,
        NUMPAD0: 96,
        NUMPAD1: 97,
        NUMPAD2: 98,
        NUMPAD3: 99,
        NUMPAD4: 100,
        NUMPAD5: 101,
        NUMPAD6: 102,
        NUMPAD7: 103,
        NUMPAD8: 104,
        NUMPAD9: 105,
        MULTIPLY: 106,
        ADD: 107,
        SEPARATOR: 108,
        SUBTRACT: 109,
        DECIMAL: 110,
        DIVIDE: 111,
        F1: 112,
        F2: 113,
        F3: 114,
        F4: 115,
        F5: 116,
        F6: 117,
        F7: 118,
        F8: 119,
        F9: 120,
        F10: 121,
        F11: 122,
        F12: 123,
        F13: 124,
        F14: 125,
        F15: 126,
        F16: 127,
        F17: 128,
        F18: 129,
        F19: 130,
        F20: 131,
        F21: 132,
        F22: 133,
        F23: 134,
        F24: 135,
        NUM_LOCK: 144,
        SCROLL_LOCK: 145,
        COMMA: 188,
        PERIOD: 190,
        SLASH: 191,
        BACK_QUOTE: 192,
        OPEN_BRACKET: 219,
        BACK_SLASH: 220,
        CLOSE_BRACKET: 221,
        QUOTE: 222,
        META: 224,
    },

};
;
"use strict";var Perplex=Perplex||{};Perplex.Forms=function(){var n={};return n.Init=function(){var t,i,n,r;for($(".umbraco-forms-label").addClass("form__label"),$(".umbraco-forms-fieldset").addClass("form__fieldset l-item"),$(".umbraco-forms-fieldset").find("legend").addClass("form__legend"),$(".umbraco-forms-field h2").addClass("h3"),$(".umbraco-forms-field").addClass("form__row l-item l-item--none"),$(".umbraco-forms-navigation").addClass("form__row l-item l-item--none"),$(".umbraco-forms-field-wrapper").contents().unwrap(),$(".umbraco-forms-container").addClass("l-item"),$(".umbraco-forms-page").addClass("l-item l-item--xl"),$('.umbraco-forms-form input[type="text"]').addClass("form__input form__input--text"),$(".umbraco-forms-form textarea").addClass("form__input form__input--textarea"),$(".umbraco-forms-form select").addClass("form__input form__input--select"),$('.umbraco-forms-form input[type="date"]').addClass("form__input form__input--date"),$('.umbraco-forms-form input[type="file"]').addClass("form__input form__input--file"),$('.umbraco-forms-form input[type="email"]').addClass("form__input form__input--text"),$('.umbraco-forms-form input[type="tel"]').addClass("form__input form__input--text"),$(".multiplechoice .checkboxlist").addClass("form__checkbox__wrapper l-item l-item--xs"),t=$(".multiplechoice .checkboxlist > *"),n=0;n<t.length;n+=3)t.slice(n,n+3).wrapAll("<div class='l-item l-item--small'><\/div>");for($(".singlechoice").addClass("form__cb-parent"),$(".singlechoice .radiobuttonlist").addClass("form__cb-wrapper"),$(".singlechoice .radiobuttonlist input").addClass("form__cb-input"),$(".singlechoice .radiobuttonlist label").addClass("form__cb-label"),$(".singlechoice .radiobuttonlist input").wrap(""),i=$(".singlechoice .radiobuttonlist > *"),n=0;n<i.length;n+=3)i.slice(n,n+3).wrapAll("<div class='form__cb-item'><\/div>");$(".umbraco-forms-container br").remove();$(".validation-summary-valid").before($(".umbraco-forms-fieldset"));$(".field-validation-valid").addClass("form__error");r=$(".checkbox");$.each(r,function(n,t){var i=$(t);i.addClass("form__checkbox__wrapper");i.find("label").before(i.find("input[type=checkbox]"))});$('.umbraco-forms-field .umbraco-forms-label ~ input[type="checkbox"]').addClass("form__checkbox--childitem");$('.umbraco-forms-field .umbraco-forms-label ~ input[type="checkbox"] ~ label').addClass("form__checkbox--childitem");$(".form__checkbox--childitem").wrapAll('<div class="form__checkbox__wrapper"/>');$(".umbraco-forms-form form").addClass("form__umbraco");$(".umbraco-forms-form").addClass("active")},n}();;
/// <reference path="/Scripts/_references.js" />

//  JV - 06-08-2018
//  UMBRACO FORMS WIJZIGINGEN + JUISTE STLYING
//
//  Het beheren en toevoegen van classes en opbouw van Umbraco Forms via deze javascript-file.
//  Zo kan je Umbraco Forms blijven updaten zonder dat de styling uit elkaar valt of de forms ontoegankelijk worden.
//  Deze wordt ge-init in Perplex.js, waar je de file ook wer kan verwijderen of uitquoten

var Perplex = Perplex || {};

Perplex.Forms = (function () {
    const forms = {};

    forms.Init = function () {
        // elements

        $('.umbraco-forms-label').addClass('form__label');
        $('.umbraco-forms-fieldset').addClass('form__fieldset l-item');
        $('.umbraco-forms-fieldset').find('legend').addClass('form__legend');
        $('.umbraco-forms-field h2').addClass('h3');

        // change attributes

        // $('.umbraco-forms-form .datepickerfield').prop('type', 'date');

        // layout structure

        $('.umbraco-forms-field').addClass('form__row l-item l-item--none');
        $('.umbraco-forms-navigation').addClass('form__row l-item l-item--none');
        $('.umbraco-forms-field-wrapper').contents().unwrap();
        $('.umbraco-forms-container').addClass('l-item');
        $('.umbraco-forms-page').addClass('l-item l-item--xl');

        // add class based on type

        $('.umbraco-forms-form input[type="text"]').addClass('form__input form__input--text');
        $('.umbraco-forms-form textarea').addClass('form__input form__input--textarea');
        $('.umbraco-forms-form select').addClass('form__input form__input--select');
        $('.umbraco-forms-form input[type="date"]').addClass('form__input form__input--date');
        $('.umbraco-forms-form input[type="file"]').addClass('form__input form__input--file');
        $('.umbraco-forms-form input[type="email"]').addClass('form__input form__input--text');
        $('.umbraco-forms-form input[type="tel"]').addClass('form__input form__input--text');

        // checkbox list standaard package

        // $('.multiplechoice').addClass('form__cb-parent');
        // $('.multiplechoice .checkboxlist').addClass('form__cb-wrapper');
        // $('.multiplechoice .checkboxlist input').addClass('form__cb-input');
        // $('.multiplechoice .checkboxlist label').addClass('form__cb-label');
        // $('.multiplechoice .checkboxlist input').wrap('');
        // var itemsMultiple = $(".multiplechoice .checkboxlist > *");
        // for (var i = 0; i < itemsMultiple.length; i += 3) { itemsMultiple.slice(i, i + 3).wrapAll("<div class='form__cb-item'></div>"); };

        $('.multiplechoice .checkboxlist').addClass('form__checkbox__wrapper l-item l-item--xs');
        const itemsMultiple = $('.multiplechoice .checkboxlist > *');

        for (var i = 0; i < itemsMultiple.length; i += 3) { itemsMultiple.slice(i, i + 3).wrapAll("<div class='l-item l-item--small'></div>"); }

        // checkbox list

        $('.singlechoice').addClass('form__cb-parent');
        $('.singlechoice .radiobuttonlist').addClass('form__cb-wrapper');
        $('.singlechoice .radiobuttonlist input').addClass('form__cb-input');
        $('.singlechoice .radiobuttonlist label').addClass('form__cb-label');
        $('.singlechoice .radiobuttonlist input').wrap('');
        const itemsSingle = $('.singlechoice .radiobuttonlist > *');

        for (var i = 0; i < itemsSingle.length; i += 3) { itemsSingle.slice(i, i + 3).wrapAll("<div class='form__cb-item'></div>"); }

        // remove elements

        $('.umbraco-forms-container br').remove();

        // errors

        $('.validation-summary-valid').before($('.umbraco-forms-fieldset'));
        $('.field-validation-valid').addClass('form__error');

        // single checkbox

        const $checkboxWrappers = $('.checkbox');

        $.each($checkboxWrappers, (k, v) => {
            const $checkboxWrap = $(v);

            $checkboxWrap.addClass('form__checkbox__wrapper');
            $checkboxWrap.find('label').before($checkboxWrap.find('input[type=checkbox]'));
        });
        // $('.checkbox label').addClass('form__label--cb');
        // $('input[type="checkbox"]').closest('.umbraco-forms-field').addClass('form__checkbox__wrapper');

        // INDENTIFY CHECKBOX CHECKBOX AND LABEL TO WRAP THEM
        $('.umbraco-forms-field .umbraco-forms-label ~ input[type="checkbox"]').addClass('form__checkbox--childitem');
        $('.umbraco-forms-field .umbraco-forms-label ~ input[type="checkbox"] ~ label').addClass('form__checkbox--childitem');
        $('.form__checkbox--childitem').wrapAll('<div class="form__checkbox__wrapper"/>');

        $('.umbraco-forms-form form').addClass('form__umbraco');
        $('.umbraco-forms-form').addClass('active');
    };

    return forms;
}());
;
var Perplex = Perplex || {};

Perplex.Global = (function () {
    const global = {};

    global.Init = function () {
        smoothPageload();
        smoothScrollToAnchors();
        viewportChecker();
        toggleTabs();
        switchTabs();
        sliderHome();
        sliderCollegas();
        sliderErvaringen();
        sliderNews();
        sliderAlbum();
        ervaringMorebutton();
        headerScrolled();
        toggleFaq();
        tabsWrapperSplit();
        printPage();
        headerHeight();
        toggleMijnmartini();
        alertbar();
        tabindexSet();
        tabindexReset();
        tabindexResetting();
        toggleInfoMobile();
        toggleContactMobile();

        function toggleInfoMobile() {
            const toggleInfoButton = '.js-inpage__toggle';
            const toggleInfoLink = '.js-inpage__nav .link';

            $(toggleInfoButton).click(function () {
                if ($(this).hasClass('c-contentpage__nav__subtitle--active')) {
                    $('.c-contentpage__nav__subtitle').removeClass('c-contentpage__nav__subtitle--active');
                    $('.c-contentpage__nav__list').hide();
                    $('.c-contentpage__bottombar').removeClass('c-contentpage__bottombar--active');
                } else {
                    $('.c-contentpage__nav__subtitle').removeClass('c-contentpage__nav__subtitle--active');
                    $('.c-contentpage__nav__list').hide();
                    $(this).addClass('c-contentpage__nav__subtitle--active');
                    $(this).next('.c-contentpage__nav__list').show();
                    $('.c-contentpage__bottombar').addClass('c-contentpage__bottombar--active');
                }
            });

            $(toggleInfoLink).click(() => {
                $('.c-contentpage__nav__subtitle').removeClass('c-contentpage__nav__subtitle--active');
                $('.c-contentpage__nav__list').hide();
                $('.c-contentpage__bottombar').removeClass('c-contentpage__bottombar--active');
            });
        }

        function toggleContactMobile() {
            const toggleButton = '.js-contact__toggle';
            const toggleWrapper = '.js-contact__wrapper';

            if (toggleButton && toggleWrapper) {
                if (window.innerWidth <= 750) {
                    $(toggleWrapper).hide();

                    $(toggleButton).click(function () {
                        if ($(this).hasClass('c-contentpage__nav__subtitle--active')) {
                            $(this).removeClass('c-contentpage__nav__subtitle--active');
                            $(toggleWrapper).hide();
                        } else {
                            $(this).addClass('c-contentpage__nav__subtitle--active');
                            $(toggleWrapper).show();
                        }
                    });
                }
            }
        }

        // Pagina printen
        function printPage() {
            $('.js-print').click(() => {
                window.print();
            });
        }

        // toggle voor dropdown in het menu naar mijn martini
        function toggleMijnmartini() {
            const toggleButton = '.js-btn-mijnmartini';
            const toggleButtonVanilla = document.querySelector(toggleButton);
            const toggleList = '.js-list-mijnmartini';
            const toggleClass = 'btn--mijnmartini__wrapper--active';

            $(document).on('click', toggleButton, function (e) {
                if (!$(this).hasClass(toggleClass)) {
                    $(this).addClass(toggleClass);
                    $(toggleList).slideDown(200);
                } else {
                    $(this).removeClass(toggleClass);
                    $(toggleList).slideUp(200);
                }
            });

            $(document).keyup((e) => {
                if ((e.keyCode === 27) && ($('.btn--mijnmartini__wrapper--active').length)) {
                    $(toggleButton).removeClass(toggleClass);
                    $(toggleList).slideUp(200);
                }
            });

            // close when click outside
            document.addEventListener('click', (event) => {
                const isClickInside = toggleButtonVanilla.contains(event.target);

                if (!isClickInside) {
                    $(toggleButton).removeClass(toggleClass);
                    $(toggleList).slideUp(200);
                }
            });
        }

        // calamiteiten balk boven menu
        function alertbar() {
            if (typeof (localStorage) !== 'undefined') {
                const hideAlertbar = window.localStorage.getItem('hideAlertbar');

                if (hideAlertbar == 'true') {
                    $('.js-alertbar').hide();
                    headerHeight();
                } else {
                    // we hebben hem niet weg geklikt dus tonen we hem
                    $('.js-alertbar').show();
                    headerHeight();
                }
            } else {
                // We hebben geen sessiestorage, dus tonen we hem altijd
                $('.js-alertbar').show();
                headerHeight();
            }
            // Hide search popup when clicking outside searchbar and show when clicking inside
            $('.js-alertbar-close').on('click', function () {
                $(this).closest('.js-alertbar').hide();
                headerHeight();
                if (typeof (sessionStorage) !== 'undefined') {
                    window.sessionStorage.setItem('hideAlertbar', 'true');
                }
            });
        }

        // Hide search popup when clicking outside searchbar and show when clicking inside
        $('.js-alertbar-close').on('click', function () {
            $(this).closest('.js-alertbar').hide();

            // headerheight opnieuw bepalen
            const headerHeight = $('.js-header-container').outerHeight();

            $('body').css('padding-top', headerHeight);
            if (window.matchMedia('(max-width:768px)').matches) {
                $('.c-nav__parent').css('top', headerHeight - 3);
                $('.c-nav__sublist').css('top', headerHeight - 3);
            }

            if (typeof (localStorage) !== 'undefined') {
                window.localStorage.setItem('hideAlertbar', 'true');
            }
        });

        // berekenen van hoogte van de header
        function headerHeight() {
            const headerHeight = $('.js-header-container').outerHeight();

            $('body').css('padding-top', headerHeight);
            if (window.matchMedia('(max-width:768px)').matches) {
                $('.c-nav__parent').css('top', headerHeight - 3);
                $('.c-nav__sublist').css('top', headerHeight - 3);
            }
        }

        // Add ?rel=0 to all Yotubue urls found on page
        $('iframe').each((k, v) => {
            if (v.outerHTML.indexOf('youtu') > 0) {
                const iframeElement = $(v);
                const isYoutubeVideo = iframeElement.attr('src').match('^(https?\:\/\/)?(www\.youtube\.com|youtu\.?be)\/.+$');

                if (isYoutubeVideo != null && isYoutubeVideo.length > 1) {
                    iframeElement.attr('src', `${iframeElement.attr('src')}&rel=0`);
                }
            }
        });
    };

    // toggle om het tonen van verschillende blokken te wisselen. bijvoorbeeld faq
    function toggleTabs() {
        if (window.matchMedia('(min-width: 768px)').matches) {
            $('.c-tabs__wrapper').find('.c-tabs__item:first-of-type').addClass('c-tabs__item--active');
        }

        $('.js-tabs > button').click(function () {
            if ($(this).parent().hasClass('c-tabs__item--active')) {
                $(this).parent().removeClass('c-tabs__item--active');
            } else {
                $(this).parent().addClass('c-tabs__item--active');
            }
        });
    }

    // toptaken in homepage toggle
    function tabsWrapperSplit() {
        if (window.matchMedia('(min-width: 768px)').matches) {
            let h = 0;

            $('.js-tabs--split .c-tabs__item').each(function () { h += $(this).height(); });
            $('.js-tabs--split .c-tabs__item .c-tabs__content').css('min-height', h + 50);

            const height = $('.js-tabs--split').find('.c-tabs__item:first-of-type').find('.c-tabs__content').outerHeight();

            $('.js-tabs--split').css('min-height', height);

            $('.js-tabs--split .c-tabs__title').click(function () {
                $('.js-tabs--split').css('min-height', 0);
                const height = $(this).next('.c-tabs__content').outerHeight();

                $('.js-tabs--split').css('min-height', height);
            });
        }
    }

    // faq toggle
    function toggleFaq() {
        $('.c-faq__wrapper').first().find('.c-faq__item:first-of-type').addClass('c-faq__item--active');

        $(document).on('click', '.js-faq > button', function (e) {
            e.preventDefault();

            if (!$(this).parent().hasClass('c-faq__item--active')) {
                $('.js-faq').removeClass('c-faq__item--active');
                $(this).parent().addClass('c-faq__item--active');

                $('.js-faq > .vh').text('Inhoud weergeven');
                $(this).parent().find('.vh').text('Inhoud verbergen (actief)');
            } else {
                $(this).parent().removeClass('c-faq__item--active');
                $(this).parent().find('.vh').text('Inhoud weergeven');
            }
        });
    }

    // toptaken tabs toggle
    function switchTabs() {
        $('.js-switch-tabs > button').click(function (e) {
            e.preventDefault();

            if (!$(this).parent().hasClass('c-tabs__item--active')) {
                $('.js-switch-tabs').removeClass('c-tabs__item--active');
                $(this).parent().addClass('c-tabs__item--active');

                setTabLabel($(this));
            } else if (window.matchMedia('(max-width:768px)').matches) {
                $('.js-switch-tabs').removeClass('c-tabs__item--active');
            }
        });

        function setTabLabel(clickedButton) {
            $('.js-switch-tabs > button').children('.vh').text('Inhoud weergeven');
            clickedButton.children('.vh').text('Inhoud verbergen (actief)');
        }

        setTabLabel($('.c-tabs__item--active > button'));
    }

    // volgt elementen of ze in de viewport te zien zijn
    function viewportChecker() {
        $('.c-hero__container').viewportChecker();
        $('.c-abc__results').viewportChecker();
        $('.c-hero__item').viewportChecker();
    }

    // verkleinen vann de header nadat gescrollt is
    function headerScrolled() {
        $(window).scroll(() => {
            const windscrolltop = $(window).scrollTop();

            if (windscrolltop >= 100) {
                $('.js-nav__parent').addClass('scrolled');
            } else {
                $('.js-nav__parent').removeClass('scrolled');
            }
        });
    }

    /**
     * Bind onclick handlers aan elke <a href="#..."> zodat er smooth wordt gescrolld naar de target.
     * Target kan zijn een <a name="..."> en anders een element met als id #...
     */
    function smoothScrollToAnchors() {
        $(document).on('click', 'a[href^="#"]:not([href="#"])', function (event) {
            event.preventDefault();

            const hash = $(this).attr('href');

            // We zoeken naar een element met als "name" attribuut
            // de inhoud van de hash (zonder #), en anders naar een
            // element met als id attribuut de inhoud van de hash (ook zonder #).
            const $target = $(`*[name="${hash.substring(1)}"],${hash}`);

            if ($target.length === 0) {
                // Niet gevonden
                return;
            }

            // OFFSET VOOR DE HEADER ALS DIE GEVONDEN KAN WORDEN
            let $header = 0;
            let $h2nav = 0;

            if ($('.js-header-container').length) {
                $header = $('.js-header-container').outerHeight();
            }
            if ($('.js-heading-anchors').length) {
                $h2nav = $('.js-heading-anchors').outerHeight();
            }

            $offsetheader = $header + $h2nav;

            Perplex.Util.scrollToElement($target, {
                // Focus element na scroll
                focus: true,
                offset: $offsetheader,

                // Update hash in URL na scroll,
                // dit gebeurt standaard niet omdat we event.preventDefault() doen
                hash,
            });
        });
    }

    /*
        Door: JV
        Deze functie zorgt voor een gelikte transitie van de ene pagina na de andere. Het wordt niet ingevoerd bij mailto-links en ctrl + click en linkjes met een "js-" class.
    */
    function smoothPageload() {
        $('a:not([class*="js-"]):not([target="_blank"])').each(function () {
            if (location.hostname === this.hostname || !this.hostname.length) {
                const link = $(this).attr('href');

                if (!(link && link.length)) {
                    return;
                }
                if (link.match('^#') || link.match('^mailto') || link.match('pdf$') || link.match('png$') || link.match('jpg$')) {

                } else {
                    $(this).click((e) => {
                        e.preventDefault();

                        if (e.ctrlKey) { window.open(link, '_blank'); } else {
                            $('body').addClass('page-out');
                            setTimeout(() => { window.location = link; }, 500);

                            // $("html, body").animate({ scrollTop: 0 }, 400);
                            return false;
                        }
                    });
                }
            }
        });
    }

    function ervaringMorebutton() {
        $(document).on('click', '.js-ervaring-morebutton', function () {
            if ($(this).parent().hasClass('active')) {
                $(this).parent().removeClass('active');
                $(this).parent().find('.c-ervaring__text').slideUp(200);
                $(this).text('Lees meer');
            } else {
                $(this).parent().addClass('active');
                $(this).parent().find('.c-ervaring__text').slideDown(200);
                $(this).text('Sluiten');
            }
        });
    }

    function sliderHome() {
        $('.js-slider-home').slick({
            slidesToShow: 1,
            slidesToScroll: 1,
            infinite: false,
            adaptiveHeight: true,
            autoplay: false,
        });
    }

    function sliderCollegas() {
        $('.js-slider-collegas').slick({
            slidesToShow: 3,
            slidesToScroll: 3,
            infinite: false,
            adaptiveHeight: true,
            responsive: [
                {
                    breakpoint: 1024,
                    settings: {
                        slidesToShow: 3,
                        slidesToScroll: 3,
                    },
                }, {
                    breakpoint: 768,
                    settings: {
                        slidesToShow: 2,
                        slidesToScroll: 2,
                    },
                }],
        });
    }

    function sliderErvaringen() {
        $('.js-slider-ervaringen').slick({
            slidesToShow: 1,
            slidesToScroll: 1,
            infinite: false,
            adaptiveHeight: false,
            prevArrow: $('.c-ervaring__slider-btns .slick-prev'),
            nextArrow: $('.c-ervaring__slider-btns .slick-next'),
            mobileFirst: true,
            dots: true,
            responsive: [
                {
                    breakpoint: 768,
                    settings: {
                        dots: false,
                    },
                }],
        });
    }

    function sliderNews() {
        if (window.matchMedia('(min-width: 1024px)').matches) {
            $('.js-slider-news').slick({
                slidesToShow: 1,
                slidesToScroll: 1,
                infinite: false,
                arrows: false,
                fade: true,
                asNavFor: '.js-slider-news-nav',
                focusOnSelect: true,
                responsive: [
                    {
                        breakpoint: 1024,
                        settings: {
                            adaptiveHeight: true,
                        },
                    }],
            });

            $('.js-slider-news-nav').slick({
                slidesToShow: $('.js-slider-news').slick('getSlick').slideCount,
                slidesToScroll: 1,
                arrows: false,
                vertical: true,
                asNavFor: '.js-slider-news',
                focusOnSelect: true,
            });

            $('.js-slider-news').on('setPosition', function () {
                const slickTrack = $(this).find('.slick-track').first();
                const slickTrackHeight = $(slickTrack).height();

                $(this).find('.slick-track').first().find('>.slick-slide .c-hero__container')
                    .css('height', `${slickTrackHeight}px`);
            });
        }
    }

    function sliderAlbum() {
        $('.js-slider-album').slick({
            slidesToShow: 1,
            slidesToScroll: 1,
            infinite: false,
            arrows: false,
            fade: true,
            adaptiveHeight: false,
            autoplay: true,
            autoplaySpeed: 5000,
            asNavFor: '.js-slider-album-nav',
        });

        $('.js-slider-album-nav').slick({
            slidesToShow: 5,
            slidesToScroll: 1,
            arrows: true,
            vertical: false,
            asNavFor: '.js-slider-album',
            focusOnSelect: true,
            responsive: [
                {
                    breakpoint: 768,
                    settings: {
                        slidesToShow: 3,
                        arrows: false,
                    },
                }, {
                    breakpoint: 1024,
                    settings: {
                        slidesToShow: 4,

                    },
                }, {
                    breakpoint: 1300,
                    settings: {
                        slidesToShow: 5,
                    },
                }],
        });
    }

    const tabindexLink = '.js-tabindex-link';
    const tabindexClose = '.js-tabindex-close';
    const tabindexParent = '.js-tabindex-parent';
    const tabindexSelectors = '[href],area[href],input:not([disabled]),select:not([disabled]),textarea:not([disabled]),button:not([disabled]),iframe,[tabindex],[contentEditable=true]';
    const tabindexSelectorsReset = '[href][tabindex="-1"],area[href][tabindex="-1"],input:not([disabled])[tabindex="-1"],select:not([disabled])[tabindex="-1"],textarea:not([disabled])[tabindex="-1"],button:not([disabled])[tabindex="-1"],iframe[tabindex="-1"],[tabindex][tabindex="-1"],[contentEditable=true][tabindex="-1"]';
    const tabindexFocus = '.js-tabindex-focus';
    const tabindexFocusClass = 'js-tabindex-focus';

    function tabindexSet() {
        // click function

        $(tabindexLink).click(function () {
            const tabindexDatalink = $(this).data('link');
            const tabindexSelector = $(` ${tabindexParent}[data-target= ${tabindexDatalink}]`);

            // Set class to clicked element to return focus
            $(this).addClass(tabindexFocusClass);

            // Set negative tabindex to all items
            $(document).find(tabindexSelectors).attr('tabindex', -1);

            // Remove tabindex from elements inside parent
            tabindexSelector.find(tabindexSelectors).removeAttr('tabindex');

            tabindexSelector.find(tabindexSelectors).addClass('tabindex');

            // Set tabindex of -1 to parent element
            tabindexSelector.attr('tabindex', -1);

            // Set focus to this element
            tabindexSelector.focus();
        });
    }

    function tabindexResetting() {
        // reset the tabindex off all the items
        $(document).find(tabindexSelectorsReset).removeAttr('tabindex');

        // set focus
        $(tabindexFocus).focus();

        // remove focus clas
        $(tabindexFocus).removeClass(tabindexFocusClass);
    }

    function tabindexReset() {
        // close function

        $(tabindexClose).click(() => {
            tabindexResetting();
        });

        // toggle function

        $(tabindexFocus).click(() => {
            tabindexResetting();
        });

        // escape key function

        $(document).keyup((e) => {
            if (e.keyCode === 27) {
                tabindexResetting();
            }
        });
    }

    return global;
}());
;
var Perplex = Perplex || {};

Perplex.Menu = (function () {
    const menu = {};

    menu.Init = function () {
        initPlugin();
        detectIfSubmenuIsOutView();

        $('.js-nav__list').setup_navigation();
    };

    function initPlugin() {
        $.fn.setup_navigation = function (settings) {
            settings = jQuery.extend(
                {
                    menuHoverClass: 'c-nav__sublist--active',
                },
                settings,
            );

            $(this)
                .attr('role', 'menubar')
                .find('li')
                .attr('role', 'menuitem');
            const top_level_links = $(this).find('> li > a');

            const links = $(top_level_links)
                .parent('li')
                .find('ul a');

            $(top_level_links)
                .next('ul')
                .attr({
                    'aria-hidden': 'true',
                    role: 'menu',
                })
                .find('a')
                .attr('tabIndex', -1);

            $(top_level_links).each(function () {
                if ($(this).next('ul').length > 0) {
                    $(this)
                        .parent('li')
                        .attr('aria-haspopup', 'true');
                }
            });

            $(top_level_links).hover(function () {
                $(this)
                    .closest('ul')
                    .attr('aria-hidden', 'false')
                    .find(`.${settings.menuHoverClass}`)
                    .attr('aria-hidden', 'true')
                    .removeClass(settings.menuHoverClass)
                    .find('a')
                    .attr('tabIndex', -1);
                $(this)
                    .next('ul')
                    .attr('aria-hidden', 'false')
                    .addClass(settings.menuHoverClass)
                    .find('a')
                    .attr('tabIndex', 0);
            });

            $(top_level_links).focus(function () {
                $(this)
                    .closest('ul')
                    .find(`.${settings.menuHoverClass}`)
                    .attr('aria-hidden', 'true')
                    .removeClass(settings.menuHoverClass)
                    .find('a')
                    .attr('tabIndex', -1);
                $(this)
                    .next('ul')
                    .attr('aria-hidden', 'false')
                    .addClass(settings.menuHoverClass)
                    .find('a')
                    .attr('tabIndex', 0);
            });

            $(top_level_links).keydown(function (e) {
                if (e.keyCode === Perplex.Constants.keyCode.LEFT) {
                    handlePressKeyEventLeftForTopLevelLinks(e);
                } else if (e.keyCode === Perplex.Constants.keyCode.UP) {
                    handlePressKeyEventUpForTopLevelLinks(e);
                } else if (e.keyCode === Perplex.Constants.keyCode.RIGHT) {
                    handlePressKeyEventRightForTopLevelLinks(e);
                } else if (e.keyCode === Perplex.Constants.keyCode.DOWN) {
                    handlePressKeyEventDownForTopLevelLinks(e);
                } else if (e.keyCode === Perplex.Constants.keyCode.SPACE) {
                    handlePressKeyEventSpaceForTopLevelLinks(e, this);
                } else if (e.keyCode === Perplex.Constants.keyCode.ESCAPE) {
                    handlePressKeyEventEscapeForTopLevelLinks(e);
                } else {
                    handlePressKeyEventOtherForTopLevelLinks(e);
                }
            });

            $(links).keydown((e) => {
                if (e.keyCode === Perplex.Constants.keyCode.UP) {
                    handlePressKeyEventUpForLinks(e);
                } else if (e.keyCode === Perplex.Constants.keyCode.DOWN) {
                    handlePressKeyEventDownForLinks(e);
                } else if (e.keyCode === Perplex.Constants.keyCode.ESCAPE || e.keyCode === Perplex.Constants.keyCode.LEFT) {
                    handlePressKeyEventEscapeOrLeftForLinks(e);
                } else if (e.keyCode === Perplex.Constants.keyCode.SPACE) {
                    handlePressKeyEventSpaceForLinks(e);
                } else {
                    handleOtherPressKeyEventForLinks(e);
                }
            });

            function handlePressKeyEventLeftForTopLevelLinks(e) {
                e.preventDefault();
                if ($(this).parent('li').prev('li').length === 0) {
                    $(this)
                        .parents('ul')
                        .find('> li')
                        .last()
                        .find('a')
                        .first()
                        .focus();
                } else {
                    $(this)
                        .parent('li')
                        .prev('li')
                        .find('a')
                        .first()
                        .focus();
                }
            }

            function handlePressKeyEventUpForTopLevelLinks(e) {
                e.preventDefault();
                if (
                    $(this)
                        .parent('li')
                        .find('ul').length > 0
                ) {
                    $(this)
                        .parent('li')
                        .find('ul')
                        .attr('aria-hidden', 'false')
                        .addClass(settings.menuHoverClass)
                        .find('a')
                        .attr('tabIndex', 0)
                        .last()
                        .focus();
                }
            }

            function handlePressKeyEventRightForTopLevelLinks(e) {
                e.preventDefault();
                if (
                    $(this)
                        .parent('li')
                        .next('li').length === 0
                ) {
                    $(this)
                        .parents('ul')
                        .find('> li')
                        .first()
                        .find('a')
                        .first()
                        .focus();
                } else {
                    $(this)
                        .parent('li')
                        .next('li')
                        .find('a')
                        .first()
                        .focus();
                }
            }

            function handlePressKeyEventDownForTopLevelLinks(e) {
                e.preventDefault();
                if (
                    $(this)
                        .parent('li')
                        .find('ul').length > 0
                ) {
                    $(this)
                        .parent('li')
                        .find('ul')
                        .attr('aria-hidden', 'false')
                        .addClass(settings.menuHoverClass)
                        .find('a')
                        .attr('tabIndex', 0)
                        .first()
                        .focus();
                }
            }

            function handlePressKeyEventSpaceForTopLevelLinks(event, element) {
                event.preventDefault();
                element.click();
            }

            function handlePressKeyEventEscapeForTopLevelLinks(e) {
                e.preventDefault();
                $(`.${settings.menuHoverClass}`)
                    .attr('aria-hidden', 'true')
                    .removeClass(settings.menuHoverClass)
                    .find('a')
                    .attr('tabIndex', -1);
            }

            function handlePressKeyEventOtherForTopLevelLinks(e) {
                $(this)
                    .parent('li')
                    .find('ul[aria-hidden=false] a')
                    .each(function () {
                        if (
                            $(this)
                                .text()
                                .substring(0, 1)
                                .toLowerCase() === Perplex.Constants.keyCodeMap[e.keyCode]
                        ) {
                            $(this).focus();

                            return false;
                        }
                    });
            }

            function handlePressKeyEventUpForLinks(e) {
                e.preventDefault();
                if (
                    $(this)
                        .parent('li')
                        .prev('li').length === 0
                ) {
                    $(this)
                        .parents('ul')
                        .parents('li')
                        .find('a')
                        .first()
                        .focus();
                } else {
                    $(this)
                        .parent('li')
                        .prev('li')
                        .find('a')
                        .first()
                        .focus();
                }
            }

            function handlePressKeyEventDownForLinks(e) {
                e.preventDefault();
                if (
                    $(this)
                        .parent('li')
                        .next('li').length === 0
                ) {
                    $(this)
                        .parents('ul')
                        .parents('li')
                        .find('a')
                        .first()
                        .focus();
                } else {
                    $(this)
                        .parent('li')
                        .next('li')
                        .find('a')
                        .first()
                        .focus();
                }
            }

            function handlePressKeyEventEscapeOrLeftForLinks(e) {
                e.preventDefault();
                $(this)
                    .parents('ul')
                    .first()
                    .prev('a')
                    .focus()
                    .parents('ul')
                    .first()
                    .find(`.${settings.menuHoverClass}`)
                    .attr('aria-hidden', 'true')
                    .removeClass(settings.menuHoverClass)
                    .find('a')
                    .attr('tabIndex', -1);
            }

            function handlePressKeyEventSpaceForLinks(e) {
                e.preventDefault();
                window.location = $(this).attr('href');
            }

            function handleOtherPressKeyEventForLinks(e) {
                let found = false;

                $(this)
                    .parent('li')
                    .nextAll('li')
                    .find('a')
                    .each(function () {
                        if (
                            $(this)
                                .text()
                                .substring(0, 1)
                                .toLowerCase() === Perplex.Constants.keyCodeMap[e.keyCode]
                        ) {
                            $(this).focus();
                            found = true;

                            return false;
                        }
                    });
                if (!found) {
                    $(this)
                        .parent('li')
                        .prevAll('li')
                        .find('a')
                        .each(function () {
                            if (
                                $(this)
                                    .text()
                                    .substring(0, 1)
                                    .toLowerCase() === Perplex.Constants.keyCodeMap[e.keyCode]
                            ) {
                                $(this).focus();

                                return false;
                            }
                        });
                }
            }

            $(this)
                .find('a')
                .last()
                .keydown((e) => {
                    if (e.keyCode === 9) {
                        $(`.${settings.menuHoverClass}`)
                            .attr('aria-hidden', 'true')
                            .removeClass(settings.menuHoverClass)
                            .find('a')
                            .attr('tabIndex', -1);
                    }
                });

            $(document).click(() => {
                // Remove hover classes
                $(`.${settings.menuHoverClass}`)
                    .attr('aria-hidden', 'true')
                    .removeClass(settings.menuHoverClass)
                    .find('a')
                    .attr('tabIndex', -1);

                // Remove s-toggled classes of buttons
                // $(".s-toggled").removeClass("s-toggled");
            });

            $(this).click((e) => {
                e.stopPropagation();
            });

            function setPaddingLeft() {
                const subnavs = document.querySelectorAll('.js-tabindex-parent');

                Array.from(subnavs).forEach((el) => {
                    const sublistContainer = el.querySelector(':scope > .c-nav__sublist .l-content');
                    const subnavText = el.querySelector(':scope > .c-nav__link span');

                    if (subnavText && sublistContainer) {
                        const offsetLeft = subnavText.getBoundingClientRect().left - document.body.getBoundingClientRect().left;

                        if (window.innerWidth >= 1024) {
                            sublistContainer.style.paddingInlineStart = `${offsetLeft}px`;
                        } else {
                            sublistContainer.style.paddingInlineStart = '';
                        }
                    }
                });
            }

            window.addEventListener('load', () => {
                setPaddingLeft();
            });

            window.addEventListener('resize', () => {
                setTimeout(() => {
                    setPaddingLeft();
                }, 1000);
            });

            $('.c-nav__item--subnav').on('mouseenter mouseleave', function (e) {
                // Niets doen indien mobiele menu zichtbaar is
                if ($('.c-headermob__menu').is(':visible') || $('.js-nav__parent').hasClass('s-open')) {
                    return;
                }

                const $button = $(this).find('> .c-nav__subtoggle');

                const openMenu = e.type === 'mouseover' || e.type === 'mouseenter';

                toggleNav($button, openMenu, e.target);
            });

            $('.js-toggleSub').on('click', function () {
                toggleNav($(this), !$(this).hasClass('s-toggled'));
            });

            function toggleNav($button, openNav) {
                const $ul = $button.next('ul');

                if (openNav) {
                    $ul.addClass('s-open');
                    $button.addClass('s-toggled');
                    $ul.attr('aria-hidden', 'false');
                } else {
                    $ul.removeClass('s-open');
                    $button.removeClass('s-toggled');
                    $ul.attr('aria-hidden', 'true');
                }

                const $as = $ul.find(' > li > a, > li > button');

                $as.each(function () {
                    const $a = $(this);

                    if (openNav) {
                        $a.attr('tabIndex', 0);
                    } else {
                        $a.attr('tabIndex', -1);
                    }
                });

                $(document).keyup((e) => {
                    if ((e.keyCode === 27) && ($('.c-nav__sublist.s-open').length)) {
                        $ul.removeClass('s-open');
                        $button.removeClass('s-toggled');
                        $ul.attr('aria-hidden', 'true');
                        toggleNav($('.js-toggleSub.s-toggled'));
                    }
                });
            }

            $('.js-mobNav').click(function () {
                $('.c-nav__parent').toggleClass('s-open');
                $(this)
                    .children('span')
                    .toggle();
            });

            $('.js-mobClose').click(() => {
                $('.js-header-container').toggleClass('c-header__container--active');
                $('.c-nav__parent').removeClass('s-open');
                $('.js-mobNav')
                    .children('span')
                    .toggle();
            });

            $('.js-mobBack').click(function () {
                const $button = $(this)
                    .closest('ul')
                    .prev('.c-nav__subtoggle');

                toggleNav($button, !$button.hasClass('s-toggled'));

                $button
                    .parent()
                    .prevAll('li:first')
                    .find('a, button')
                    .focus();
            });
        };
    }

    /*  BD, 23-08-2018:
            Deze functie kijkt of het submenu en het sub-submenu (dat aan de rechterkant van het submenu opent) nog op je scherm past.
            Wanneer dit niet zo is, lijnt het submenu rechts uit, en/of plaatst het sub-submenu zich aan de linkerkant van het submenu. Deze plaatsing wordt met de CSS-class "switch" geregeld.
            Op elke resize wordt de functie opnieuw uitgevoerd.
        */
    function detectIfSubmenuIsOutView() {
        // Functie init op pageload
        calculateSubMenu();

        // Opnieuw uitvoeren op resize
        $(window).resize(() => {
            clearTimeout(window.resizedFinished);
            window.resizedFinished = setTimeout(() => {
                calculateSubMenu();
            }, 250);
        });

        function calculateSubMenu() {
            $('.c-nav__sublist').each(function () {
                const windowWidth = $(window).outerWidth();
                let parentSublistWidth = 0;
                let parentItem = $(this).closest('.c-nav__item');
                let offset = parentItem.offset();
                const elemWidth = $(this).outerWidth();
                const pageScrollbarWidth = 20;

                // Wanneer het een sublist--sub betreft worden er wat variables gewijzigd
                if ($(this).hasClass('c-nav__sublist--sub')) {
                    const parentSublist = $(this).parents('.c-nav__sublist');

                    parentItem = $(this).parents('.c-nav__sublist').parents('.c-nav__item');
                    parentSublistWidth = parentSublist.outerWidth();
                    offset = parentItem.offset();
                }

                // De switch class wordt toegevoegd wanneer de elemPos groter is dan de WindowWidth (en dus uit beeld valt)
                const elemPos = offset.left + parentSublistWidth + elemWidth + pageScrollbarWidth;

                if (elemPos > windowWidth) {
                    $(this).addClass('switch');
                } else {
                    $(this).removeClass('switch');
                }
            });
        }
    }

    /**
     * BD, 09-11-2018:
     *  Voorkomt het "meescrollen" van de pagina wanneer het mobiele menu geopend is.
     *
     *  Werking:
     *      Stap 1: Wanneer je het menu opent wordt de huidige scrollpositie van de gebruiker opgeslagen in een array.
     *      Stap 2: Wanneer de menu-animatie voltooid is zet de pagina zich terug naar top:0px, left: 0px (bovenkant pagina) en word de HTML gelockt.
     *      Stap 3: Bij het sluiten van het menu zet de pagina zich terug naar de scrollpositie die in de array opgeslagen is.
     *
     *  Gebruik:
     *  Roep de functie als volgt aan op de .js-mobNav en de .js-mobClose:
     *      $(".js-mobNav").click(function() { lockHtmlScroll(true); });
     *      $(".js-mobClose").click(function() { lockHtmlScroll(false); });
     * @param {boolean} status true indien menu moet worden gelockt, false indoen het moet worden geunlockt
     */
    function lockHtmlScroll(status) {
        const html = $('html');
        let scrollPosition = [
            window.self.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
            window.self.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop,
        ];

        if (status) {
            html.data('scroll-position', scrollPosition);

            // BD: Timeout wordt gebruikt om de HTML pas te locken wanneer de menu-animatie voltooid is. Dit is standaard 400ms.
            setTimeout(() => { html.addClass('is-locked'); }, 400);
        } else {
            html.removeClass('is-locked');

            scrollPosition = html.data('scroll-position');
            if (Array.isArray(scrollPosition) && scrollPosition.length === 2) {
                window.scrollTo(scrollPosition[0], scrollPosition[1]);
            }
        }
    }

    return menu;
}());
;
var Perplex = Perplex || {};

Perplex.Plugins = (function () {
    const pluginList = function () {
    	loadOFI();
    };

    function loadOFI() {
        objectFitImages('img:not([data-src])');
        // Apply object fit (again) on lazy images right before lazy image is loaded (lazybeforeunveil).
        $('.l-image__item--lazy, .lazyload').one('lazybeforeunveil', (e) => {
            $(e.target).one('load', () => {
                objectFitImages(e.target);
            });
        });
    }

    return pluginList;
}());
;
var Perplex = Perplex || {};

Perplex.TabsTable = (function () {
    const tabsTable = {};

    tabsTable.Init = function () {
        tabsWrapperTable();
        // These functions must re-run on window resize since they depend on media query logic
        $( window ).on( "resize", function() {
            requestAnimationFrame(() => {
                tabsWrapperTable();
            })
        } );

    };

    function tabsWrapperTable() {
        if (window.matchMedia('(min-width: 768px)').matches) {
            let h = 0;

            $('.js-tabs--table .c-tabs__item .c-tabs__content').each(function () {
                if (h < $(this).height()) {
                    h = $(this).height();
                }
            });
            $('.js-tabs--table .c-tabs__item .c-tabs__content').css('min-height', h + 50);

            const height = h + $('.js-tabs--table .c-tabs__item').first().height() + 50;

            $('.js-tabs--table').css('min-height', height);

            $('.js-tabs--table .c-tabs__title').click(function () {
                $('.js-tabs--table').css('min-height', 0);

                $('.js-tabs--table').css('min-height', height);
            });
        } else {
            $('.js-tabs--table .c-tabs__item .c-tabs__content').css('min-height', 0);
        }
    }


    return tabsTable;
}());
;
var Perplex = Perplex || {};

Perplex.Util = (function () {
    const util = {};

    util.Cookies = (function () {
        const cookies = {};

        // Read a cookie (does not work for HTTP-only cookies!)
        cookies.getCookie = function (name) {
            const nameEQ = `${name}=`;
            const ca = document.cookie.split(';');

            for (let i = 0; i < ca.length; i++) {
                let c = ca[i];

                while (c.charAt(0) === ' ') c = c.substring(1, c.length);
                if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
            }

            return null;
        };

        /*
         * Generic function to set a cookie
         * This method handles the secure flag if the current connection is secure
         */
        cookies.setCookie = function (key, value, exDays, expDate) {
            const isSecure = window.location.protocol === 'https:';

            let date = new Date();

            if (exDays > 0) {
                date.setTime(date.getTime() + exDays * 24 * 60 * 60 * 1000);
            } else {
                date = expDate;
            }

            const expires = `expires=${date.toUTCString()}`;

            document.cookie = `${key}=${value}; ${expires}; path=/;${isSecure ? 'secure' : ''}`;
        };

        // Remove a cookie
        // @param {string} name Cookie name
        cookies.removeCookie = function (name) {
            cookies.createCookie(name, '', -1);
        };

        return cookies;
    }());

    /**
     * Let op, aanroepen met "new Perplex.Util.PostcodeKoppeling({...})".
     * @param options - Object met verplichte properties "postcode", "huisnummer", "straat", "stad", en optioneel "timeout" en "apiUrl".
     * De verplichte properties moeten jQuery objecten zijn van de betreffende inputs
     */
    util.PostcodeKoppeling = (function () {
        function PostcodeKoppeling(options) {
            this.timer = null;
            this.timeout = options.timeout || 333;
            this.apiUrl = options.apiUrl || '/umbraco/api/postcodeapi/GetStreetAndCity';

            this.$postcode = options.postcode;
            this.$huisnummer = options.huisnummer;
            this.$straat = options.straat;
            this.$stad = options.stad;

            // Om te detecteren of het een change is.
            // We gebruiken niet .on("change") omdat dit
            // pas triggert als de input focus verliest.
            // We willen wel gewoon al zoeken als het veld nog focus heeft.
            this.prevPostcode = null;
            this.prevHuisnummer = null;

            this.init();
        }

        PostcodeKoppeling.prototype = {
            init() {
                const self = this;

                $.each([this.$postcode, this.$huisnummer], function () {
                    $(this).on('keyup', () => {
                        self.vulStraatEnStadIn();
                    });
                });
            },

            vulStraatEnStadIn(postcode, huisnummer) {
                const self = this;

                clearTimeout(self.timer);

                this.timer = setTimeout(() => {
                    const postcode = self.$postcode.val();
                    const huisnummer = self.$huisnummer.val();

                    if (
                        !huisnummer
                        || !postcode
                        || (huisnummer == self.prevHuisnummer && postcode === self.prevPostcode)
                    ) return;

                    $.ajax({
                        url: self.apiUrl,
                        data: { Postcode: postcode, Huisnummer: huisnummer },
                        contentType: 'application/json',
                    }).done((data) => {
                        self.$straat.val(data.Street);
                        self.$stad.val(data.City);

                        self.prevPostcode = postcode;
                        self.prevHuisnummer = huisnummer;
                    });
                }, this.timeout);
            },
        };

        return PostcodeKoppeling;
    }());

    /**
     * @param $target jQuery element om naartoe te scrollen
     * @param options Opties object met daarin (allemaal optioneel):
     * timeout - Number. Timeout in milliseconden dat het scrollen moet duren (default 500)
     * focus - Boolean, indien true wordt $target focus gegeven als de scroll klaar is
     * callback - Function. Wordt aangeroepen zodra de scroll is voltooid.
     * hash - String. Indien meegegeven wordt de hash geupdate met de gegeven string
     * offset - Number. De hoeveelheid pixels die extra omlaag moet worden gescrolled, bijvoorbeeld om
     * rekening te houden met een header met position fixed
     */
    util.scrollToElement = function ($target, options) {
        const opts = options || {};

        const timeout = opts.timeout != null ? opts.timeout : 500;
        const offset = opts.offset != null ? opts.offset : 0;
        const focus = !!opts.focus; // Default dus false
        const { callback } = opts;
        const { hash } = opts;

        // .animate callback hoeft maar 1x te worden aangeroepen,
        // niet voor zowel html als body
        let animationCompleted = false;

        const scrollTop = $target.offset().top - offset;

        $('html,body').animate({ scrollTop }, timeout, () => {
            if (animationCompleted) return;

            if (hash) {
                if (typeof window.history.replaceState === 'function') {
                    // Door de hash met replaceState in te stellen gaat de
                    // browser niet nogmaals naar het element scrollen + focus geven.
                    // We zijn er al heen gescrolled, en focus geven ja/nee is optioneel.
                    window.history.replaceState(null, null, hash);
                } else {
                    window.location.hash = hash;
                }
            }

            if (focus) {
                $target.focus();
                if (!$target.is(':focus')) {
                    // Indien het element geen focus heeft gekregen
                    // kunnen we het nogmaals proberen nadat we een tabindex
                    // attribute toevoegen.
                    $target.attr('tabindex', '-1');
                    $target.focus();
                }
            }

            if (typeof callback === 'function') {
                callback();
            }

            animationCompleted = true;
        });
    };

    util.Url = (function () {
        const urlHelper = {};

        urlHelper.getUrlWithoutQueryString = function (url) {
            url = url === undefined ? window.location.href : url;

            return url.split('?')[0] || '';
        };
        urlHelper.getQueryStringFromUrl = function (url) {
            url = url === undefined ? window.location.href : url;

            return url.split('?')[1] || '';
        };
        urlHelper.createUrlWithQueryString = function (urlWithouQuery, queryString) {
            if (queryString && queryString.length > 0) {
                return `${urlWithouQuery}?${queryString}`;
            }

            return urlWithouQuery;
        };
        urlHelper.queryStringToObject = function (query) {
            return query.replace(/^\?/, '').split('&').reduce((json, item) => {
                if (item) {
                    item = item.split('=').map((value) => decodeURIComponent(value));
                    json[item[0]] = item[1];
                }

                return json;
            }, {});
        };
        urlHelper.queryObjectToString = function (object) {
            object = object === undefined ? {} : object;

            return $.param(object);
        };

        /**
         * Convert object to url querystring.
         * @param {any} obj Object to convert
         * @returns {any} Querystring starting with ?
         */
        urlHelper.objectToQueryString = function (obj) {
            let result = '';

            if (!$.isEmptyObject(obj)) {
                result += '?';
                const keyValues = Object.keys(obj).map((key) => `${key}=${obj[key]}`).join('&');

                result += keyValues;
            }

            return result;
        };

        /**
         * Append properties of the specified object to the provided url
         * @param {any} url Source url to append to
         * @param {any} queryVars Object who's properties will be appended to the url
         * @returns {any} a querystring starting with ?
         */
        urlHelper.appendToQueryString = function (url, queryVars) {
            const firstSeperator = url.indexOf('?') == -1 ? '?' : '&';
            const queryStringParts = [];

            for (const key in queryVars) {
                queryStringParts.push(`${key}=${queryVars[key]}`);
            }
            const queryString = queryStringParts.join('&');

            return url + firstSeperator + queryString;
        };

        return urlHelper;
    }());

    util.Paging = (function () {
        const paging = {};

        paging.AsyncPagingInit = function () {
            function changePage(e) {
                const $element = $(this);

                const huidigeUrl = window.location.href;
                const huidigeQueryString = Perplex.Util.Url.getQueryStringFromUrl(huidigeUrl);
                const huidigeQueryParams = Perplex.Util.Url.queryStringToObject(huidigeQueryString) || {};
                const huidigePagina = parseInt(huidigeQueryParams.pagina) || 1;

                const nieuwePagina = parseInt($element.data('page')) || 1;

                if (huidigePagina == nieuwePagina) return false;

                const nieuweUrlZonderQuery = Perplex.Util.Url.getUrlWithoutQueryString(huidigeUrl);
                const nieuweQueryParams = $.extend(true, {}, huidigeQueryParams, { pagina: nieuwePagina });

                if (nieuwePagina <= 1) delete nieuweQueryParams.pagina;
                const nieuweQueryString = Perplex.Util.Url.queryObjectToString(nieuweQueryParams);
                const nieuweUrl = Perplex.Util.Url.createUrlWithQueryString(nieuweUrlZonderQuery, nieuweQueryString);

                Perplex.Analytics.TrackPageview(nieuweUrl);
                try {
                    const currentState = history.state;

                    window.history.pushState(currentState, '', nieuweUrl);
                } catch (error) {
                    console.error('Cannot push history state');
                    window.location.href = nieuweUrl;

                    return false;
                }

                nieuweQueryParams.partial = true;

                $.ajax({
                    url: nieuweUrlZonderQuery,
                    data: nieuweQueryParams,
                }).done((html) => {
                    const container = $('.js-partialcontainer');

                    container.empty();
                    container.append(html).show();
                    $('html, body').animate({ scrollTop: `${$('.js-partialcontainer').offset().top}px` }, 500);
                });

                return false;
            }

            $(document).on('click', '.js-page-link', changePage);
        };

        return paging;
    }());

    return util;
}());
;
var Perplex = Perplex || {};

Perplex.ziekenhuizen = (function () {
    const ziekenhuizen = {};

    ziekenhuizen.Init = function () {
        scrollTo();
        search();
        // for populating the event state
        processFilters();

        // SELECT2
        $('.js-select2').select2({
            language: {
                noResults() {
                    return 'Geen resulaten gevonden';
                },
            },
        });

        // Select2 initialize when loading slects with js-select2 dynamically
        $('body').on('DOMNodeInserted', 'select', function () {
            const select = $(this);

            if (select.hasClass('js-select2')) {
                if (!$(select).hasClass('select2-hidden-accessible')) {
                    select.select2({
                        language: {
                            noResults() {
                                return 'Geen resulaten gevonden';
                            },
                        },
                    });
                }
            }
        });
    };

    // load page state from history object
    ziekenhuizen.LoadState = function (stateObj) {
        if (stateObj == null) {
            return;
        }
        const form = $('.js-filters-wrapper .js-filters');

        if (form != undefined) {
            const action = form.data('surfacecontrollerurl') !== undefined ? form.data('surfacecontrollerurl') : form.attr('action');
            const resultsWrapperClass = form.data('resultselementclass');

            const nodeId = $('input[name=nodeId]').val();

            if (nodeId != undefined) {
                if (!stateObj.hasOwnProperty('NodeId')) {
                    stateObj.NodeId = [];
                }
                stateObj.NodeId.push(nodeId);
            }
            getData(action, resultsWrapperClass, stateObj);
        }
    };

    let searchTimeout = null;

    function search() {
        $('.js-filters-wrapper').on('input', '.js-searchterm-input', function (e) {
            const searchterm = $(this).val();

            // when 0 characters are entered enable the select
            if (searchterm.length > 0) {
                $('.js-searchterm-input').addClass('js-searched');
                $('.js-searchterm-input').addClass('js-filter-active');
                $('.js-specialismen').val(''); // when typing we reset the select
            } else {
                processFilters();
                $('.js-searchterm-input').removeClass('js-searched');
                $('.js-searchterm-input').removeClass('js-filter-active');
            }

            const form = $(this).closest('form');

            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(() => {
                if (form != undefined) {
                    const action = form.data('surfacecontrollerurl') !== undefined ? form.data('surfacecontrollerurl') : form.attr('action');
                    const resultsWrapperClass = form.data('resultselementclass');

                    getData(action, resultsWrapperClass);
                }
            }, 500);

            return false;
        });

        $('.js-filters-wrapper').on('change', '.js-specialismen', function () {
            const specialisme = $(this).val();

            // reset searchbar when selecting all option
            if (specialisme.length == 0) {
                $('.js-searchterm-input').removeClass('js-searched');
                $('.js-specialismen').removeClass('js-filter-active');
            } else {
                $('.js-searchterm-input').addClass('js-searched');
                $('.js-specialismen').addClass('js-filter-active');
                // when using select, we reset the searchbar
                $('.js-searchterm-input').val('');
            }

            const form = $(this).closest('form');

            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(() => {
                if (form != undefined) {
                    const action = form.data('surfacecontrollerurl') !== undefined ? form.data('surfacecontrollerurl') : form.attr('action');
                    const resultsWrapperClass = form.data('resultselementclass');

                    getData(action, resultsWrapperClass);
                }
            }, 500);
        });

        $('.js-filters-wrapper').on('change', '.js-checkbox', function () {
            const checkbox = $(this);

            // 0 items selected (of 2) so we are not filtering
            if ($('.js-checkbox:checked').length == 0) {
                $('.js-checkbox').not(':checked').prop('checked', true);
                $('.js-checkbox').addClass('js-filter-active');
                $('.js-searchterm-input').removeClass('js-searched');
            } else if ($('.js-checkbox:checked').length == 1) {
                // Only 1 item selected (of 2) so we are filtering
                $('.js-searchterm-input').addClass('js-searched');
            } else {
                // 2 items selected (of 2) so we are not filtering
                $('.js-searchterm-input').removeClass('js-searched');
            }

            // If checkbox is checked add the active class, else remove it
            if (checkbox.is(':checked')) {
                checkbox.addClass('js-filter-active');
            } else {
                checkbox.removeClass('js-filter-active');
            }

            const form = $(this).closest('form');

            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(() => {
                if (form != undefined) {
                    const action = form.data('surfacecontrollerurl') !== undefined ? form.data('surfacecontrollerurl') : form.attr('action');
                    const resultsWrapperClass = form.data('resultselementclass');

                    getData(action, resultsWrapperClass);
                }
            }, 500);
        });

        // alle velden uitlezen en gepaste zoekaanroep doen
        $('.js-filters-wrapper').on('submit', '.js-filters', function (e) {
            e.preventDefault();
            const searchterm = $('.js-searchterm-input').val();
            const form = $(this).closest('form');

            if (form != undefined) {
                var action = form.attr('action');

                $('.js-searchterm-input').addClass('js-searched');
                var action = form.data('surfacecontrollerurl') !== undefined ? form.data('surfacecontrollerurl') : form.attr('action');
                const resultsWrapperClass = form.data('resultselementclass');

                getData(action, resultsWrapperClass);
            }
        });
    }

    // Haalt data op van de opgegeven controller in url
    let oldQueryObj;

    function getData(baseUrl, resultsWrapperClass, queryObj) {
        $('.js-loader').addClass('js-loader--active');

        $('.js-results-wrapper')[0].ariaBusy = 'true';

        // Build url
        var queryObj = queryObj == undefined ? processFilters() : queryObj;

        if (JSON.stringify(queryObj) == JSON.stringify(oldQueryObj)) {
            // We veranderen niets aan onze request, dus gaan we ook niets doen.
            $('.js-loader').delay(200).removeClass('js-loader--active');
            $('.js-results-wrapper')[0].ariaBusy = 'false';

            return false;
        }

        // Request data
        $.ajax({
            url: `/umbraco/surface/${baseUrl}`,
            method: 'Post',
            data: queryObj,
        }).done((data) => {
            $(`.${resultsWrapperClass}`).html(data.results);
            if (data.results.indexOf('js-tracking-abz-no-results') > 0) {
                let tekst = ' - Auto aanvullen - Geen resultaten';
                let zoekwoord = '';

                $zoekbalkBehandelingOnderzoek = $('.js-tracking-zoeken-overzicht-behandelingenonderzoeken');
                $zoekbalkPoliAfdeling = $('.js-tracking-zoeken-overzicht-poliafdeling');
                $zoekbalkSpecialismenExpertises = $('.js-tracking-zoeken-overzicht-specialismenexpertises');
                $zoekbalkSpecialisten = $('.js-tracking-zoeken-overzicht-specialisten');

                if ($zoekbalkBehandelingOnderzoek != undefined && $zoekbalkBehandelingOnderzoek.length > 0) {
                    tekst = `Behandelingen${tekst}`;
                    zoekwoord = $zoekbalkBehandelingOnderzoek.val();
                }
                if ($zoekbalkSpecialismenExpertises != undefined && $zoekbalkSpecialismenExpertises.length > 0) {
                    tekst = `Specialismen${tekst}`;
                    zoekwoord = $zoekbalkSpecialismenExpertises.val();
                }
                if ($zoekbalkPoliAfdeling != undefined && $zoekbalkPoliAfdeling.length > 0) {
                    tekst = `Poliklinieken & afdelingen${tekst}`;
                    zoekwoord = $zoekbalkPoliAfdeling.val();
                }
                if ($zoekbalkSpecialisten != undefined && $zoekbalkSpecialisten.length > 0) {
                    tekst = `Behandelaars${tekst}`;
                    zoekwoord = $zoekbalkSpecialisten.val();
                }

                Perplex.Analytics.TrackEvent('Zoekfunctie', tekst, zoekwoord, true);
            }

            $('.js-filters').html(data.filters);

            const previousValue = $('.js-searchterm-input').val();

            $('.js-searchterm-input').val('').focus().val(previousValue);
            $('.js-select2').select2({
                language: {
                    noResults() {
                        return 'Geen resulaten gevonden';
                    },
                },
            });
            setTimeout(() => {
                $('.c-abc__results').viewportChecker();
                $('html, body').animate({
                    scrollTop: $('#abzbody').offset().top,
                }, 600);
                $('.js-loader').removeClass('js-loader--active');
                $('.js-results-wrapper')[0].ariaBusy = 'false';
            }, 300);
        });
        oldQueryObj = queryObj;
    }

    // browser popstate
    window.onpopstate = function (event) {
        ziekenhuizen.LoadState(event.state);
    };

    // process the selected filters
    function processFilters() {
        const queryObj = {};
        const queryObjForUrl = {};

        // loop through selected filters elements
        $('.js-filters-wrapper .js-filters').find('.js-filter-active, input[type=hidden]').each(function (index) {
            const $filterEl = $(this);
            const filterName = $filterEl.attr('name').toLowerCase();
            const filterValue = $filterEl.val().trim();

            if (filterValue) {
                // make sure property exists
                if (filterName != 'ufprt' && !queryObj.hasOwnProperty(filterName)) {
                    queryObj[filterName] = [];
                }
                if (!queryObjForUrl.hasOwnProperty(filterName) && $filterEl.attr('type') != 'hidden') {
                    queryObjForUrl[filterName] = [];
                }

                // push the value; remove hidden values because we don't want them inside our url, only for filtering
                if (queryObj.hasOwnProperty(filterName)) {
                    queryObj[filterName].push(filterValue);
                }
                if ($filterEl.attr('type') != 'hidden') {
                    queryObjForUrl[filterName].push(filterValue);
                }
            }
        });

        let url = Perplex.Util.Url.objectToQueryString(queryObjForUrl);

        if (url == '') {
            // Wanneer we geen parameters hebben resetten we hier de nieuwe URL even zodat we een toch een pushstate hebben
            url = window.location.pathname;
        }
        // change browser url + push query object when changing filters so we can go back to previous set filter values if set
        if (Object.keys(queryObjForUrl).length > 0) {
            history.pushState(queryObjForUrl, '', url);
        }

        return queryObj;
    }

    return ziekenhuizen;
}());
;
var Perplex = Perplex || {};

Perplex.Init = function() {
    Perplex.Analytics.Init(); // perplex.analytics.js
    Perplex.Global.Init();
    Perplex.Forms.Init();
    Perplex.Menu.Init();
    Perplex.Zoeken.Init();
    Perplex.Plugins();
    Perplex.Ready();
    Perplex.Accessibility.Init();
    //  Perplex.TrackingEvents.Init();
};

// Init op document.ready
// Dit is de korte versie van: $(document).ready(function() { Perplex.Init(); })

$(Perplex.Init);
;
