/**
 * PENDING: Workaround for the fact that aui-validator cannot validate mandatory checkboxes
 */
function checkboxClicked() {
    var hiddenInput = $("input[name*='contactStatement']");
    if (($("input[id='chk_kontakterklaerung']:checked").length) <= 0) {
        hiddenInput.val("");
        $("#lbl_chk_kontakterklaerung").css("border", "1px solid #b50303");
    } else {
        hiddenInput.val("selected");
        $("#lbl_chk_kontakterklaerung").css("border", "0px");
        // Removing the error message of the hidden aui input
        $('#control-group-contact-agreement div div div').remove();
    }
}

function deleteSuccessMessage() {
    $('#successMessageDiv').remove();
}
;
$(document).ready(function(){
    var clicked = false;
    var addMarginBottom = true;

    $(".wrapper-pannel-item").find("label").append('<span class="design-form-radio"></span>');
    $(".anrede").find("label").append('<span class="design-form-radio"></span>');
    $(".form-inline.input-checkbox-wrapper").find("label").append('<span class="checkmark"></span>');

    $('.contact-form-control').each(function(){
        if(this.value){
            $(this).parent().parent().find('.contact-input-label').addClass('active-label');
        }
    });

    $(".nav-list__item").mouseenter(function() {
        let count = $(this).children().find("ul:lt(1)").children().length;
        if ($(this).parent().children().length > count && count != 0) {
            $(this).children(".container-grid:lt(1)").addClass("compare-children-height");
        }
    }).mouseleave(function() {
        $(this).children(".container-grid:lt(1)").removeClass("compare-children-height");
    });

    $(".row.form-header").click(function(e) {
        if (!clicked && addMarginBottom && $(window).width() > 300 && $(window).width() < 989
        && ($(e.target).hasClass("wrapper-list-item") || $(e.target).parent(".wrapper-list-item-content").length > 0)) {
            $(".wrapper-list-item").css("margin-bottom", "");
        }
        clicked = false;
    });

    $(".wrapper-list-item").click(function(e) {
        if ($(window).width() > 300 && $(window).width() < 989) {
            if ($(this).css("margin-bottom") == $(this).find(".wrapper-pannel").height()+"px" && $(this).find(".wrapper-pannel").height() !== 0
                && ($(e.target).hasClass("wrapper-list-item") || $(e.target).parent(".wrapper-list-item-content").length > 0)) {
                $(".wrapper-list-item").css("margin-bottom", "");
                $(this).addClass("color-white-for-mobile-hover");
                $(this).find(".wrapper-pannel").addClass("hidden");
            } else {
                if ($(this).find(".design-form-radio__checked").length == 0) {
                    $(".wrapper-list-item").css("background-color", "");
                    $(".wrapper-pannel").css("display", "");
                    $(".wrapper-pannel").css("flex-direction", "");
                }
                $(".wrapper-list-item").css("margin-bottom", "");
                $(this).removeClass("color-white-for-mobile-hover");
                $(this).find(".wrapper-pannel").removeClass("hidden");
                $(this).css("margin-bottom", $(this).find(".wrapper-pannel").height());
            }

            clicked = true;
        }
    });

    if ($(window).width() > 989) {
        $(".wrapper-list-item").mouseenter(function() {
            if (addMarginBottom) {
                $(this).parents(".info.padding-block").css("margin-bottom", $(this).find(".wrapper-pannel").height() - 50);
            }
        }).mouseleave(function() {
            if (addMarginBottom) {
                $(this).parents(".info.padding-block").css("margin-bottom", "");
            }
        });
    }

    $('.contact-form-control').focus(function() {
        $(this).parent().parent().find('.contact-input-label').addClass('active-label');
        if ($(this).hasClass('success-field')) {
            $(this).parent().parent().find('.contact-input-label').removeClass('contact-input-label-focus');
            $(this).parent().parent().find('.contact-input-label').addClass('contact-input-success-label-focus');
        }
        if ($(this).hasClass('error-field')) {
            $(this).parent().parent().find('.contact-input-label').removeClass('contact-input-label-focus');
            $(this).parent().parent().find('.contact-input-label').addClass('contact-input-error-label-focus');
        } else {
            $(this).parent().parent().find('.contact-input-label').addClass('contact-input-label-focus');
            $(this).addClass('contact-form-control-focus');
        }
    });

    $('.contact-form-control').focusout(function() {
        $(this).removeClass('contact-form-control-focus');
        if (!this.value) {
            $(this).parent().parent().find('.contact-input-label').removeClass('active-label');
        }
        $(this).removeClass('error-field');
        $(this).parent().find(".form-validator-stack.help-block").remove();
        $(this).parent().parent().find('.contact-input-label').removeClass('contact-input-label-focus');
        $(this).parent().parent().find('.contact-input-label').removeClass('contact-input-error-label-focus');
        $(this).parent().parent().find('.contact-input-label').removeClass('contact-input-success-label-focus');
        var that = $(this);
        setTimeout(function() {
            if (that.hasClass('success-field')) {
                that.parent().parent().find('.contact-input-label').addClass('contact-input-success-label-focus');
            }
            if (that.hasClass('error-field')) {
                that.parent().parent().find('.contact-input-label').addClass('contact-input-error-label-focus');
            }
        }, 500);
    });

    $('.contact-form-control-textarea').focus(function() {
        $(this).parent().parent().find('.contact-input-label').addClass('contact-input-label-focus');
        $(this).addClass('contact-form-control-focus');
    });

    $('.contact-form-control-textarea').focusout(function() {
        $(this).parent().parent().find('.contact-input-label').removeClass('contact-input-label-focus');
        $(this).removeClass('contact-form-control-focus');

    });

    //cleck to any input with type radio
    $(".anrede-field-input").click(function () {
        $(".anrede-flex-for-inputs").find(".design-form-radio").removeClass("design-form-radio__checked");
        $(this).parent().find(".design-form-radio").addClass("design-form-radio__checked");
        $(this).parents(".anrede-flex-for-inputs").find(".form-validator-stack.help-block.custom-error-message-for-input").remove();
        $(this).parents(".anrede-flex-for-inputs").removeClass("custom-error-for-input");
    });

    $(".wrapper-list").children().each(function(item) {
        $(this).mouseenter(function() {

        }).mouseleave(function() {

        });
    });
    $('.wrapper-pannel-item-radio').click(function() {
        if ($(window).width() > 989) {
            $(".wrapper-list-item").removeClass("wrapper-list-item-selected-radio");
            $(".wrapper-pannel").css("display", "");
            $(".wrapper-pannel").css("z-index", "");
            $(this).parents(".wrapper-list-item").addClass("wrapper-list-item-selected-radio");
            $(this).parents(".wrapper-pannel").css("display", "flex");
            $(this).parents(".wrapper-pannel").css("z-index", "9");
        }
        if ($(window).width() > 300 && $(window).width() < 989) {
            $(".wrapper-list-item").css("background-color", "");
            $(".wrapper-pannel").css("display", "");
            $(".wrapper-pannel").css("flex-direction", "");
            $(this).parents(".wrapper-list-item").css("background-color", "#ccecf8");
            $(this).parents(".wrapper-pannel").css("display", "flex");
            $(this).parents(".wrapper-pannel").css("flex-direction", "column");
        }
        addMarginBottom = false;

        $(".info .wrapper-list").find(".form-validator-stack.help-block.custom-error-message-for-input").remove();
        $(".info .wrapper-list").removeClass("custom-error-for-input");
        $(".design-form-radio").removeClass("design-form-radio__checked");
        $(this).parents(".wrapper-pannel-item").find(".design-form-radio").addClass("design-form-radio__checked");

        $(".wrapper-pannel-item").removeClass('wrapper-pannel-item__checked');
        $(".wrapper-pannel-item").find("label").removeClass('wrapper-pannel-item-content-seccion-title__checked');
        $(".wrapper-pannel-item").find(".wrapper-pannel-item-content-text").removeClass("wrapper-pannel-item-content-text__checked");

        $(this).parents(".wrapper-pannel-item").addClass('wrapper-pannel-item__checked');
        $(this).parents(".wrapper-pannel-item").find('label').addClass('wrapper-pannel-item-content-seccion-title__checked');
        $(this).parents(".wrapper-pannel-item").find('.wrapper-pannel-item-content-text').addClass('wrapper-pannel-item-content-text__checked');

    });
});

function sendGAEventOnSelectOption(radio){
    dataLayer.push({'event': 'Service', 'eventkategorie': 'Kontaktformular','eventaktion': 'Auswahl AP','eventlabel': radio.parentElement.textContent.trim()});
}
/* ===========================================================
 * bootstrap-tooltip.js v2.3.2
 * http://twbs.github.com/bootstrap/javascript.html#tooltips
 * Inspired by the original jQuery.tipsy by Jason Frame
 * ===========================================================
 * Copyright 2013 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================================================== */


!function ($) {

  "use strict"; // jshint ;_;


 /* TOOLTIP PUBLIC CLASS DEFINITION
  * =============================== */

  var Tooltip = function (element, options) {
    this.init('tooltip', element, options)
  }

  Tooltip.prototype = {

    constructor: Tooltip

  , init: function (type, element, options) {
      var eventIn
        , eventOut
        , triggers
        , trigger
        , i

      this.type = type
      this.$element = $(element)
      this.options = this.getOptions(options)
      this.enabled = true

      triggers = this.options.trigger.split(' ')

      for (i = triggers.length; i--;) {
        trigger = triggers[i]
        if (trigger == 'click') {
          this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
        } else if (trigger != 'manual') {
          eventIn = trigger == 'hover' ? 'mouseenter' : 'focus'
          eventOut = trigger == 'hover' ? 'mouseleave' : 'blur'
          this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
          this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
        }
      }

      this.options.selector ?
        (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) :
        this.fixTitle()
    }

  , getOptions: function (options) {
      options = $.extend({}, $.fn[this.type].defaults, this.$element.data(), options)

      if (options.delay && typeof options.delay == 'number') {
        options.delay = {
          show: options.delay
        , hide: options.delay
        }
      }

      return options
    }

  , enter: function (e) {
      var defaults = $.fn[this.type].defaults
        , options = {}
        , self

      this._options && $.each(this._options, function (key, value) {
        if (defaults[key] != value) options[key] = value
      }, this)

      self = $(e.currentTarget)[this.type](options).data(this.type)

      if (!self.options.delay || !self.options.delay.show) return self.show()

      clearTimeout(this.timeout)
      self.hoverState = 'in'
      this.timeout = setTimeout(function() {
        if (self.hoverState == 'in') self.show()
      }, self.options.delay.show)
    }

  , leave: function (e) {
      var self = $(e.currentTarget)[this.type](this._options).data(this.type)

      if (this.timeout) clearTimeout(this.timeout)
      if (!self.options.delay || !self.options.delay.hide) return self.hide()

      self.hoverState = 'out'
      this.timeout = setTimeout(function() {
        if (self.hoverState == 'out') self.hide()
      }, self.options.delay.hide)
    }

  , show: function () {
      var $tip
        , pos
        , actualWidth
        , actualHeight
        , placement
        , tp
        , e = $.Event('show')

      if (this.hasContent() && this.enabled) {
        this.$element.trigger(e)
        if (e.isDefaultPrevented()) return
        $tip = this.tip()
        this.setContent()

        if (this.options.animation) {
          $tip.addClass('fade')
        }

        placement = typeof this.options.placement == 'function' ?
          this.options.placement.call(this, $tip[0], this.$element[0]) :
          this.options.placement

        $tip
          .detach()
          .css({ top: 0, left: 0, display: 'block' })

        this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)

        pos = this.getPosition()

        actualWidth = $tip[0].offsetWidth
        actualHeight = $tip[0].offsetHeight

        switch (placement) {
          case 'bottom':
            tp = {top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2}
            break
          case 'top':
            tp = {top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2}
            break
          case 'left':
            tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth}
            break
          case 'right':
            tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width}
            break
        }

        this.applyPlacement(tp, placement)
        this.$element.trigger('shown')
      }
    }

  , applyPlacement: function(offset, placement){
      var $tip = this.tip()
        , width = $tip[0].offsetWidth
        , height = $tip[0].offsetHeight
        , actualWidth
        , actualHeight
        , delta
        , replace

      $tip
        .offset(offset)
        .addClass(placement)
        .addClass('in')

      actualWidth = $tip[0].offsetWidth
      actualHeight = $tip[0].offsetHeight

      if (placement == 'top' && actualHeight != height) {
        offset.top = offset.top + height - actualHeight
        replace = true
      }

      if (placement == 'bottom' || placement == 'top') {
        delta = 0

        if (offset.left < 0){
          delta = offset.left * -2
          offset.left = 0
          $tip.offset(offset)
          actualWidth = $tip[0].offsetWidth
          actualHeight = $tip[0].offsetHeight
        }

        this.replaceArrow(delta - width + actualWidth, actualWidth, 'left')
      } else {
        this.replaceArrow(actualHeight - height, actualHeight, 'top')
      }

      if (replace) $tip.offset(offset)
    }

  , replaceArrow: function(delta, dimension, position){
      this
        .arrow()
        .css(position, delta ? (50 * (1 - delta / dimension) + "%") : '')
    }

  , setContent: function () {
      var $tip = this.tip()
        , title = this.getTitle()

      $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title)
      $tip.removeClass('fade in top bottom left right')
    }

  , hide: function () {
      var that = this
        , $tip = this.tip()
        , e = $.Event('hide')

      this.$element.trigger(e)
      if (e.isDefaultPrevented()) return

      $tip.removeClass('in')

      function removeWithAnimation() {
        var timeout = setTimeout(function () {
          $tip.off($.support.transition.end).detach()
        }, 500)

        $tip.one($.support.transition.end, function () {
          clearTimeout(timeout)
          $tip.detach()
        })
      }

      $.support.transition && this.$tip.hasClass('fade') ?
        removeWithAnimation() :
        $tip.detach()

      this.$element.trigger('hidden')

      return this
    }

  , fixTitle: function () {
      var $e = this.$element
      if ($e.attr('title') || typeof($e.attr('data-original-title')) != 'string') {
        $e.attr('data-original-title', $e.attr('title') || '').attr('title', '')
      }
    }

  , hasContent: function () {
      return this.getTitle()
    }

  , getPosition: function () {
      var el = this.$element[0]
      return $.extend({}, (typeof el.getBoundingClientRect == 'function') ? el.getBoundingClientRect() : {
        width: el.offsetWidth
      , height: el.offsetHeight
      }, this.$element.offset())
    }

  , getTitle: function () {
      var title
        , $e = this.$element
        , o = this.options

      title = $e.attr('data-original-title')
        || (typeof o.title == 'function' ? o.title.call($e[0]) :  o.title)

      return title
    }

  , tip: function () {
      return this.$tip = this.$tip || $(this.options.template)
    }

  , arrow: function(){
      return this.$arrow = this.$arrow || this.tip().find(".tooltip-arrow")
    }

  , validate: function () {
      if (!this.$element[0].parentNode) {
        this.hide()
        this.$element = null
        this.options = null
      }
    }

  , enable: function () {
      this.enabled = true
    }

  , disable: function () {
      this.enabled = false
    }

  , toggleEnabled: function () {
      this.enabled = !this.enabled
    }

  , toggle: function (e) {
      var self = e ? $(e.currentTarget)[this.type](this._options).data(this.type) : this
      self.tip().hasClass('in') ? self.hide() : self.show()
    }

  , destroy: function () {
      this.hide().$element.off('.' + this.type).removeData(this.type)
    }

  }


 /* TOOLTIP PLUGIN DEFINITION
  * ========================= */

  var old = $.fn.tooltip

  $.fn.tooltip = function ( option ) {
    return this.each(function () {
      var $this = $(this)
        , data = $this.data('tooltip')
        , options = typeof option == 'object' && option
      if (!data) $this.data('tooltip', (data = new Tooltip(this, options)))
      if (typeof option == 'string') data[option]()
    })
  }

  $.fn.tooltip.Constructor = Tooltip

  $.fn.tooltip.defaults = {
    animation: true
  , placement: 'top'
  , selector: false
  , template: '<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>'
  , trigger: 'hover focus'
  , title: ''
  , delay: 0
  , html: false
  , container: false
  }


 /* TOOLTIP NO CONFLICT
  * =================== */

  $.fn.tooltip.noConflict = function () {
    $.fn.tooltip = old
    return this
  }

}(window.jQuery);

/* ===========================================================
 * bootstrap-popover.js v2.3.2
 * http://twbs.github.com/bootstrap/javascript.html#popovers
 * ===========================================================
 * Copyright 2013 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =========================================================== */


!function ($) {

  "use strict"; // jshint ;_;


 /* POPOVER PUBLIC CLASS DEFINITION
  * =============================== */

  var Popover = function (element, options) {
    this.init('popover', element, options)
  }


  /* NOTE: POPOVER EXTENDS BOOTSTRAP-TOOLTIP.js
     ========================================== */

  Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype, {

    constructor: Popover

  , setContent: function () {
      var $tip = this.tip()
        , title = this.getTitle()
        , content = this.getContent()

      $tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title)
      $tip.find('.popover-content')[this.options.html ? 'html' : 'text'](content)

      $tip.removeClass('fade top bottom left right in')
    }

  , hasContent: function () {
      return this.getTitle() || this.getContent()
    }

  , getContent: function () {
      var content
        , $e = this.$element
        , o = this.options

      content = (typeof o.content == 'function' ? o.content.call($e[0]) :  o.content)
        || $e.attr('data-content')

      return content
    }

  , tip: function () {
      if (!this.$tip) {
        this.$tip = $(this.options.template)
      }
      return this.$tip
    }

  , destroy: function () {
      this.hide().$element.off('.' + this.type).removeData(this.type)
    }

  })


 /* POPOVER PLUGIN DEFINITION
  * ======================= */

  var old = $.fn.popover

  $.fn.popover = function (option) {
    return this.each(function () {
      var $this = $(this)
        , data = $this.data('popover')
        , options = typeof option == 'object' && option
      if (!data) $this.data('popover', (data = new Popover(this, options)))
      if (typeof option == 'string') data[option]()
    })
  }

  $.fn.popover.Constructor = Popover

  $.fn.popover.defaults = $.extend({} , $.fn.tooltip.defaults, {
    placement: 'right'
  , trigger: 'click'
  , content: ''
  , template: '<div class="popover"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
  })


 /* POPOVER NO CONFLICT
  * =================== */

  $.fn.popover.noConflict = function () {
    $.fn.popover = old
    return this
  }

}(window.jQuery);

/**
 * bxSlider v4.2.1d
 * Copyright 2013-2017 Steven Wanderski
 * Written while drinking Belgian ales and listening to jazz
 * Licensed under MIT (http://opensource.org/licenses/MIT)
 */

;(function($) {
  
    var defaults = {
  
      // GENERAL
      mode: 'horizontal',
      slideSelector: '',
      infiniteLoop: true,
      hideControlOnEnd: false,
      speed: 500,
      easing: null,
      slideMargin: 0,
      startSlide: 0,
      randomStart: false,
      captions: false,
      ticker: false,
      tickerHover: false,
      adaptiveHeight: false,
      adaptiveHeightSpeed: 500,
      video: false,
      useCSS: true,
      preloadImages: 'visible',
      responsive: true,
      slideZIndex: 50,
      wrapperClass: 'bx-wrapper',
  
      // TOUCH
      touchEnabled: true,
      swipeThreshold: 50,
      oneToOneTouch: true,
      preventDefaultSwipeX: true,
      preventDefaultSwipeY: false,
  
      // ACCESSIBILITY
      ariaLive: true,
      ariaHidden: true,
  
      // KEYBOARD
      keyboardEnabled: false,
  
      // PAGER
      pager: true,
      pagerType: 'full',
      pagerShortSeparator: ' / ',
      pagerSelector: null,
      buildPager: null,
      pagerCustom: null,
  
      // CONTROLS
      controls: true,
      nextText: 'Next',
      prevText: 'Prev',
      nextSelector: null,
      prevSelector: null,
      autoControls: false,
      startText: 'Start',
      stopText: 'Stop',
      autoControlsCombine: false,
      autoControlsSelector: null,
  
      // AUTO
      auto: false,
      pause: 4000,
      autoStart: true,
      autoDirection: 'next',
      stopAutoOnClick: false,
      autoHover: false,
      autoDelay: 0,
      autoSlideForOnePage: false,
  
      // CAROUSEL
      minSlides: 1,
      maxSlides: 1,
      moveSlides: 0,
      slideWidth: 0,
      shrinkItems: false,
  
      // CALLBACKS
      onSliderLoad: function() { return true; },
      onSlideBefore: function() { return true; },
      onSlideAfter: function() { return true; },
      onSlideNext: function() { return true; },
      onSlidePrev: function() { return true; },
      onSliderResize: function() { return true; },
    onAutoChange: function() { return true; } //calls when auto slides starts and stops
    };
  
    $.fn.bxSlider = function(options) {
  
      if (this.length === 0) {
        return this;
      }
  
      // support multiple elements
      if (this.length > 1) {
        this.each(function() {
          $(this).bxSlider(options);
        });
        return this;
      }
  
      // create a namespace to be used throughout the plugin
      var slider = {},
      // set a reference to our slider element
      el = this,
      // get the original window dimens (thanks a lot IE)
      windowWidth = $(window).width(),
      windowHeight = $(window).height();
  
      // Return if slider is already initialized
      if ($(el).data('bxSlider')) { return; }
  
      /**
       * ===================================================================================
       * = PRIVATE FUNCTIONS
       * ===================================================================================
       */
  
      /**
       * Initializes namespace settings to be used throughout plugin
       */
      var init = function() {
        // Return if slider is already initialized
        if ($(el).data('bxSlider')) { return; }
        // merge user-supplied options with the defaults
        slider.settings = $.extend({}, defaults, options);
        // parse slideWidth setting
        slider.settings.slideWidth = parseInt(slider.settings.slideWidth);
        // store the original children
        slider.children = el.children(slider.settings.slideSelector);
        // check if actual number of slides is less than minSlides / maxSlides
        if (slider.children.length < slider.settings.minSlides) { slider.settings.minSlides = slider.children.length; }
        if (slider.children.length < slider.settings.maxSlides) { slider.settings.maxSlides = slider.children.length; }
        // if random start, set the startSlide setting to random number
        if (slider.settings.randomStart) { slider.settings.startSlide = Math.floor(Math.random() * slider.children.length); }
        // store active slide information
        slider.active = { index: slider.settings.startSlide };
        // store if the slider is in carousel mode (displaying / moving multiple slides)
        slider.carousel = slider.settings.minSlides > 1 || slider.settings.maxSlides > 1;
        // if carousel, force preloadImages = 'all'
        if (slider.carousel) { slider.settings.preloadImages = 'all'; }
        // calculate the min / max width thresholds based on min / max number of slides
        // used to setup and update carousel slides dimensions
        slider.minThreshold = (slider.settings.minSlides * slider.settings.slideWidth) + ((slider.settings.minSlides - 1) * slider.settings.slideMargin);
        slider.maxThreshold = (slider.settings.maxSlides * slider.settings.slideWidth) + ((slider.settings.maxSlides - 1) * slider.settings.slideMargin);
        // store the current state of the slider (if currently animating, working is true)
        slider.working = false;
        // initialize the controls object
        slider.controls = {};
        // initialize an auto interval
        slider.interval = null;
        // determine which property to use for transitions
        slider.animProp = slider.settings.mode === 'vertical' ? 'top' : 'left';
        // determine if hardware acceleration can be used
        slider.usingCSS = slider.settings.useCSS && slider.settings.mode !== 'fade' && (function() {
          // create our test div element
          var div = document.createElement('div'),
          // css transition properties
          props = ['WebkitPerspective', 'MozPerspective', 'OPerspective', 'msPerspective'];
          // test for each property
          for (var i = 0; i < props.length; i++) {
            if (div.style[props[i]] !== undefined) {
              slider.cssPrefix = props[i].replace('Perspective', '').toLowerCase();
              slider.animProp = '-' + slider.cssPrefix + '-transform';
              return true;
            }
          }
          return false;
        }());
        // if vertical mode always make maxSlides and minSlides equal
        if (slider.settings.mode === 'vertical') { slider.settings.maxSlides = slider.settings.minSlides; }
        // save original style data
        el.data('origStyle', el.attr('style'));
        el.children(slider.settings.slideSelector).each(function() {
          $(this).data('origStyle', $(this).attr('style'));
        });
  
        // perform all DOM / CSS modifications
        setup();
      };
  
      /**
       * Performs all DOM and CSS modifications
       */
      var setup = function() {
        var preloadSelector = slider.children.eq(slider.settings.startSlide); // set the default preload selector (visible)
  
        // wrap el in a wrapper
        el.wrap('<div class="' + slider.settings.wrapperClass + '"><div class="bx-viewport"></div></div>');
        // store a namespace reference to .bx-viewport
        slider.viewport = el.parent();
  
        // add aria-live if the setting is enabled and ticker mode is disabled
        if (slider.settings.ariaLive && !slider.settings.ticker) {
          slider.viewport.attr('aria-live', 'polite');
        }
        // add a loading div to display while images are loading
        slider.loader = $('<div class="bx-loading" />');
        slider.viewport.prepend(slider.loader);
        // set el to a massive width, to hold any needed slides
        // also strip any margin and padding from el
        el.css({
          width: slider.settings.mode === 'horizontal' ? (slider.children.length * 1000 + 215) + '%' : 'auto',
          position: 'relative'
        });
        // if using CSS, add the easing property
        if (slider.usingCSS && slider.settings.easing) {
          el.css('-' + slider.cssPrefix + '-transition-timing-function', slider.settings.easing);
        // if not using CSS and no easing value was supplied, use the default JS animation easing (swing)
        } else if (!slider.settings.easing) {
          slider.settings.easing = 'swing';
        }
        // make modifications to the viewport (.bx-viewport)
        slider.viewport.css({
          width: '100%',
          overflow: 'hidden',
          position: 'relative'
        });
        slider.viewport.parent().css({
          maxWidth: getViewportMaxWidth()
        });
        // apply css to all slider children
        slider.children.css({
          // the float attribute is a reserved word in compressors like YUI compressor and need to be quoted #48
          'float': slider.settings.mode === 'horizontal' ? 'left' : 'none',
          listStyle: 'none',
          position: 'relative'
        });
        // apply the calculated width after the float is applied to prevent scrollbar interference
        slider.children.css('width', getSlideWidth());
        // if slideMargin is supplied, add the css
        if (slider.settings.mode === 'horizontal' && slider.settings.slideMargin > 0) { slider.children.css('marginRight', slider.settings.slideMargin); }
        if (slider.settings.mode === 'vertical' && slider.settings.slideMargin > 0) { slider.children.css('marginBottom', slider.settings.slideMargin); }
        // if "fade" mode, add positioning and z-index CSS
        if (slider.settings.mode === 'fade') {
          slider.children.css({
            position: 'absolute',
            zIndex: 0,
            display: 'none'
          });
          // prepare the z-index on the showing element
          slider.children.eq(slider.settings.startSlide).css({zIndex: slider.settings.slideZIndex, display: 'block'});
        }
        // create an element to contain all slider controls (pager, start / stop, etc)
        slider.controls.el = $('<div class="bx-controls" />');
        // if captions are requested, add them
        if (slider.settings.captions) { appendCaptions(); }
        // check if startSlide is last slide
        slider.active.last = slider.settings.startSlide === getPagerQty() - 1;
        // if video is true, set up the fitVids plugin
        if (slider.settings.video) { el.fitVids(); }
      //preloadImages
      if (slider.settings.preloadImages === 'none') { 
        preloadSelector = null; 
      }
        else if (slider.settings.preloadImages === 'all' || slider.settings.ticker) { 
        preloadSelector = slider.children; 
      }
        // only check for control addition if not in "ticker" mode
        if (!slider.settings.ticker) {
          // if controls are requested, add them
          if (slider.settings.controls) { appendControls(); }
          // if auto is true, and auto controls are requested, add them
          if (slider.settings.auto && slider.settings.autoControls) { appendControlsAuto(); }
          // if pager is requested, add it
          if (slider.settings.pager) { appendPager(); }
          // if any control option is requested, add the controls wrapper
          if (slider.settings.controls || slider.settings.autoControls || slider.settings.pager) { slider.viewport.after(slider.controls.el); }
        // if ticker mode, do not allow a pager
        } else {
          slider.settings.pager = false;
        }
      if (preloadSelector === null) {
          start();
        } else {
          loadElements(preloadSelector, start);
        }
      };
  
      var loadElements = function(selector, callback) {
        var total = selector.find('img:not([src=""]), iframe').length,
        count = 0;
        if (total === 0) {
          callback();
          return;
        }
        selector.find('img:not([src=""]), iframe').each(function() {
          $(this).one('load error', function() {
            if (++count === total) { callback(); }
          }).each(function() {
            if (this.complete || this.src == '') { $(this).trigger('load'); }
          });
        });
      };
  
      /**
       * Start the slider
       */
      var start = function() {
        // if infinite loop, prepare additional slides
        if (slider.settings.infiniteLoop && slider.settings.mode !== 'fade' && !slider.settings.ticker) {
          var slice    = slider.settings.mode === 'vertical' ? slider.settings.minSlides : slider.settings.maxSlides,
          sliceAppend  = slider.children.slice(0, slice).clone(true).addClass('bx-clone'),
          slicePrepend = slider.children.slice(-slice).clone(true).addClass('bx-clone');
          if (slider.settings.ariaHidden) {
            sliceAppend.attr('aria-hidden', true);
            slicePrepend.attr('aria-hidden', true);
          }
          el.append(sliceAppend).prepend(slicePrepend);
        }
        // remove the loading DOM element
        slider.loader.remove();
        // set the left / top position of "el"
        setSlidePosition();
        // if "vertical" mode, always use adaptiveHeight to prevent odd behavior
        if (slider.settings.mode === 'vertical') { slider.settings.adaptiveHeight = true; }
        // set the viewport height
        slider.viewport.height(getViewportHeight());
        // make sure everything is positioned just right (same as a window resize)
        el.redrawSlider();
        // onSliderLoad callback
        slider.settings.onSliderLoad.call(el, slider.active.index);
        // slider has been fully initialized
        slider.initialized = true;
        // add the resize call to the window
        if (slider.settings.responsive) { $(window).on('resize', resizeWindow); }
        // if auto is true and has more than 1 page, start the show
        if (slider.settings.auto && slider.settings.autoStart && (getPagerQty() > 1 || slider.settings.autoSlideForOnePage)) { initAuto(); }
        // if ticker is true, start the ticker
        if (slider.settings.ticker) { initTicker(); }
        // if pager is requested, make the appropriate pager link active
        if (slider.settings.pager) { updatePagerActive(slider.settings.startSlide); }
        // check for any updates to the controls (like hideControlOnEnd updates)
        if (slider.settings.controls) { updateDirectionControls(); }
        // if touchEnabled is true, setup the touch events
        if (slider.settings.touchEnabled && !slider.settings.ticker) { initTouch(); }
        // if keyboardEnabled is true, setup the keyboard events
        if (slider.settings.keyboardEnabled && !slider.settings.ticker) {
          $(document).keydown(keyPress);
        }
      };
  
      /**
       * Returns the calculated height of the viewport, used to determine either adaptiveHeight or the maxHeight value
       */
      var getViewportHeight = function() {
        var height = 0;
        // first determine which children (slides) should be used in our height calculation
        var children = $();
        // if mode is not "vertical" and adaptiveHeight is false, include all children
        if (slider.settings.mode !== 'vertical' && !slider.settings.adaptiveHeight) {
          children = slider.children;
        } else {
          // if not carousel, return the single active child
          if (!slider.carousel) {
            children = slider.children.eq(slider.active.index);
          // if carousel, return a slice of children
          } else {
            // get the individual slide index
            var currentIndex = slider.settings.moveSlides === 1 ? slider.active.index : slider.active.index * getMoveBy();
            // add the current slide to the children
            children = slider.children.eq(currentIndex);
            // cycle through the remaining "showing" slides
            for (i = 1; i <= slider.settings.maxSlides - 1; i++) {
              // if looped back to the start
              if (currentIndex + i >= slider.children.length) {
                children = children.add(slider.children.eq(i - 1));
              } else {
                children = children.add(slider.children.eq(currentIndex + i));
              }
            }
          }
        }
        // if "vertical" mode, calculate the sum of the heights of the children
        if (slider.settings.mode === 'vertical') {
          children.each(function(index) {
            height += $(this).outerHeight();
          });
          // add user-supplied margins
          if (slider.settings.slideMargin > 0) {
            height += slider.settings.slideMargin * (slider.settings.minSlides - 1);
          }
        // if not "vertical" mode, calculate the max height of the children
        } else {
          height = Math.max.apply(Math, children.map(function() {
            return $(this).outerHeight(false);
          }).get());
        }
  
        if (slider.viewport.css('box-sizing') === 'border-box') {
          height += parseFloat(slider.viewport.css('padding-top')) + parseFloat(slider.viewport.css('padding-bottom')) +
                parseFloat(slider.viewport.css('border-top-width')) + parseFloat(slider.viewport.css('border-bottom-width'));
        } else if (slider.viewport.css('box-sizing') === 'padding-box') {
          height += parseFloat(slider.viewport.css('padding-top')) + parseFloat(slider.viewport.css('padding-bottom'));
        }
  
        return height;
      };
  
      /**
       * Returns the calculated width to be used for the outer wrapper / viewport
       */
      var getViewportMaxWidth = function() {
        var width = '100%';
        if (slider.settings.slideWidth > 0) {
          if (slider.settings.mode === 'horizontal') {
            width = (slider.settings.maxSlides * slider.settings.slideWidth) + ((slider.settings.maxSlides - 1) * slider.settings.slideMargin);
          } else {
            width = slider.settings.slideWidth;
          }
        }
        return width;
      };
  
      /**
       * Returns the calculated width to be applied to each slide
       */
      var getSlideWidth = function() {
        var newElWidth = slider.settings.slideWidth, // start with any user-supplied slide width
        wrapWidth      = slider.viewport.width();    // get the current viewport width
        // if slide width was not supplied, or is larger than the viewport use the viewport width
        if (slider.settings.slideWidth === 0 ||
          (slider.settings.slideWidth > wrapWidth && !slider.carousel) ||
          slider.settings.mode === 'vertical') {
          newElWidth = wrapWidth;
        // if carousel, use the thresholds to determine the width
        } else if (slider.settings.maxSlides > 1 && slider.settings.mode === 'horizontal') {
          if (wrapWidth > slider.maxThreshold) {
            return newElWidth;
          } else if (wrapWidth < slider.minThreshold) {
            newElWidth = (wrapWidth - (slider.settings.slideMargin * (slider.settings.minSlides - 1))) / slider.settings.minSlides;
          } else if (slider.settings.shrinkItems) {
            newElWidth = Math.floor((wrapWidth + slider.settings.slideMargin) / (Math.ceil((wrapWidth + slider.settings.slideMargin) / (newElWidth + slider.settings.slideMargin))) - slider.settings.slideMargin);
          }
        }
        return newElWidth;
      };
  
      /**
       * Returns the number of slides currently visible in the viewport (includes partially visible slides)
       */
      var getNumberSlidesShowing = function() {
        var slidesShowing = 1,
        childWidth = null;
        if (slider.settings.mode === 'horizontal' && slider.settings.slideWidth > 0) {
          // if viewport is smaller than minThreshold, return minSlides
          if (slider.viewport.width() < slider.minThreshold) {
            slidesShowing = slider.settings.minSlides;
          // if viewport is larger than maxThreshold, return maxSlides
          } else if (slider.viewport.width() > slider.maxThreshold) {
            slidesShowing = slider.settings.maxSlides;
          // if viewport is between min / max thresholds, divide viewport width by first child width
          } else {
            childWidth = slider.children.first().width() + slider.settings.slideMargin;
            slidesShowing = Math.floor((slider.viewport.width() +
              slider.settings.slideMargin) / childWidth) || 1;
          }
        // if "vertical" mode, slides showing will always be minSlides
        } else if (slider.settings.mode === 'vertical') {
          slidesShowing = slider.settings.minSlides;
        }
        return slidesShowing;
      };
  
      /**
       * Returns the number of pages (one full viewport of slides is one "page")
       */
      var getPagerQty = function() {
        var pagerQty = 0,
        breakPoint = 0,
        counter = 0;
        // if moveSlides is specified by the user
        if (slider.settings.moveSlides > 0) {
          if (slider.settings.infiniteLoop) {
            pagerQty = Math.ceil(slider.children.length / getMoveBy());
          } else {
            // when breakpoint goes above children length, counter is the number of pages
            while (breakPoint < slider.children.length) {
              ++pagerQty;
              breakPoint = counter + getNumberSlidesShowing();
              counter += slider.settings.moveSlides <= getNumberSlidesShowing() ? slider.settings.moveSlides : getNumberSlidesShowing();
            }
        return counter;
          }
        // if moveSlides is 0 (auto) divide children length by sides showing, then round up
        } else {
          pagerQty = Math.ceil(slider.children.length / getNumberSlidesShowing());
        }
        return pagerQty;
      };
  
      /**
       * Returns the number of individual slides by which to shift the slider
       */
      var getMoveBy = function() {
        // if moveSlides was set by the user and moveSlides is less than number of slides showing
        if (slider.settings.moveSlides > 0 && slider.settings.moveSlides <= getNumberSlidesShowing()) {
          return slider.settings.moveSlides;
        }
        // if moveSlides is 0 (auto)
        return getNumberSlidesShowing();
      };
  
      /**
       * Sets the slider's (el) left or top position
       */
      var setSlidePosition = function() {
        var position, lastChild, lastShowingIndex;
        // if last slide, not infinite loop, and number of children is larger than specified maxSlides
        if (slider.children.length > slider.settings.maxSlides && slider.active.last && !slider.settings.infiniteLoop) {
          if (slider.settings.mode === 'horizontal') {
            // get the last child's position
            lastChild = slider.children.last();
            position = lastChild.position();
            // set the left position
            setPositionProperty(-(position.left - (slider.viewport.width() - lastChild.outerWidth())), 'reset', 0);
          } else if (slider.settings.mode === 'vertical') {
            // get the last showing index's position
            lastShowingIndex = slider.children.length - slider.settings.minSlides;
            position = slider.children.eq(lastShowingIndex).position();
            // set the top position
            setPositionProperty(-position.top, 'reset', 0);
          }
        // if not last slide
        } else {
          // get the position of the first showing slide
          position = slider.children.eq(slider.active.index * getMoveBy()).position();
          // check for last slide
          if (slider.active.index === getPagerQty() - 1) { slider.active.last = true; }
          // set the respective position
          if (position !== undefined) {
            if (slider.settings.mode === 'horizontal') { setPositionProperty(-position.left, 'reset', 0); }
            else if (slider.settings.mode === 'vertical') { setPositionProperty(-position.top, 'reset', 0); }
          }
        }
      };
  
      /**
       * Sets the el's animating property position (which in turn will sometimes animate el).
       * If using CSS, sets the transform property. If not using CSS, sets the top / left property.
       *
       * @param value (int)
       *  - the animating property's value
       *
       * @param type (string) 'slide', 'reset', 'ticker'
       *  - the type of instance for which the function is being
       *
       * @param duration (int)
       *  - the amount of time (in ms) the transition should occupy
       *
       * @param params (array) optional
       *  - an optional parameter containing any variables that need to be passed in
       */
      var setPositionProperty = function(value, type, duration, params) {
        var animateObj, propValue;
        // use CSS transform
        if (slider.usingCSS) {
          // determine the translate3d value
          propValue = slider.settings.mode === 'vertical' ? 'translate3d(0, ' + value + 'px, 0)' : 'translate3d(' + value + 'px, 0, 0)';
          // add the CSS transition-duration
          el.css('-' + slider.cssPrefix + '-transition-duration', duration / 1000 + 's');
          if (type === 'slide') {
            // set the property value
            el.css(slider.animProp, propValue);
            if (duration !== 0) {
              // add a callback method - executes when CSS transition completes
              el.on('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd', function(e) {
                //make sure it's the correct one
                if (!$(e.target).is(el)) { return; }
                // remove the callback
                el.off('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd');
                updateAfterSlideTransition();
              });
            } else { //duration = 0
              updateAfterSlideTransition();
            }
          } else if (type === 'reset') {
            el.css(slider.animProp, propValue);
          } else if (type === 'ticker') {
            // make the transition use 'linear'
            el.css('-' + slider.cssPrefix + '-transition-timing-function', 'linear');
            el.css(slider.animProp, propValue);
            if (duration !== 0) {
              el.on('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd', function(e) {
                //make sure it's the correct one
                if (!$(e.target).is(el)) { return; }
                // remove the callback
                el.off('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd');
                // reset the position
                setPositionProperty(params.resetValue, 'reset', 0);
                // start the loop again
                tickerLoop();
              });
            } else { //duration = 0
              setPositionProperty(params.resetValue, 'reset', 0);
              tickerLoop();
            }
          }
        // use JS animate
        } else {
          animateObj = {};
          animateObj[slider.animProp] = value;
          if (type === 'slide') {
            el.animate(animateObj, duration, slider.settings.easing, function() {
              updateAfterSlideTransition();
            });
          } else if (type === 'reset') {
            el.css(slider.animProp, value);
          } else if (type === 'ticker') {
            el.animate(animateObj, duration, 'linear', function() {
              setPositionProperty(params.resetValue, 'reset', 0);
              // run the recursive loop after animation
              tickerLoop();
            });
          }
        }
      };
  
      /**
       * Populates the pager with proper amount of pages
       */
      var populatePager = function() {
        var pagerHtml = '',
        linkContent = '',
        pagerQty = getPagerQty();
        // loop through each pager item
        for (var i = 0; i < pagerQty; i++) {
          linkContent = '';
          // if a buildPager function is supplied, use it to get pager link value, else use index + 1
          if (slider.settings.buildPager && $.isFunction(slider.settings.buildPager) || slider.settings.pagerCustom) {
            linkContent = slider.settings.buildPager(i);
            slider.pagerEl.addClass('bx-custom-pager');
          } else {
            linkContent = i + 1;
            slider.pagerEl.addClass('bx-default-pager');
          }
          // var linkContent = slider.settings.buildPager && $.isFunction(slider.settings.buildPager) ? slider.settings.buildPager(i) : i + 1;
          // add the markup to the string
          pagerHtml += '<div class="bx-pager-item"><a href="" data-slide-index="' + i + '" class="bx-pager-link">' + linkContent + '</a></div>';
        }
        // populate the pager element with pager links
        slider.pagerEl.html(pagerHtml);
      };
  
      /**
       * Appends the pager to the controls element
       */
      var appendPager = function() {
        if (!slider.settings.pagerCustom) {
          // create the pager DOM element
          slider.pagerEl = $('<div class="bx-pager" />');
          // if a pager selector was supplied, populate it with the pager
          if (slider.settings.pagerSelector) {
            $(slider.settings.pagerSelector).html(slider.pagerEl);
          // if no pager selector was supplied, add it after the wrapper
          } else {
            slider.controls.el.addClass('bx-has-pager').append(slider.pagerEl);
          }
          // populate the pager
          populatePager();
        } else {
          slider.pagerEl = $(slider.settings.pagerCustom);
        }
        // assign the pager click binding
        slider.pagerEl.on('click touchend', 'a', clickPagerBind);
      };
  
      /**
       * Appends prev / next controls to the controls element
       */
      var appendControls = function() {
        slider.controls.next = $('<a class="bx-next" href="">' + slider.settings.nextText + '</a>');
        slider.controls.prev = $('<a class="bx-prev" href="">' + slider.settings.prevText + '</a>');
        // add click actions to the controls
        slider.controls.next.on('click touchend', clickNextBind);
        slider.controls.prev.on('click touchend', clickPrevBind);
        // if nextSelector was supplied, populate it
        if (slider.settings.nextSelector) {
          $(slider.settings.nextSelector).append(slider.controls.next);
        }
        // if prevSelector was supplied, populate it
        if (slider.settings.prevSelector) {
          $(slider.settings.prevSelector).append(slider.controls.prev);
        }
        // if no custom selectors were supplied
        if (!slider.settings.nextSelector && !slider.settings.prevSelector) {
          // add the controls to the DOM
          slider.controls.directionEl = $('<div class="bx-controls-direction" />');
          // add the control elements to the directionEl
          slider.controls.directionEl.append(slider.controls.prev).append(slider.controls.next);
          // slider.viewport.append(slider.controls.directionEl);
          slider.controls.el.addClass('bx-has-controls-direction').append(slider.controls.directionEl);
        }
      };
  
      /**
       * Appends start / stop auto controls to the controls element
       */
      var appendControlsAuto = function() {
        slider.controls.start = $('<div class="bx-controls-auto-item"><a class="bx-start" href="">' + slider.settings.startText + '</a></div>');
        slider.controls.stop = $('<div class="bx-controls-auto-item"><a class="bx-stop" href="">' + slider.settings.stopText + '</a></div>');
        // add the controls to the DOM
        slider.controls.autoEl = $('<div class="bx-controls-auto" />');
        // on click actions to the controls
        slider.controls.autoEl.on('click', '.bx-start', clickStartBind);
        slider.controls.autoEl.on('click', '.bx-stop', clickStopBind);
        // if autoControlsCombine, insert only the "start" control
        if (slider.settings.autoControlsCombine) {
          slider.controls.autoEl.append(slider.controls.start);
        // if autoControlsCombine is false, insert both controls
        } else {
          slider.controls.autoEl.append(slider.controls.start).append(slider.controls.stop);
        }
        // if auto controls selector was supplied, populate it with the controls
        if (slider.settings.autoControlsSelector) {
          $(slider.settings.autoControlsSelector).html(slider.controls.autoEl);
        // if auto controls selector was not supplied, add it after the wrapper
        } else {
          slider.controls.el.addClass('bx-has-controls-auto').append(slider.controls.autoEl);
        }
        // update the auto controls
        updateAutoControls(slider.settings.autoStart ? 'stop' : 'start');
      };
  
      /**
       * Appends image captions to the DOM
       */
      var appendCaptions = function() {
        // cycle through each child
        slider.children.each(function(index) {
          // get the image title attribute
          var title = $(this).find('img:first').attr('title');
          // append the caption
          if (title !== undefined && ('' + title).length) {
            $(this).append('<div class="bx-caption"><span>' + title + '</span></div>');
          }
        });
      };
  
      /**
       * Click next binding
       *
       * @param e (event)
       *  - DOM event object
       */
      var clickNextBind = function(e) {
        e.preventDefault();
        if (slider.controls.el.hasClass('disabled')) { return; }
        // if auto show is running, stop it
        if (slider.settings.auto && slider.settings.stopAutoOnClick) { el.stopAuto(); }
        el.goToNextSlide();
      };
  
      /**
       * Click prev binding
       *
       * @param e (event)
       *  - DOM event object
       */
      var clickPrevBind = function(e) {
        e.preventDefault();
        if (slider.controls.el.hasClass('disabled')) { return; }
        // if auto show is running, stop it
        if (slider.settings.auto && slider.settings.stopAutoOnClick) { el.stopAuto(); }
        el.goToPrevSlide();
      };
  
      /**
       * Click start binding
       *
       * @param e (event)
       *  - DOM event object
       */
      var clickStartBind = function(e) {
        el.startAuto();
        e.preventDefault();
      };
  
      /**
       * Click stop binding
       *
       * @param e (event)
       *  - DOM event object
       */
      var clickStopBind = function(e) {
        el.stopAuto();
        e.preventDefault();
      };
  
      /**
       * Click pager binding
       *
       * @param e (event)
       *  - DOM event object
       */
      var clickPagerBind = function(e) {
        var pagerLink, pagerIndex;
        e.preventDefault();
        if (slider.controls.el.hasClass('disabled')) {
          return;
        }
        // if auto show is running, stop it
        if (slider.settings.auto  && slider.settings.stopAutoOnClick) { el.stopAuto(); }
        pagerLink = $(e.currentTarget);
        if (pagerLink.attr('data-slide-index') !== undefined) {
          pagerIndex = parseInt(pagerLink.attr('data-slide-index'));
          // if clicked pager link is not active, continue with the goToSlide call
          if (pagerIndex !== slider.active.index) { el.goToSlide(pagerIndex); }
        }
      };
  
      /**
       * Updates the pager links with an active class
       *
       * @param slideIndex (int)
       *  - index of slide to make active
       */
      var updatePagerActive = function(slideIndex) {
        // if "short" pager type
        var len = slider.children.length; // nb of children
        if (slider.settings.pagerType === 'short') {
          if (slider.settings.maxSlides > 1) {
            len = Math.ceil(slider.children.length / slider.settings.maxSlides);
          }
          slider.pagerEl.html((slideIndex + 1) + slider.settings.pagerShortSeparator + len);
          return;
        }
        // remove all pager active classes
        slider.pagerEl.find('a').removeClass('active');
        // apply the active class for all pagers
        slider.pagerEl.each(function(i, el) { $(el).find('a').eq(slideIndex).addClass('active'); });
      };
  
      /**
       * Performs needed actions after a slide transition
       */
      var updateAfterSlideTransition = function() {
        // if infinite loop is true
        if (slider.settings.infiniteLoop) {
          var position = '';
          // first slide
          if (slider.active.index === 0) {
            // set the new position
            position = slider.children.eq(0).position();
          // carousel, last slide
          } else if (slider.active.index === getPagerQty() - 1 && slider.carousel) {
            position = slider.children.eq((getPagerQty() - 1) * getMoveBy()).position();
          // last slide
          } else if (slider.active.index === slider.children.length - 1) {
            position = slider.children.eq(slider.children.length - 1).position();
          }
          if (position) {
            if (slider.settings.mode === 'horizontal') { setPositionProperty(-position.left, 'reset', 0); }
            else if (slider.settings.mode === 'vertical') { setPositionProperty(-position.top, 'reset', 0); }
          }
        }
        // declare that the transition is complete
        slider.working = false;
        // onSlideAfter callback
        slider.settings.onSlideAfter.call(el, slider.children.eq(slider.active.index), slider.oldIndex, slider.active.index);
      };
  
      /**
       * Updates the auto controls state (either active, or combined switch)
       *
       * @param state (string) "start", "stop"
       *  - the new state of the auto show
       */
      var updateAutoControls = function(state) {
        // if autoControlsCombine is true, replace the current control with the new state
        if (slider.settings.autoControlsCombine) {
          slider.controls.autoEl.html(slider.controls[state]);
        // if autoControlsCombine is false, apply the "active" class to the appropriate control
        } else {
          slider.controls.autoEl.find('a').removeClass('active');
          slider.controls.autoEl.find('a:not(.bx-' + state + ')').addClass('active');
        }
      };
  
      /**
       * Updates the direction controls (checks if either should be hidden)
       */
      var updateDirectionControls = function() {
        if (getPagerQty() === 1) {
          slider.controls.prev.addClass('disabled');
          slider.controls.next.addClass('disabled');
        } else if (!slider.settings.infiniteLoop && slider.settings.hideControlOnEnd) {
          // if first slide
          if (slider.active.index === 0) {
            slider.controls.prev.addClass('disabled');
            slider.controls.next.removeClass('disabled');
          // if last slide
          } else if (slider.active.index === getPagerQty() - 1) {
            slider.controls.next.addClass('disabled');
            slider.controls.prev.removeClass('disabled');
          // if any slide in the middle
          } else {
            slider.controls.prev.removeClass('disabled');
            slider.controls.next.removeClass('disabled');
          }
        }
      };
    /* auto start and stop functions */
    var windowFocusHandler = function() { el.startAuto(); };
    var windowBlurHandler = function() { el.stopAuto(); };
      /**
       * Initializes the auto process
       */
      var initAuto = function() {
        // if autoDelay was supplied, launch the auto show using a setTimeout() call
        if (slider.settings.autoDelay > 0) {
          setTimeout(el.startAuto, slider.settings.autoDelay);
        // if autoDelay was not supplied, start the auto show normally
        } else {
          el.startAuto();
  
          //add focus and blur events to ensure its running if timeout gets paused
          $(window).focus(windowFocusHandler).blur(windowBlurHandler);
        }
        // if autoHover is requested
        if (slider.settings.autoHover) {
          // on el hover
          el.hover(function() {
            // if the auto show is currently playing (has an active interval)
            if (slider.interval) {
              // stop the auto show and pass true argument which will prevent control update
              el.stopAuto(true);
              // create a new autoPaused value which will be used by the relative "mouseout" event
              slider.autoPaused = true;
            }
          }, function() {
            // if the autoPaused value was created be the prior "mouseover" event
            if (slider.autoPaused) {
              // start the auto show and pass true argument which will prevent control update
              el.startAuto(true);
              // reset the autoPaused value
              slider.autoPaused = null;
            }
          });
        }
      };
  
      /**
       * Initializes the ticker process
       */
      var initTicker = function() {
        var startPosition = 0,
        position, transform, value, idx, ratio, property, newSpeed, totalDimens;
        // if autoDirection is "next", append a clone of the entire slider
        if (slider.settings.autoDirection === 'next') {
          el.append(slider.children.clone().addClass('bx-clone'));
        // if autoDirection is "prev", prepend a clone of the entire slider, and set the left position
        } else {
          el.prepend(slider.children.clone().addClass('bx-clone'));
          position = slider.children.first().position();
          startPosition = slider.settings.mode === 'horizontal' ? -position.left : -position.top;
        }
        setPositionProperty(startPosition, 'reset', 0);
        // do not allow controls in ticker mode
        slider.settings.pager = false;
        slider.settings.controls = false;
        slider.settings.autoControls = false;
        // if autoHover is requested
        if (slider.settings.tickerHover) {
          if (slider.usingCSS) {
            idx = slider.settings.mode === 'horizontal' ? 4 : 5;
            slider.viewport.hover(function() {
              transform = el.css('-' + slider.cssPrefix + '-transform');
              value = parseFloat(transform.split(',')[idx]);
              setPositionProperty(value, 'reset', 0);
            }, function() {
              totalDimens = 0;
              slider.children.each(function(index) {
                totalDimens += slider.settings.mode === 'horizontal' ? $(this).outerWidth(true) : $(this).outerHeight(true);
              });
              // calculate the speed ratio (used to determine the new speed to finish the paused animation)
              ratio = slider.settings.speed / totalDimens;
              // determine which property to use
              property = slider.settings.mode === 'horizontal' ? 'left' : 'top';
              // calculate the new speed
              newSpeed = ratio * (totalDimens - (Math.abs(parseInt(value))));
              tickerLoop(newSpeed);
            });
          } else {
            // on el hover
            slider.viewport.hover(function() {
              el.stop();
            }, function() {
              // calculate the total width of children (used to calculate the speed ratio)
              totalDimens = 0;
              slider.children.each(function(index) {
                totalDimens += slider.settings.mode === 'horizontal' ? $(this).outerWidth(true) : $(this).outerHeight(true);
              });
              // calculate the speed ratio (used to determine the new speed to finish the paused animation)
              ratio = slider.settings.speed / totalDimens;
              // determine which property to use
              property = slider.settings.mode === 'horizontal' ? 'left' : 'top';
              // calculate the new speed
              newSpeed = ratio * (totalDimens - (Math.abs(parseInt(el.css(property)))));
              tickerLoop(newSpeed);
            });
          }
        }
        // start the ticker loop
        tickerLoop();
      };
  
      /**
       * Runs a continuous loop, news ticker-style
       */
      var tickerLoop = function(resumeSpeed) {
        var speed = resumeSpeed ? resumeSpeed : slider.settings.speed,
        position = {left: 0, top: 0},
        reset = {left: 0, top: 0},
        animateProperty, resetValue, params;
  
        // if "next" animate left position to last child, then reset left to 0
        if (slider.settings.autoDirection === 'next') {
          position = el.find('.bx-clone').first().position();
        // if "prev" animate left position to 0, then reset left to first non-clone child
        } else {
          reset = slider.children.first().position();
        }
        animateProperty = slider.settings.mode === 'horizontal' ? -position.left : -position.top;
        resetValue = slider.settings.mode === 'horizontal' ? -reset.left : -reset.top;
        params = {resetValue: resetValue};
        setPositionProperty(animateProperty, 'ticker', speed, params);
      };
  
      /**
       * Check if el is on screen
       */
      var isOnScreen = function(el) {
        var win = $(window),
        viewport = {
          top: win.scrollTop(),
          left: win.scrollLeft()
        },
        bounds = el.offset();
  
        viewport.right = viewport.left + win.width();
        viewport.bottom = viewport.top + win.height();
        bounds.right = bounds.left + el.outerWidth();
        bounds.bottom = bounds.top + el.outerHeight();
  
        return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
      };
  
      /**
       * Initializes keyboard events
       */
      var keyPress = function(e) {
        var activeElementTag = document.activeElement.tagName.toLowerCase(),
        tagFilters = 'input|textarea',
        p = new RegExp(activeElementTag,['i']),
        result = p.exec(tagFilters);
  
        if (result == null && isOnScreen(el)) {
          if (e.keyCode === 39) {
            clickNextBind(e);
            return false;
          } else if (e.keyCode === 37) {
            clickPrevBind(e);
            return false;
          }
        }
      };
  
      /**
       * Initializes touch events
       */
      var initTouch = function() {
        // initialize object to contain all touch values
        slider.touch = {
          start: {x: 0, y: 0},
          end: {x: 0, y: 0}
        };
        slider.viewport.on('touchstart MSPointerDown pointerdown', onTouchStart);
  
        //for browsers that have implemented pointer events and fire a click after
        //every pointerup regardless of whether pointerup is on same screen location as pointerdown or not
        slider.viewport.on('click', '.bxslider a', function(e) {
          if (slider.viewport.hasClass('click-disabled')) {
            e.preventDefault();
            slider.viewport.removeClass('click-disabled');
          }
        });
      };
  
      /**
       * Event handler for "touchstart"
       *
       * @param e (event)
       *  - DOM event object
       */
      var onTouchStart = function(e) {
        // watch only for left mouse, touch contact and pen contact
        // touchstart event object doesn`t have button property
        if (e.type !== 'touchstart' && e.button !== 0) {
          return;
        }
        e.preventDefault();
        //disable slider controls while user is interacting with slides to avoid slider freeze that happens on touch devices when a slide swipe happens immediately after interacting with slider controls
        slider.controls.el.addClass('disabled');
  
        if (slider.working) {
          slider.controls.el.removeClass('disabled');
        } else {
          // record the original position when touch starts
          slider.touch.originalPos = el.position();
          var orig = e.originalEvent,
          touchPoints = (typeof orig.changedTouches !== 'undefined') ? orig.changedTouches : [orig];
      var chromePointerEvents = typeof PointerEvent === 'function'; 
      if (chromePointerEvents) { 
        if (orig.pointerId === undefined) { 
          return;
        } 
      }
          // record the starting touch x, y coordinates
          slider.touch.start.x = touchPoints[0].pageX;
          slider.touch.start.y = touchPoints[0].pageY;
  
          if (slider.viewport.get(0).setPointerCapture) {
            slider.pointerId = orig.pointerId;
            slider.viewport.get(0).setPointerCapture(slider.pointerId);
          }
          // store original event data for click fixation
          slider.originalClickTarget = orig.originalTarget || orig.target;
          slider.originalClickButton = orig.button;
          slider.originalClickButtons = orig.buttons;
          slider.originalEventType = orig.type;
          // at this moment we don`t know what it is click or swipe
          slider.hasMove = false;
          // on a "touchmove" event to the viewport
          slider.viewport.on('touchmove MSPointerMove pointermove', onTouchMove);
          // on a "touchend" event to the viewport
          slider.viewport.on('touchend MSPointerUp pointerup', onTouchEnd);
          slider.viewport.on('MSPointerCancel pointercancel', onPointerCancel);
        }
      };
  
      /**
       * Cancel Pointer for Windows Phone
       *
       * @param e (event)
       *  - DOM event object
       */
      var onPointerCancel = function(e) {
        e.preventDefault();
        /* onPointerCancel handler is needed to deal with situations when a touchend
        doesn't fire after a touchstart (this happens on windows phones only) */
        setPositionProperty(slider.touch.originalPos.left, 'reset', 0);
  
        //remove handlers
        slider.controls.el.removeClass('disabled');
        slider.viewport.off('MSPointerCancel pointercancel', onPointerCancel);
        slider.viewport.off('touchmove MSPointerMove pointermove', onTouchMove);
        slider.viewport.off('touchend MSPointerUp pointerup', onTouchEnd);
        if (slider.viewport.get(0).releasePointerCapture) {
          slider.viewport.get(0).releasePointerCapture(slider.pointerId);
        }
      };
  
      /**
       * Event handler for "touchmove"
       *
       * @param e (event)
       *  - DOM event object
       */
      var onTouchMove = function(e) {
        var orig = e.originalEvent,
        touchPoints = (typeof orig.changedTouches !== 'undefined') ? orig.changedTouches : [orig],
        // if scrolling on y axis, do not prevent default
        xMovement = Math.abs(touchPoints[0].pageX - slider.touch.start.x),
        yMovement = Math.abs(touchPoints[0].pageY - slider.touch.start.y),
        value = 0,
        change = 0;
        // this is swipe
        slider.hasMove = true;
  
        // x axis swipe
        if ((xMovement * 3) > yMovement && slider.settings.preventDefaultSwipeX) {
          e.preventDefault();
        // y axis swipe
        } else if ((yMovement * 3) > xMovement && slider.settings.preventDefaultSwipeY) {
          e.preventDefault();
        }
        if (e.type !== 'touchmove') {
          e.preventDefault();
        }
  
        if (slider.settings.mode !== 'fade' && slider.settings.oneToOneTouch) {
          // if horizontal, drag along x axis
          if (slider.settings.mode === 'horizontal') {
            change = touchPoints[0].pageX - slider.touch.start.x;
            value = slider.touch.originalPos.left + change;
          // if vertical, drag along y axis
          } else {
            change = touchPoints[0].pageY - slider.touch.start.y;
            value = slider.touch.originalPos.top + change;
          }
          setPositionProperty(value, 'reset', 0);
        }
      };
  
      /**
       * Event handler for "touchend"
       *
       * @param e (event)
       *  - DOM event object
       */
      var onTouchEnd = function(e) {
        e.preventDefault();
        slider.viewport.off('touchmove MSPointerMove pointermove', onTouchMove);
        //enable slider controls as soon as user stops interacing with slides
        slider.controls.el.removeClass('disabled');
        var orig    = e.originalEvent,
        touchPoints = (typeof orig.changedTouches !== 'undefined') ? orig.changedTouches : [orig],
        value       = 0,
        distance    = 0;
        // record end x, y positions
        slider.touch.end.x = touchPoints[0].pageX;
        slider.touch.end.y = touchPoints[0].pageY;
        // if fade mode, check if absolute x distance clears the threshold
        if (slider.settings.mode === 'fade') {
          distance = Math.abs(slider.touch.start.x - slider.touch.end.x);
          if (distance >= slider.settings.swipeThreshold) {
            if (slider.touch.start.x > slider.touch.end.x) {
              el.goToNextSlide();
            } else {
              el.goToPrevSlide();
            }
            el.stopAuto();
          }
        // not fade mode
        } else {
          // calculate distance and el's animate property
          if (slider.settings.mode === 'horizontal') {
            distance = slider.touch.end.x - slider.touch.start.x;
            value = slider.touch.originalPos.left;
          } else {
            distance = slider.touch.end.y - slider.touch.start.y;
            value = slider.touch.originalPos.top;
          }
          // if not infinite loop and first / last slide, do not attempt a slide transition
          if (!slider.settings.infiniteLoop && ((slider.active.index === 0 && distance > 0) || (slider.active.last && distance < 0))) {
            setPositionProperty(value, 'reset', 200);
          } else {
            // check if distance clears threshold
            if (Math.abs(distance) >= slider.settings.swipeThreshold) {
              if (distance < 0) {
                el.goToNextSlide();
              } else {
                el.goToPrevSlide();
              }
              el.stopAuto();
            } else {
              // el.animate(property, 200);
              setPositionProperty(value, 'reset', 200);
            }
          }
        }
        slider.viewport.off('touchend MSPointerUp pointerup', onTouchEnd);
  
        if (slider.viewport.get(0).releasePointerCapture) {
          slider.viewport.get(0).releasePointerCapture(slider.pointerId);
        }
        // if slider had swipe with left mouse, touch contact and pen contact
        if (slider.hasMove === false && (slider.originalClickButton === 0 || slider.originalEventType === 'touchstart')) {
          // trigger click event (fix for Firefox59 and PointerEvent standard compatibility)
          $(slider.originalClickTarget).trigger({
            type: 'click',
            button: slider.originalClickButton,
            buttons: slider.originalClickButtons
          });
        }
      };
  
      /**
       * Window resize event callback
       */
      var resizeWindow = function(e) {
        // don't do anything if slider isn't initialized.
        if (!slider.initialized) { return; }
        // Delay if slider working.
        if (slider.working) {
          window.setTimeout(resizeWindow, 10);
        } else {
          // get the new window dimens (again, thank you IE)
          var windowWidthNew = $(window).width(),
          windowHeightNew = $(window).height();
          // make sure that it is a true window resize
          // *we must check this because our dinosaur friend IE fires a window resize event when certain DOM elements
          // are resized. Can you just die already?*
          if (windowWidth !== windowWidthNew || windowHeight !== windowHeightNew) {
            // set the new window dimens
            windowWidth = windowWidthNew;
            windowHeight = windowHeightNew;
            // update all dynamic elements
            el.redrawSlider();
            // Call user resize handler
            slider.settings.onSliderResize.call(el, slider.active.index);
          }
        }
      };
  
      /**
       * Adds an aria-hidden=true attribute to each element
       *
       * @param startVisibleIndex (int)
       *  - the first visible element's index
       */
      var applyAriaHiddenAttributes = function(startVisibleIndex) {
        var numberOfSlidesShowing = getNumberSlidesShowing();
        // only apply attributes if the setting is enabled and not in ticker mode
        if (slider.settings.ariaHidden && !slider.settings.ticker) {
          // add aria-hidden=true to all elements
          slider.children.attr('aria-hidden', 'true');
          // get the visible elements and change to aria-hidden=false
          slider.children.slice(startVisibleIndex, startVisibleIndex + numberOfSlidesShowing).attr('aria-hidden', 'false');
        }
      };
  
      /**
       * Returns index according to present page range
       *
       * @param slideOndex (int)
       *  - the desired slide index
       */
      var setSlideIndex = function(slideIndex) {
        if (slideIndex < 0) {
          if (slider.settings.infiniteLoop) {
            return getPagerQty() - 1;
          }else {
            //we don't go to undefined slides
            return slider.active.index;
          }
        // if slideIndex is greater than children length, set active index to 0 (this happens during infinite loop)
        } else if (slideIndex >= getPagerQty()) {
          if (slider.settings.infiniteLoop) {
            return 0;
          } else {
            //we don't move to undefined pages
            return slider.active.index;
          }
        // set active index to requested slide
        } else {
          return slideIndex;
        }
      };
  
      /**
       * ===================================================================================
       * = PUBLIC FUNCTIONS
       * ===================================================================================
       */
  
      /**
       * Performs slide transition to the specified slide
       *
       * @param slideIndex (int)
       *  - the destination slide's index (zero-based)
       *
       * @param direction (string)
       *  - INTERNAL USE ONLY - the direction of travel ("prev" / "next")
       */
      el.goToSlide = function(slideIndex, direction) {
        // onSlideBefore, onSlideNext, onSlidePrev callbacks
        // Allow transition canceling based on returned value
        var performTransition = true,
        moveBy = 0,
        position = {left: 0, top: 0},
        lastChild = null,
        lastShowingIndex, eq, value, requestEl;
        // store the old index
        slider.oldIndex = slider.active.index;
        //set new index
        slider.active.index = setSlideIndex(slideIndex);
  
        // if plugin is currently in motion, ignore request
        if (slider.working || slider.active.index === slider.oldIndex) { return; }
        // declare that plugin is in motion
        slider.working = true;
  
        performTransition = slider.settings.onSlideBefore.call(el, slider.children.eq(slider.active.index), slider.oldIndex, slider.active.index);
  
        // If transitions canceled, reset and return
        if (typeof (performTransition) !== 'undefined' && !performTransition) {
          slider.active.index = slider.oldIndex; // restore old index
          slider.working = false; // is not in motion
          return;
        }
  
        if (direction === 'next') {
          // Prevent canceling in future functions or lack there-of from negating previous commands to cancel
          if (!slider.settings.onSlideNext.call(el, slider.children.eq(slider.active.index), slider.oldIndex, slider.active.index)) {
            performTransition = false;
          }
        } else if (direction === 'prev') {
          // Prevent canceling in future functions or lack there-of from negating previous commands to cancel
          if (!slider.settings.onSlidePrev.call(el, slider.children.eq(slider.active.index), slider.oldIndex, slider.active.index)) {
            performTransition = false;
          }
        }
  
        // check if last slide
        slider.active.last = slider.active.index >= getPagerQty() - 1;
        // update the pager with active class
        if (slider.settings.pager || slider.settings.pagerCustom) { updatePagerActive(slider.active.index); }
        // // check for direction control update
        if (slider.settings.controls) { updateDirectionControls(); }
        // if slider is set to mode: "fade"
        if (slider.settings.mode === 'fade') {
          // if adaptiveHeight is true and next height is different from current height, animate to the new height
          if (slider.settings.adaptiveHeight && slider.viewport.height() !== getViewportHeight()) {
            slider.viewport.animate({height: getViewportHeight()}, slider.settings.adaptiveHeightSpeed);
          }
          // fade out the visible child and reset its z-index value
          slider.children.filter(':visible').fadeOut(slider.settings.speed).css({zIndex: 0});
          // fade in the newly requested slide
          slider.children.eq(slider.active.index).css('zIndex', slider.settings.slideZIndex + 1).fadeIn(slider.settings.speed, function() {
            $(this).css('zIndex', slider.settings.slideZIndex);
            updateAfterSlideTransition();
          });
        // slider mode is not "fade"
        } else {
          // if adaptiveHeight is true and next height is different from current height, animate to the new height
          if (slider.settings.adaptiveHeight && slider.viewport.height() !== getViewportHeight()) {
            slider.viewport.animate({height: getViewportHeight()}, slider.settings.adaptiveHeightSpeed);
          }
          // if carousel and not infinite loop
          if (!slider.settings.infiniteLoop && slider.carousel && slider.active.last) {
            if (slider.settings.mode === 'horizontal') {
              // get the last child position
              lastChild = slider.children.eq(slider.children.length - 1);
              position = lastChild.position();
              // calculate the position of the last slide
              moveBy = slider.viewport.width() - lastChild.outerWidth();
            } else {
              // get last showing index position
              lastShowingIndex = slider.children.length - slider.settings.minSlides;
              position = slider.children.eq(lastShowingIndex).position();
            }
            // horizontal carousel, going previous while on first slide (infiniteLoop mode)
          } else if (slider.carousel && slider.active.last && direction === 'prev') {
            // get the last child position
            eq = slider.settings.moveSlides === 1 ? slider.settings.maxSlides - getMoveBy() : ((getPagerQty() - 1) * getMoveBy()) - (slider.children.length - slider.settings.maxSlides);
            lastChild = el.children('.bx-clone').eq(eq);
            position = lastChild.position();
          // if infinite loop and "Next" is clicked on the last slide
          } else if (direction === 'next' && slider.active.index === 0) {
            // get the last clone position
            position = el.find('> .bx-clone').eq(slider.settings.maxSlides).position();
            slider.active.last = false;
          // normal non-zero requests
          } else if (slideIndex >= 0) {
            //parseInt is applied to allow floats for slides/page
            requestEl = slideIndex * parseInt(getMoveBy());
            position = slider.children.eq(requestEl).position();
          }
  
          /* If the position doesn't exist
           * (e.g. if you destroy the slider on a next click),
           * it doesn't throw an error.
           */
          if (typeof (position) !== 'undefined') {
            value = slider.settings.mode === 'horizontal' ? -(position.left - moveBy) : -position.top;
            // plugin values to be animated
            setPositionProperty(value, 'slide', slider.settings.speed);
          }
          slider.working = false;
        }
        if (slider.settings.ariaHidden) { applyAriaHiddenAttributes(slider.active.index * getMoveBy()); }
      };
  
      /**
       * Transitions to the next slide in the show
       */
      el.goToNextSlide = function() {
        // if infiniteLoop is false and last page is showing, disregard call
        if (!slider.settings.infiniteLoop && slider.active.last) { return; }
      if (slider.working === true){ return ;}
        var pagerIndex = parseInt(slider.active.index) + 1;
        el.goToSlide(pagerIndex, 'next');
      };
  
      /**
       * Transitions to the prev slide in the show
       */
      el.goToPrevSlide = function() {
        // if infiniteLoop is false and last page is showing, disregard call
        if (!slider.settings.infiniteLoop && slider.active.index === 0) { return; }
      if (slider.working === true){ return ;}
        var pagerIndex = parseInt(slider.active.index) - 1;
        el.goToSlide(pagerIndex, 'prev');
      };
  
      /**
       * Starts the auto show
       *
       * @param preventControlUpdate (boolean)
       *  - if true, auto controls state will not be updated
       */
      el.startAuto = function(preventControlUpdate) {
        // if an interval already exists, disregard call
        if (slider.interval) { return; }
        // create an interval
        slider.interval = setInterval(function() {
          if (slider.settings.autoDirection === 'next') {
            el.goToNextSlide();
          } else {
            el.goToPrevSlide();
          }
        }, slider.settings.pause);
      //allback for when the auto rotate status changes
      slider.settings.onAutoChange.call(el, true);
        // if auto controls are displayed and preventControlUpdate is not true
        if (slider.settings.autoControls && preventControlUpdate !== true) { updateAutoControls('stop'); }
      };
  
      /**
       * Stops the auto show
       *
       * @param preventControlUpdate (boolean)
       *  - if true, auto controls state will not be updated
       */
      el.stopAuto = function(preventControlUpdate) {
        // if slider is auto paused, just clear that state
        if (slider.autoPaused) slider.autoPaused = false;
        // if no interval exists, disregard call
        if (!slider.interval) { return; }
        // clear the interval
        clearInterval(slider.interval);
        slider.interval = null;
      //allback for when the auto rotate status changes
      slider.settings.onAutoChange.call(el, false);
        // if auto controls are displayed and preventControlUpdate is not true
        if (slider.settings.autoControls && preventControlUpdate !== true) { updateAutoControls('start'); }
      };
  
      /**
       * Returns current slide index (zero-based)
       */
      el.getCurrentSlide = function() {
        return slider.active.index;
      };
  
      /**
       * Returns current slide element
       */
      el.getCurrentSlideElement = function() {
        return slider.children.eq(slider.active.index);
      };
  
      /**
       * Returns a slide element
       * @param index (int)
       *  - The index (zero-based) of the element you want returned.
       */
      el.getSlideElement = function(index) {
        return slider.children.eq(index);
      };
  
      /**
       * Returns number of slides in show
       */
      el.getSlideCount = function() {
        return slider.children.length;
      };
  
      /**
       * Return slider.working variable
       */
      el.isWorking = function() {
        return slider.working;
      };
  
      /**
       * Update all dynamic slider elements
       */
      el.redrawSlider = function() {
        // resize all children in ratio to new screen size
        slider.children.add(el.find('.bx-clone')).outerWidth(getSlideWidth());
        // adjust the height
        slider.viewport.css('height', getViewportHeight());
        // update the slide position
        if (!slider.settings.ticker) { setSlidePosition(); }
        // if active.last was true before the screen resize, we want
        // to keep it last no matter what screen size we end on
        if (slider.active.last) { slider.active.index = getPagerQty() - 1; }
        // if the active index (page) no longer exists due to the resize, simply set the index as last
        if (slider.active.index >= getPagerQty()) { slider.active.last = true; }
        // if a pager is being displayed and a custom pager is not being used, update it
        if (slider.settings.pager && !slider.settings.pagerCustom) {
          populatePager();
          updatePagerActive(slider.active.index);
        }
        if (slider.settings.ariaHidden) { applyAriaHiddenAttributes(slider.active.index * getMoveBy()); }
      };
  
      /**
       * Destroy the current instance of the slider (revert everything back to original state)
       */
      el.destroySlider = function() {
        // don't do anything if slider has already been destroyed
        if (!slider.initialized) { return; }
        slider.initialized = false;
        $('.bx-clone', this).remove();
        slider.children.each(function() {
          if ($(this).data('origStyle') !== undefined) {
            $(this).attr('style', $(this).data('origStyle'));
          } else {
            $(this).removeAttr('style');
          }
        });
        if ($(this).data('origStyle') !== undefined) {
          this.attr('style', $(this).data('origStyle'));
        } else {
          $(this).removeAttr('style');
        }
        $(this).unwrap().unwrap();
        if (slider.controls.el) { slider.controls.el.remove(); }
        if (slider.controls.next) { slider.controls.next.remove(); }
        if (slider.controls.prev) { slider.controls.prev.remove(); }
        if (slider.pagerEl && slider.settings.controls && !slider.settings.pagerCustom) { slider.pagerEl.remove(); }
        $('.bx-caption', this).remove();
        if (slider.controls.autoEl) { slider.controls.autoEl.remove(); }
        clearInterval(slider.interval);
        if (slider.settings.responsive) { $(window).off('resize', resizeWindow); }
        if (slider.settings.keyboardEnabled) { $(document).off('keydown', keyPress); }
        //remove self reference in data
        $(this).removeData('bxSlider');
      // remove global window handlers
      $(window).off('blur', windowBlurHandler).off('focus', windowFocusHandler);
      };
  
      /**
       * Reload the slider (revert all DOM changes, and re-initialize)
       */
      el.reloadSlider = function(settings) {
        if (settings !== undefined) { options = settings; }
        el.destroySlider();
        init();
        //store reference to self in order to access public functions later
        $(el).data('bxSlider', this);
      };
  
      init();
  
      $(el).data('bxSlider', this);
  
      // returns the current jQuery object
      return this;
    };
  
  })(jQuery);
!function(t,e,i){function n(t){return t.replace(/\s*$/,"")}function s(t,e){if(t.innerText)t.innerText=e;else if(t.nodeValue)t.nodeValue=e;else{if(!t.textContent)return!1;t.textContent=e}}function o(t,e,i,n){var o,h=t.parent();t.remove();var r=i?i.length:0;if(h.contents().length>r)return o=h.contents().eq(-1-r),a(o,e,i,n);var l=h.prev();return o=l.contents().eq(-1),!!o.length&&(s(o[0],o.text()+n.ellipsis),h.remove(),i.length&&l.append(i),!0)}function h(t,e,i,h){for(var r,l,a=t[0],p=t.text(),d="",c=0,u=p.length;c<=u;)r=c+(u-c>>1),l=h.ellipsis+n(p.substr(r-1,p.length)),s(a,l),e.height()>h.maxHeight?c=r+1:(u=r-1,d=d.length>l.length?d:l);return d.length>0?(s(a,d),!0):o(t,e,i,h)}function r(t,e,i,h){for(var r,l,a=t[0],p=t.text(),d="",c=0,u=p.length;c<=u;)r=c+(u-c>>1),l=n(p.substr(0,r+1))+h.ellipsis,s(a,l),e.height()>h.maxHeight?u=r-1:(c=r+1,d=d.length>l.length?d:l);return d.length>0?(s(a,d),!0):o(t,e,i,h)}function l(t,e,i,h){for(var r,l,a=t[0],p=t.text(),d="",c=0,u=p.length,g=u>>1;c<=g;)r=c+(g-c>>1),l=n(p.substr(0,r))+h.ellipsis+p.substr(u-r,u-r),s(a,l),e.height()>h.maxHeight?g=r-1:(c=r+1,d=d.length>l.length?d:l);return d.length>0?(s(a,d),!0):o(t,e,i,h)}function a(t,e,i,n){return"end"===n.position?r(t,e,i,n):"start"===n.position?h(t,e,i,n):l(t,e,i,n)}function p(t,i,n,s){var o,h,r=t[0],l=t.contents(),p=l.length,d=p-1,u=!1;for(t.empty();d>=0&&!u;d--)o=l.eq(d),h=o[0],8!==h.nodeType&&(r.insertBefore(h,r.firstChild),n.length&&(e.inArray(r.tagName.toLowerCase(),g)>=0?t.after(n):t.append(n)),i.height()>s.maxHeight&&(u=3===h.nodeType?a(o,i,n,s):c(o,i,n,s)),!u&&n.length&&n.remove());return u}function d(t,i,n,s){var o,h,r=t[0],l=t.contents(),p=0,d=l.length,u=!1;for(t.empty();p<d&&!u;p++)o=l.eq(p),h=o[0],8!==h.nodeType&&(r.appendChild(h),n.length&&(e.inArray(r.tagName.toLowerCase(),g)>=0?t.after(n):t.append(n)),i.height()>s.maxHeight&&(u=3===h.nodeType?a(o,i,n,s):c(o,i,n,s)),!u&&n.length&&n.remove());return u}function c(t,e,i,n){return"end"===n.position?d(t,e,i,n):"start"===n.position?p(t,e,i,n):d(t,e,i,n)}function u(t,i){this.element=t,this.$element=e(t),this._name="truncate",this._defaults={lines:1,ellipsis:"…",showMore:"",showLess:"",position:"end",lineHeight:"auto"},this.config(i),this.original=this.cached=t.innerHTML,this.isTruncated=!1,this.isCollapsed=!0,this.update()}var g=["table","thead","tbody","tfoot","tr","col","colgroup","object","embed","param","ol","ul","dl","blockquote","select","optgroup","option","textarea","script","style"];u.prototype={config:function(t){if(this.options=e.extend({},this._defaults,t),"auto"===this.options.lineHeight){var n=this.$element.css("line-height"),s=18;"normal"!==n&&(s=parseInt(n,10)),this.options.lineHeight=s}this.options.maxHeight===i&&(this.options.maxHeight=parseInt(this.options.lines,10)*parseInt(this.options.lineHeight,10)),"start"!==this.options.position&&"middle"!==this.options.position&&"end"!==this.options.position&&(this.options.position="end"),this.$clipNode=e(e.parseHTML(this.options.showMore),this.$element),this.original&&this.update()},update:function(t){var e=!this.isCollapsed;"undefined"!=typeof t?this.original=this.element.innerHTML=t:this.isCollapsed&&this.element.innerHTML===this.cached&&(this.element.innerHTML=this.original);var i=this.$element.wrapInner("<div/>").children();i.css({border:"none",margin:0,padding:0,width:"auto",height:"auto","word-wrap":"break-word"}),this.isTruncated=!1,i.height()>this.options.maxHeight?(this.isTruncated=c(i,i,this.$clipNode,this.options),this.isExplicitlyCollapsed&&(this.isCollapsed=!0,e=!1)):this.isCollapsed=!1,i.replaceWith(i.contents()),this.cached=this.element.innerHTML,e&&(this.element.innerHTML=this.original)},expand:function(){var t=!0;this.isExplicitlyCollapsed&&(this.isExplicitlyCollapsed=!1,t=!1),this.isCollapsed&&(this.isCollapsed=!1,this.element.innerHTML=this.isTruncated?this.original+(t?this.options.showLess:""):this.original)},collapse:function(t){this.isExplicitlyCollapsed=!0,this.isCollapsed||(this.isCollapsed=!0,t=t||!1,t?this.update():this.element.innerHTML=this.cached)}},e.fn.truncate=function(t){var i=e.makeArray(arguments).slice(1);return this.each(function(){var n=e.data(this,"jquery-truncate");n?"function"==typeof n[t]&&n[t].apply(n,i):e.data(this,"jquery-truncate",new u(this,t))})},t.Truncate=u}(this,jQuery);
var isMobile = {
    Windows: function () {
        return /IEMobile/i.test(navigator.userAgent);
    },
    Android: function () {
        return /Android/i.test(navigator.userAgent);
    },
    BlackBerry: function () {
        return /BlackBerry/i.test(navigator.userAgent);
    },
    iOS: function () {
        return /iPhone|iPad|iPod/i.test(navigator.userAgent);
    },
    any: function () {
        return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Windows());
    }
};

AUI().use('aui-toggler', function (A) {
    if (A.one('.jobsearch-filter-options')) {
        try {
            new A.TogglerDelegate({
                animated: false,
                expanded: false,
                closeAllOnExpand: false,
                container: '.jobsearch-filter-options',
                content: '.js-jobsearch-content',
                header: '.js-jobsearch-header'
            });
        } catch (ex) {
            console.log(ex);
        }
    }
});

(function () {
    var $, GoogleMap, LocationsFilter, MapOptions, SELECTORS,
            bind = function (fn, me) {
                return function () {
                    return fn.apply(me, arguments);
                };
            };

    $ = jQuery;

    SELECTORS = {
        searchSortBySelect: '.search__toolbar__sort-by select',
        searchHelpText: '.hays__search__help-text',
        searchHelpIcon: '.hays__search__help-icon',
        searchResultHeaderFavorite: '.search__result__header__favorite',
        searchToolbarFavorite: '.search__toolbar__favorites',
        queryInputField: '.hays__search__input',
        searchToolbarFavorites: '.search__toolbar__favorites, .search__toolbar__favorites:after',
        locationsFilterSelect: '#hays__r1__locations__filter__select',
        locationsFilterReset: '.hays__r1__locations__filter__reset__link,.hays__r1__locations__filter__reset__button',
        locationsFilterNothingFound: '.hays__r1__locations__list__nothing-found',
        locationsCities: '[data-city]'
    };

    LocationsFilter = (function () {
        function LocationsFilter() {
            this.onFilterReset = bind(this.onFilterReset, this);
            this.onBlur = bind(this.onBlur, this);
            this.onChange = bind(this.onChange, this);
            this.onType = bind(this.onType, this);
            var selectizeTarget;
            selectizeTarget = $(SELECTORS.locationsFilterSelect);
            this.curVal = '';
            this.originalPlaceholder = selectizeTarget.attr('placeholder');
            this.select = selectizeTarget.selectize({
                onType: this.onType,
                onChange: this.onChange,
                onBlur: this.onBlur
            });
            $(SELECTORS.locationsFilterReset).on('click', this.onFilterReset);
        }

        LocationsFilter.prototype.onType = function (val) {
            var $cities, hiddenCount;
            $(SELECTORS.locationsFilterNothingFound).addClass('hidden');
            this.curVal = val;
            hiddenCount = 0;
            $cities = $(SELECTORS.locationsCities);
            $cities.each(function (i, el) {
                if (!$(el).data('city').match(RegExp(".*" + val + ".*", "i"))) {
                    $(el).hide();
                    return hiddenCount += 1;
                } else {
                    return $(el).show();
                }
            });
            if ($cities.length === hiddenCount) {
                return $(SELECTORS.locationsFilterNothingFound).removeClass('hidden');
            }
        };

        LocationsFilter.prototype.onChange = function (val) {
            var target;
            target = $("[data-city='" + val + "']");
            return location.href = target.attr('href');
        };

        LocationsFilter.prototype.onBlur = function (val) {
            return this._updatePlaceholder(this.curVal);
        };

        LocationsFilter.prototype.onFilterReset = function () {
            var selectize;
            selectize = this._getSelectizeInstance();
            this.curVal = '';
            this._updatePlaceholder(this.originalPlaceholder);
            $(SELECTORS.locationsCities).show();
            return $(SELECTORS.locationsFilterNothingFound).addClass('hidden');
        };

        LocationsFilter.prototype._updatePlaceholder = function (placeholder) {
            var selectize;
            selectize = this._getSelectizeInstance();
            selectize.settings.placeholder = placeholder;
            return selectize.updatePlaceholder();
        };

        LocationsFilter.prototype._getSelectizeInstance = function () {
            return this.select[0].selectize;
        };

        return LocationsFilter;

    })();

    MapOptions = {
        mapTypeControl: false,
        scrollwheel: false,
        zoom: 15,
        styles: [
            {
                "featureType": "all",
                "elementType": "labels.text.fill",
                "stylers": [
                    {
                        "saturation": 36
                    }, {
                        "color": "#333333"
                    }, {
                        "lightness": 40
                    }
                ]
            }, {
                "featureType": "all",
                "elementType": "labels.text.stroke",
                "stylers": [
                    {
                        "visibility": "on"
                    }, {
                        "color": "#ffffff"
                    }, {
                        "lightness": 16
                    }
                ]
            }, {
                "featureType": "all",
                "elementType": "labels.icon",
                "stylers": [
                    {
                        "visibility": "off"
                    }
                ]
            }, {
                "featureType": "administrative",
                "elementType": "geometry.fill",
                "stylers": [
                    {
                        "color": "#fefefe"
                    }, {
                        "lightness": 20
                    }
                ]
            }, {
                "featureType": "administrative",
                "elementType": "geometry.stroke",
                "stylers": [
                    {
                        "color": "#fefefe"
                    }, {
                        "lightness": 17
                    }, {
                        "weight": 1.2
                    }
                ]
            }, {
                "featureType": "landscape",
                "elementType": "geometry",
                "stylers": [
                    {
                        "color": "#f5f5f5"
                    }, {
                        "lightness": "-4"
                    }, {
                        "saturation": "0"
                    }
                ]
            }, {
                "featureType": "poi",
                "elementType": "geometry",
                "stylers": [
                    {
                        "color": "#f5f5f5"
                    }, {
                        "lightness": 21
                    }
                ]
            }, {
                "featureType": "poi.park",
                "elementType": "geometry",
                "stylers": [
                    {
                        "color": "#dedede"
                    }, {
                        "lightness": 21
                    }
                ]
            }, {
                "featureType": "road.highway",
                "elementType": "geometry.fill",
                "stylers": [
                    {
                        "color": "#ffffff"
                    }, {
                        "lightness": 17
                    }
                ]
            }, {
                "featureType": "road.highway",
                "elementType": "geometry.stroke",
                "stylers": [
                    {
                        "color": "#ffffff"
                    }, {
                        "lightness": 29
                    }, {
                        "weight": 0.2
                    }
                ]
            }, {
                "featureType": "road.arterial",
                "elementType": "geometry",
                "stylers": [
                    {
                        "color": "#ffffff"
                    }, {
                        "lightness": 18
                    }
                ]
            }, {
                "featureType": "road.local",
                "elementType": "geometry",
                "stylers": [
                    {
                        "color": "#ffffff"
                    }, {
                        "lightness": 16
                    }
                ]
            }, {
                "featureType": "transit",
                "elementType": "geometry",
                "stylers": [
                    {
                        "color": "#f2f2f2"
                    }, {
                        "lightness": "15"
                    }, {
                        "visibility": "on"
                    }
                ]
            }, {
                "featureType": "transit.station",
                "elementType": "all",
                "stylers": [
                    {
                        "visibility": "on"
                    }
                ]
            }, {
                "featureType": "water",
                "elementType": "geometry",
                "stylers": [
                    {
                        "color": "#009ed9"
                    }, {
                        "lightness": "90"
                    }, {
                        "saturation": "-50"
                    }
                ]
            }
        ]
    };

    GoogleMap = (function () {
        function GoogleMap() {}

        GoogleMap.prototype.initInstance = function () {
            this.$mapEl = $('#js-map');
            if (this.$mapEl.length > 0) {
                this.set_map_section_height();
                this.add_map();
                this.add_map_markers();
                return google.maps.event.addDomListener(window, "resize", (function (_this) {
                    return function () {
                        var center;
                        center = _this.map.getCenter();
                        google.maps.event.trigger(_this.map, "resize");
                        return _this.map.setCenter(center);
                    };
                })(this));
            }
        };

        GoogleMap.prototype.set_map_section_height = function () {
            var new_map_height;
            new_map_height = $('#js-map').parent().height();
            return $('#js-map').height(new_map_height);
        };

        GoogleMap.prototype.add_map = function () {
            var center;
            center = new google.maps.LatLng(this.$mapEl.data('lat'), this.$mapEl.data('lng'));
            MapOptions.center = center;
            MapOptions.mapTypeId = google.maps.MapTypeId.ROADMAP;
            return this.map = new google.maps.Map($('#js-map').get(0), MapOptions);
        };

        GoogleMap.prototype.add_map_markers = function () {
            var icon, marker;
            icon = new google.maps.MarkerImage("/img/hays-map-marker.png", null, null, null, new google.maps.Size(64, 64));
            return marker = new google.maps.Marker({
                position: new google.maps.LatLng(this.$mapEl.data('lat'), this.$mapEl.data('lng')),
                map: this.map,
                title: this.$mapEl.data('title'),
                icon: icon
            });
        };

        GoogleMap.prototype.update = function (lat, lng) {
            return this.map.setCenter(new google.maps.LatLng(lat, lng));
        };

        return GoogleMap;

    })();

    createFavoritePopover = function (favoriteElem, popoverContainerSelector) {
        $(favoriteElem).popover({
            html: true,
            content: function () {
                var count = $(SELECTORS.searchToolbarFavorites).data('count');
                var maxCount = $(SELECTORS.searchToolbarFavorites).data('maxcount');
                var template = $(SELECTORS.searchToolbarFavorites).data((parseInt(count) >= parseInt(maxCount)) ? 'exceeded-template' : 'count-template');
                return template.replace('@count', count).replace('@maxcount', maxCount);
            },
            placement: 'top',
            container: popoverContainerSelector,
            trigger: isMobile.any() ? 'manual' : 'hover',
            delay: {"show": 100, "hide": 100}
        });
    };

    $(document).ready(function () {
        var gm;
        $(SELECTORS.searchSortBySelect).selectize({
            create: false,
            sortField: 'text'
        });
        $(SELECTORS.searchResultHeaderFavorite).each(function () {
            createFavoritePopover(this, 'body');
        });
        $(SELECTORS.searchToolbarFavorite).each(function () {
            createFavoritePopover(this, SELECTORS.searchToolbarFavorite);
        });
        $(SELECTORS.queryInputField).each(function () {
            $(this).popover({
                html: true,
                content: $(this).data('maxlength-template').replace('@maxlength', $(this).attr('maxlength')),
                placement: 'right',
                container: 'body'
            });
        });
        $(SELECTORS.queryInputField).on(isMobile.any() ? 'keyup focus click' : 'keyup mouseenter mouseleave focus click', function () {
            if (parseInt($(this).val().length) >= parseInt($(this).attr('maxlength'))) {
                return $(this).popover('show');
            } else {
                return $(this).popover('hide');
            }
        });
        new LocationsFilter;
        gm = new GoogleMap;
        gm.initInstance();
        $('.hays__r1__location__carousel').bxSlider();
        if ($('.bx-pager-item').length < 2) {
            $('.bx-pager').hide();
        }
        if ($('.hays__r1__events__col').length === 0 || $('.hays__r1__events__col').length && $('.hays__r1__events__col').css('display') === 'none') {
            $('.hays__r1__location__map__col').css('width', '100%').css('flex', '0 0 100%').css('max-width', '100%');
        }
        
        $('[data-toggle]').click(function () {
            var target;
            target = $(this).data('toggle');
            if ($(target).css('display') === 'block') {
                $(this).removeClass('open');
                return $(target).hide();
            } else {
                $(this).addClass('open');
                return $(target).show();
            }
        });
       
    });

}).call(this);

var change_width = 991;

$(".search__filters__filter").bind( "click", function() {
    if ($(window).width() > change_width) {                
        //Alle Dropdowns automatisch schließen, wenn eine andere Dropdown geöffnet wird.
        $(".search__filters__filter").not(this).each(function() {
            
            if ($(this).closest("li").siblings(".hassubs-filter").css("display") == "list-item" || $(this).parent("li").next().css("display") == "list-item") {
                $(this).closest("li").siblings(".hassubs-filter").slideToggle();//Schließ dropdown

                if($(this).parent("li").find("hr").css("display") == "block"){//Hide hr
                    $(this).parent("li").find("hr").toggle();
                }         
                   
            }
        });
 
        //Für Desktop blendet dropdown ein
        $(this).closest("li").siblings(".hassubs-filter").slideToggle();
        $(this).parent("li").find("hr").toggle();     
   
    }
    if ($(window).width() < change_width) {
        //Für Mobile blendet dropdown in Full-Width ein
        $(this).parent("li").parent("ul").toggleClass("make-it-fullscreen");
        $(this).closest(".dropdown-filter").toggleClass("opacity-one");
        $(this).closest("li").siblings(".hassubs-filter").slideToggle();
    }
   
});
$(".search__filters__filter__subfilter").bind( "click", function() {   
    //Für mobile,blendet zweite dropdown ein (Full-Width)
    if ($(window).width() < change_width) {
        $(this).next().toggleClass("opacity-one");
        $(this).next().children().toggleClass("make-it-fullscreen");
        $(this).next().children().children().first().toggle();//Back button
    }
});
$("#filter__button").bind( "click", function() {
    //Suchfilter werden on filter__button click angezeigt
    if ($(window).width() < change_width) {
        $("ul.search__filters").slideToggle();
        $("ul.search__filters").toggleClass("make-it-fullscreen");
        $("ul.search__filters").children().first().toggle();
        $(".search__projektBoerse__desktop").toggle();
        $(".search__toolbar__item").each(function() {
            $(this).toggle();
        });
     $('.hays__search__number-of-results').addClass('hays__search__number-of-results-show');
    }
});

//Die überschrifte und icon nur für mobile
$(".search__filters__contract-filter").bind( "click", function() {
    if ($(window).width() < change_width) {
        $("#search__chevron__jobtype").toggle();
        $("#mobile__title__jobtype").toggle();
        $(this).parent().prev().prev().toggle();
    }
});
$(".search__filters__specialism-filter").bind( "click", function() {
    if ($(window).width() < change_width) {
        $("#search__chevron__specialism").toggle();
        $("#mobile__title__specialism").toggle();
        $(this).parent().prev().prev().toggle();
    }
});
$(".search__filters__industry-filter").bind( "click", function() {
    if ($(window).width() < change_width) {
        $("#search__chevron__branch").toggle();
        $("#mobile__title__branch").toggle();
        $(this).parent().prev().prev().toggle();
    }
});
$(".search__filters__region-filter").bind( "click", function() {
    if ($(window).width() < change_width) {
        $("#search__chevron__land").toggle();
        $("#mobile__title__land").toggle();
        $(this).parent().prev().prev().toggle();
    }
});

//Back button actions nur mobile
$(".back-button").bind( "click", function() {
    if ($(window).width() < change_width) {
        $(this).parent().removeClass("make-it-fullscreen");
        $(this).toggle();
        $(this).parent().toggle();
        $(".search__toolbar__item").each(function() {
            $(this).toggle();
        });  
        $('.hays__search__number-of-results').removeClass('hays__search__number-of-results-show');      
    }
});
$(".back-button-2").bind( "click", function() {
    if ($(window).width() < change_width) {
        $(this).toggle();
        $(this).next().toggle();
        $(this).parent().removeClass("make-it-fullscreen");
        $(".hassubs-filter").each(function() {
            if ($(this).css("display") == "list-item") {
                $(this).slideToggle();
                $(this).closest("hr").toggle();
            }
        });
        //Check if single filter reset button is visible
        if($(this).next().next().next().css('display')=='list-item'){
            $(this).next().next().next().toggle();
        }
    }
});
$(".back-button-3").bind( "click", function() {
    if ($(window).width() < change_width) {
        $(this).toggle();
        $(this).parent().parent().removeClass("opacity-one");
        $(this).parent().removeClass("make-it-fullscreen");
        
        
    }
});

$(window).on('resize', function(event){
    var windowSize = $(window).width(); 
    if(windowSize >= change_width){
        $('.search__filters').show();
    } 
}); 
var Ui_Combo = function(
    container,
    options = {
        empty_elem: true,
        placeholder: ""
    }
) {
    this.options = options;

    this.options.empty_elem = options.empty_elem || true;
    this.options.placeholder = options.placeholder || "";

    this.$container = container;
    this.$elems = [];
    this.$selected = null;
    this.$first = null;
    let that = this;

    function set_selected(elem) {
        if (that.$first) {
            that.$first.innerHTML = elem.innerHTML;
            that.$first.dataset.val = elem.dataset.val;
        }
    }

    function add(text, val, selected = false) {
        let result = document.createElement("li");

        result.innerHTML = text;
        result.dataset.val = val;
        result.classList.add("elem");

        result.show = function() {
            this.style.visibility = "visible";

            let height = getComputedStyle(that.$container).getPropertyValue(
                "--elem-height"
            );

            this.style.height = height;
        };

        result.hide = function() {
            this.style.visibility = "hidden";
            this.style.height = 0;
        };

        result.toggle = function() {
            let vis = getComputedStyle(this).getPropertyValue("visibility");
            vis == "hidden" ? this.show() : this.hide();
        };

        result.onclick = function() {
            set_selected(this);
            that.collapse();
            that.onchange();
        };

        if (selected) {
            set_selected(result);
        }

        this.$elems.push(result);
        this.$container.appendChild(result);

        return result;
    }

    function collapse() {
        let elems = that.$elems.slice(1);
        elems.forEach(el => {
            el.hide();
        });
    }

    function val() {
        let result = this.$first.dataset.val;

        return result;
    }

    that.add = add;
    that.collapse = collapse;
    that.val = val;

    that.onchange = function() {};

    if (that.options.empty_elem) {
        that.$first = that.add(that.options.placeholder, 0);
        that.$first.onclick = function() {
            let = elems = that.$elems.slice(1);
            elems.forEach(el => {
                el.toggle();
            });
        };
    }

    document.addEventListener("click", function(e) {
        if (e.target != that.$first) {
            that.collapse();
        }
    });

    return that;
};


