jQuery(function(){initSmoothScroll();initCarousel();initOpenClose();initCustomForms();initMobileNav();initTouchNav();initRetinaCover();initAccordion();initAccordionStudioFinder();initRteJsFuncs();initPovermailValidation();initFixHeaderImg();initFranchise();initStickyHeader();initWorkTimeFormPart();initCouponPreferenceOrder();initCoronaBanner();initContractSummary()});function overEighteen(birthday,html5){var arr,day,month,year;if(html5==!0){arr=birthday.split('-');(day=arr[2]),(month=arr[1]),(year=arr[0]),(age=18)}else{arr=birthday.split('.');(day=arr[0]),(month=arr[1]),(year=arr[2]),(age=18)}
if(year<1000){return!1}
var givenDate=new Date();givenDate.setFullYear(year,month-1,day);var currDate=new Date();currDate.setFullYear(currDate.getFullYear()-age);return currDate-givenDate>0}
function initPovermailValidation(){window.Parsley.addValidator('custom100',function(value,requirement){var reg=new RegExp(requirement);if(reg.test(value)){return overEighteen(value,!0)}else{var regb=new RegExp(/^(0?[1-9]|[12][0-9]|3[01])[\.](0?[1-9]|1[012])[\.]\d{4}$/);if(regb.test(value)){return overEighteen(value,!1)}}
return!1},32).addMessage('de','custom100','Error')}
function initRteJsFuncs(){/** Clear cookies **/
  var delete_cookie = function (name) {
    document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT; Path=/;';
  };
  if (jQuery('a.js-clear-cookie').length) {
    jQuery('a.js-clear-cookie').click(function (event) {
      event.preventDefault();
      delete_cookie('allowCookie');

      Cookies.set('disallowCookies', true, {
        expires: 30,
        domain: '',
      });

      alert('Facebook Konversionsmessung Einwilligung erfolgreich widerrufen.');
    });
  }
}

function initFranchise() {
  if ($('.onepager__franchise').length) {
    $('.module__divider').each(function () {
      var id = this.id;
      var text = $(this).find('span').text();
      $('ul.main-nav').append(
        '<li><a class="opener" href="#' + id + '">' + text + '</a></li>'
      );
    });

    $('.onepager__franchise ul.main-nav li a').on('click', function (e) {
      e.preventDefault();
      var anchor = $(this).attr('href');
      $('html,body').animate({ scrollTop: $(anchor).offset().top }, 'slow');
    });

    $('.onepager__franchise a.btn-info').on('click', function (e) {
      e.preventDefault();
      var anchor = $(this).attr('href');
      $('html,body').animate({ scrollTop: $(anchor).offset().top }, 'slow');
    });
  }
  return false;
}

function initStickyBlock() {
  var win = jQuery(window);

  jQuery('.fixed-block-holder').each(function () {
    var holder = jQuery(this),
      activeClass = 'fixed-position',
      fixedBlock = holder.find('.taming-section');

    function toggleState() {
      if (win.scrollTop() >= holder.offset().top) {
        holder.css('height', fixedBlock.outerHeight());
        fixedBlock.addClass(activeClass);
      } else {
        holder.css('height', '');
        fixedBlock.removeClass(activeClass);
      }
    }

    toggleState();

    win.on('scroll resize orientationchange', toggleState);
  });
}

function initStickyHeader() {
  // When the user scrolls the page, execute myFunction
  window.onscroll = function () {
    stickyHeaderFunction();
  };

  // Get the header
  var header = document.getElementById('header');

  // Get the offset position of the navbar
  var sticky = header.offsetTop;

  window.onresize = function () {
    if (window.pageYOffset == 0) {
      sticky = header.offsetTop;
    }
  };

  // Add the sticky class to the header when you reach its scroll position. Remove "sticky" when you leave the scroll position
  function stickyHeaderFunction() {
    if (window.pageYOffset > sticky) {
      header.classList.add('sticky');
    } else {
      header.classList.remove('sticky');
    }
  }

  stickyHeaderFunction();
}

// scroll gallery init
function initCarousel() {
  jQuery('.slider-banner').scrollGallery({
    mask: '.mask',
    slider: '.slideset',
    slides: '.slide-banner',
    maskAutoSize: true,
    autoRotation: true,
    step: 'number',
    switchTime: 4000,
  });

  jQuery('.carousel-products:not(.testimonial)').scrollGallery({
    mask: '.mask',
    slider: '.slideset',
    slides: '.slide-product',
    maskAutoSize: true,
    autoRotation: true,
  });

  ResponsiveHelper.addRange({
    '..767': {
      on: function () {
        jQuery('.testimonial').scrollGallery({
          mask: '.mask',
          slider: '.slideset',
          slides: '.slide-product',
          autoRotation: false,
          stretchSlideToMask: true,
        });
      },
    },
    '768..': {
      on: function () {
        jQuery('.testimonial').scrollGallery({
          mask: '.mask',
          slider: '.slideset',
          slides: '.slide-product',
          autoRotation: false,
          maskAutoSize: true,
          step: 1,
        });
      },
    },
  });

  if (jQuery('.carousel-products:not(.testimonial)').length >= 1) {
    jQuery('.carousel-products:not(.testimonial) .slide-product img')
      .removeAttr('width')
      .removeAttr('height');
  }
}

// accordion menu init
function initAccordion() {
  jQuery('.accordion').slideAccordion({
    opener: '.panel-heading',
    slider: '.panel-body',
    animSpeed: 300,
  });
}

function initAccordionStudioFinder() {
  jQuery('.filter-results').each(function () {
    var holder = jQuery(this),
      scrollHolder = holder.find('.scroll-holder'),
      accordion = holder.find('.filter-accordion'),
      initialMapHolder = holder.find('.map-col'),
      isDesktopLayout = false;

    accordion.slideAccordion({
      opener: '.opener',
      slider: '.slide',
      animSpeed: 300,
    });
  });
}

// open-close init
function initOpenClose() {
  jQuery('.filter-open-close').openClose({
    activeClass: 'active',
    opener: '.opener',
    slider: '.slide',
    animSpeed: 400,
    effect: 'slide',
  });
}

// initialize custom form elements
function initCustomForms() {
  jcf.setOptions('Select', {
    wrapNative: false,
    wrapNativeOnMobile: false,
  });
  jcf.replaceAll();
}

// mobile menu init
function initMobileNav() {
  jQuery('body').mobileNav({
    menuActiveClass: 'nav-active',
    menuOpener: '.nav-opener',
    hideOnClickOutside: true,
    menuDrop: '.nav-drop',
  });
}

function initSmoothScroll() {
  if(window.location.hash) {
    disableScroll();
    anchor = document.querySelector(window.location.hash);
    scrollToAnchor(anchor);
    window.onscroll = function() {};
  }  

  jQuery('a[href^="#"]').on("click", function(event) { 
    event.preventDefault(); 

    selector = $(this).attr("href");

    if(selector.length > 1){
      anchor = document.querySelector(selector);
      window.onscroll = function() {};
      scrollToAnchor(anchor);
    } else if($(this).hasClass("scroll-link")){
      scrollToAnchor(document.querySelector("body"));
    }
  });
}

function scrollToAnchor(anchor) {
  var scroll = new SmoothScroll();

  scroll.animateScroll(anchor, 1, {
    speed: 700,
    speedAsDuration: true,
    header: "#header"
  }); 

}

function disableScroll() {
  scrollTop = window.pageYOffset || document.documentElement.scrollTop;
  scrollLeft = window.pageXOffset || document.documentElement.scrollLeft,
  window.onscroll = function() {
    window.scrollTo(scrollLeft, scrollTop);
  };
}

function disableScroll() {
  scrollTop = window.pageYOffset || document.documentElement.scrollTop;
  scrollLeft = window.pageXOffset || document.documentElement.scrollLeft,
  window.onscroll = function() {
    window.scrollTo(scrollLeft, scrollTop);
  };
}


// handle dropdowns on mobile devices
function initTouchNav() {
  var nav = jQuery('.slide-nav'),
    page = jQuery('body'),
    dropOpenedClass = 'nav-drop-visible',
    isTouchDevice =
      /Windows Phone/.test(navigator.userAgent) ||
      'ontouchstart' in window ||
      (window.DocumentTouch && document instanceof DocumentTouch);

  function initNavAccordion() {
    nav.slideAccordion({
      opener: '>a.opener',
      slider: '>div.drop',
      collapsible: true,
      animSpeed: 300,
      allowClickWhenExpanded: true,
      activeClass: 'drop-active',
      event: 'click',
    });
  }

  function destroyNavAccordion() {
    nav.each(function () {
      var navAPI = jQuery(this).data('SlideAccordion');

      if (navAPI) {
        navAPI.destroy();
      }
    });
  }

  function initTouchNav() {
    nav.each(function () {
      jQuery(this).data(
        'TouchNav',
        new TouchNav({
          navBlock: this,
          menuDrop: '.drop',
        })
      );
    });
    jQuery(nav)
      .find('>li:has(.drop)')
      .on(isTouchDevice ? 'itemhover' : 'mouseenter', function () {
        page.addClass(dropOpenedClass);
      })
      .on(isTouchDevice ? 'itemleave' : 'mouseleave', function () {
        page.removeClass(dropOpenedClass);
      });
  }

  function destroyTouchNav() {
    nav.each(function () {
      var inst = jQuery(this).data('TouchNav');
      if (inst) {
        inst.destroy();
      }
    });
  }

  // handle layout resize
  ResponsiveHelper.addRange({
    '..991': {
      on: function () {
        initNavAccordion();
      },
      off: function () {
        destroyNavAccordion();
      },
    },
    '992..': {
      on: function () {
        initTouchNav();
      },
      off: function () {
        destroyTouchNav();
        page.removeClass(dropOpenedClass);
      },
    },
  });
}

function initRetinaCover() {
  jQuery('.bg-stretch').retinaCover();
}

function initFixHeaderImg() {
  var headerSection = jQuery('.main-top .intro-section');
  if (headerSection.length >= 1) {
    headerSection
      .find('.image-box img')
      .removeAttr('width')
      .removeAttr('height');
  }
}

function initWorkTimeFormPart() {
  // init
  if (jQuery('.powermail_radio.applicability-individual').is(':checked')) {
    jQuery('.worktimes').removeClass('hidden');
  } else {
    jQuery('.worktimes').addClass('hidden');
  }
  jQuery('.worktimes .singleday input.wholedayfield').each(function () {
    parttimeInputs = jQuery(this)
      .parent()
      .parent()
      .parent()
      .find('.parttimes input');
    parttimeInputs.prop('disabled', false);

    if (jQuery(this).is(':checked')) {
      parttimeInputs.prop('checked', null);
      parttimeInputs.prop('disabled', true);
    } else {
      parttimeInputs.prop('disabled', false);
    }
    jcf.refreshAll();
  });
  jQuery('.worktimes .singleday input.powermail_checkbox').each(function () {
    daylabelEl = jQuery(this).closest('.singleday');
    if (
      jQuery(this)
        .closest('.singleday')
        .find('input.powermail_checkbox:checked').length > 0
    ) {
      daylabelEl.addClass('highlighted');
    } else {
      daylabelEl.removeClass('highlighted');
    }
  });

  // events
  jQuery('input.applicability-individual, input.applicability-flexible').on(
    'change',
    function () {
      if (
        typeof jQuery('input.applicability-individual:checked').val() !==
        'undefined'
      ) {
        jQuery('.worktimes').removeClass('hidden');
      } else {
        jQuery('.worktimes').addClass('hidden');
      }
    }
  );

  jQuery('.worktimes .singleday input.wholedayfield').on('change', function () {
    parttimeInputs = jQuery(this)
      .parent()
      .parent()
      .parent()
      .find('.parttimes input');
    parttimeInputs.prop('disabled', false);

    if (jQuery(this).is(':checked')) {
      parttimeInputs.prop('checked', null);
      parttimeInputs.prop('disabled', true);
    } else {
      parttimeInputs.prop('disabled', false);
    }
    jcf.refreshAll();
  });

  jQuery('.worktimes .singleday input.powermail_checkbox').on(
    'change',
    function () {
      daylabelEl = jQuery(this).closest('.singleday');
      if (
        jQuery(this)
          .closest('.singleday')
          .find('input.powermail_checkbox:checked').length > 0
      ) {
        daylabelEl.addClass('highlighted');
      } else {
        daylabelEl.removeClass('highlighted');
      }
      if (
        jQuery(this)
          .closest('.singleday')
          .find('input.powermail_checkbox:checked').length == 3
      ) {
        daylabelEl.find('.switch input.wholedayfield').click();
      }
    }
  );
}

function initCouponPreferenceOrder() {
  if ($('#coupon_preference').length) {
    // set a coupon as preferred if it fits to page
    Cookies.set(
      'couponpreference',
      $('#coupon_preference').data('couponprefuid'),
      {
        expires: 7,
        domain: '',
      }
    );
  } else {
    if ($('.coupons-wrapper').length) {
      // get preferred coupon based on previously visited page
      var preferCouponUid = Cookies.get('couponpreference');

      if (preferCouponUid && preferCouponUid != null) {
        // move preferred coupon to top
        var couponElementToPrefer = $(
          '.product-box.coupon[data-couponuid=' +
            preferCouponUid.toString() +
            ']'
        ).parent();
        $(
          '.product-box.coupon[data-couponuid=' +
            preferCouponUid.toString() +
            ']'
        )
          .parent()
          .remove();
        $('.coupons-wrapper .boxes-row').prepend(couponElementToPrefer);
      }
    }
  }
}

function initCoronaBanner() {
  jQuery('#corona-banner-close').on('click', function (e) {
    e.preventDefault();

    jQuery('.corona-banner').fadeOut();
  });
}

function initContractSummary() {
  // handle layout resize
  ResponsiveHelper.addRange({
    '..767': {
      on: function () {
        jQuery('details').attr('open', false);
      },
      off: function () {
        jQuery('details').attr('open', true);
      },
    },
  });
}

/*
 * jQuery Carousel plugin
 */
(function ($) {
  'use strict';
  // detect device type
  var isTouchDevice =
    /Windows Phone/.test(navigator.userAgent) ||
    'ontouchstart' in window ||
    (window.DocumentTouch && document instanceof DocumentTouch);

  function ScrollGallery(options) {
    this.options = $.extend(
      {
        mask: 'div.mask',
        slider: '>*',
        slides: '>*',
        activeClass: 'active',
        disabledClass: 'disabled',
        btnPrev: 'a.btn-prev',
        btnNext: 'a.btn-next',
        generatePagination: false,
        pagerList: '<ul>',
        pagerListItem: '<li><a href="#"></a></li>',
        pagerListItemText: 'a',
        pagerLinks: '.pagination li',
        currentNumber: 'span.current-num',
        totalNumber: 'span.total-num',
        btnPlay: '.btn-play',
        btnPause: '.btn-pause',
        btnPlayPause: '.btn-play-pause',
        galleryReadyClass: 'gallery-js-ready',
        autorotationActiveClass: 'autorotation-active',
        autorotationDisabledClass: 'autorotation-disabled',
        stretchSlideToMask: false,
        circularRotation: true,
        disableWhileAnimating: false,
        autoRotation: false,
        pauseOnHover: isTouchDevice ? false : true,
        maskAutoSize: false,
        switchTime: 4000,
        animSpeed: 600,
        event: 'click',
        swipeThreshold: 15,
        handleTouch: true,
        vertical: false,
        useTranslate3D: false,
        step: false,
      },
      options
    );
    this.init();
  }

  ScrollGallery.prototype = {
    init: function () {
      if (this.options.holder) {
        this.findElements();
        this.attachEvents();
        this.refreshPosition();
        this.refreshState(true);
        this.resumeRotation();
        this.makeCallback('onInit', this);
      }
    },
    findElements: function () {
      // define dimensions proporties
      this.fullSizeFunction = this.options.vertical
        ? 'outerHeight'
        : 'outerWidth';
      this.innerSizeFunction = this.options.vertical ? 'height' : 'width';
      this.slideSizeFunction = 'outerHeight';
      this.maskSizeProperty = 'height';
      this.animProperty = this.options.vertical ? 'marginTop' : 'marginLeft';

      // control elements
      this.gallery = $(this.options.holder).addClass(
        this.options.galleryReadyClass
      );
      this.mask = this.gallery.find(this.options.mask);
      this.slider = this.mask.find(this.options.slider);
      this.slides = this.slider.find(this.options.slides);
      this.btnPrev = this.gallery.find(this.options.btnPrev);
      this.btnNext = this.gallery.find(this.options.btnNext);
      this.currentStep = 0;
      this.stepsCount = 0;

      // get start index
      if (this.options.step === false) {
        var activeSlide = this.slides.filter('.' + this.options.activeClass);
        if (activeSlide.length) {
          this.currentStep = this.slides.index(activeSlide);
        }
      }

      // calculate offsets
      this.calculateOffsets();

      // create gallery pagination
      if (typeof this.options.generatePagination === 'string') {
        this.pagerLinks = $();
        this.buildPagination();
      } else {
        this.pagerLinks = this.gallery.find(this.options.pagerLinks);
        this.attachPaginationEvents();
      }

      // autorotation control buttons
      this.btnPlay = this.gallery.find(this.options.btnPlay);
      this.btnPause = this.gallery.find(this.options.btnPause);
      this.btnPlayPause = this.gallery.find(this.options.btnPlayPause);

      // misc elements
      this.curNum = this.gallery.find(this.options.currentNumber);
      this.allNum = this.gallery.find(this.options.totalNumber);
      this.isInit = true;
    },
    attachEvents: function () {
      // bind handlers scope
      var self = this;
      this.bindHandlers(['onWindowResize']);
      $(window).bind('load resize orientationchange', this.onWindowResize);

      // previous and next button handlers
      if (this.btnPrev.length) {
        this.prevSlideHandler = function (e) {
          e.preventDefault();
          self.prevSlide();
        };
        this.btnPrev.bind(this.options.event, this.prevSlideHandler);
      }
      if (this.btnNext.length) {
        this.nextSlideHandler = function (e) {
          e.preventDefault();
          self.nextSlide();
        };
        this.btnNext.bind(this.options.event, this.nextSlideHandler);
      }

      // pause on hover handling
      if (this.options.pauseOnHover && !isTouchDevice) {
        this.hoverHandler = function () {
          if (self.options.autoRotation) {
            self.galleryHover = true;
            self.pauseRotation();
          }
        };
        this.leaveHandler = function () {
          if (self.options.autoRotation) {
            self.galleryHover = false;
            self.resumeRotation();
          }
        };
        this.gallery.bind({
          mouseenter: this.hoverHandler,
          mouseleave: this.leaveHandler,
        });
      }

      // autorotation buttons handler
      if (this.btnPlay.length) {
        this.btnPlayHandler = function (e) {
          e.preventDefault();
          self.startRotation();
        };
        this.btnPlay.bind(this.options.event, this.btnPlayHandler);
      }
      if (this.btnPause.length) {
        this.btnPauseHandler = function (e) {
          e.preventDefault();
          self.stopRotation();
        };
        this.btnPause.bind(this.options.event, this.btnPauseHandler);
      }
      if (this.btnPlayPause.length) {
        this.btnPlayPauseHandler = function (e) {
          e.preventDefault();
          if (!self.gallery.hasClass(self.options.autorotationActiveClass)) {
            self.startRotation();
          } else {
            self.stopRotation();
          }
        };
        this.btnPlayPause.bind(this.options.event, this.btnPlayPauseHandler);
      }

      // enable hardware acceleration
      if (isTouchDevice && this.options.useTranslate3D) {
        this.slider.css({
          '-webkit-transform': 'translate3d(0px, 0px, 0px)',
        });
      }

      // swipe event handling
      if (
        isTouchDevice &&
        this.options.handleTouch &&
        window.Hammer &&
        this.mask.length
      ) {
        this.swipeHandler = new Hammer.Manager(this.mask[0]);
        this.swipeHandler.add(
          new Hammer.Pan({
            direction: self.options.vertical
              ? Hammer.DIRECTION_VERTICAL
              : Hammer.DIRECTION_HORIZONTAL,
            threshold: self.options.swipeThreshold,
          })
        );

        this.swipeHandler
          .on('panstart', function () {
            if (self.galleryAnimating) {
              self.swipeHandler.stop();
            } else {
              self.pauseRotation();

              self.originalOffset = parseFloat(
                self.slider.css(self.animProperty)
              );
            }
          })
          .on('panmove', function (e) {
            var tmpOffset =
              self.originalOffset +
              e[self.options.vertical ? 'deltaY' : 'deltaX'];
            tmpOffset = Math.max(Math.min(0, tmpOffset), self.maxOffset);

            self.slider.css(self.animProperty, tmpOffset);
          })
          .on('panend', function (e) {
            self.resumeRotation();
            if (e.distance > self.options.swipeThreshold) {
              if (
                e.offsetDirection === Hammer.DIRECTION_RIGHT ||
                e.offsetDirection === Hammer.DIRECTION_DOWN
              ) {
                self.prevSlide();
              } else {
                self.nextSlide();
              }
            } else {
              self.switchSlide();
            }
          });
      }
    },
    onWindowResize: function () {
      if (!this.isInit) return;
      if (!this.galleryAnimating) {
        this.calculateOffsets();
        this.refreshPosition();
        this.buildPagination();
        this.refreshState();
        this.resizeQueue = false;
      } else {
        this.resizeQueue = true;
      }
    },
    refreshPosition: function () {
      this.currentStep = Math.min(this.currentStep, this.stepsCount - 1);
      this.tmpProps = {};
      this.tmpProps[this.animProperty] = this.getStepOffset();

      this.slider.stop().css(this.tmpProps);
    },
    calculateOffsets: function () {
      var self = this,
        tmpOffset,
        tmpStep;
      if (this.options.stretchSlideToMask) {
        var tmpObj = {};
        tmpObj[this.innerSizeFunction] = this.mask[this.innerSizeFunction]();
        this.slides.css(tmpObj);
      }

      this.maskSize = this.mask[this.innerSizeFunction]();
      this.sumSize = this.getSumSize();

      this.maxOffset = this.maskSize - this.sumSize;

      // vertical gallery with single size step custom behavior
      if (this.options.vertical && this.options.maskAutoSize) {
        this.options.step = 1;
        this.stepsCount = this.slides.length;
        this.stepOffsets = [0];
        tmpOffset = 0;
        for (var i = 0; i < this.slides.length; i++) {
          tmpOffset -= $(this.slides[i])[this.fullSizeFunction](true);
          this.stepOffsets.push(tmpOffset);
        }
        this.maxOffset = tmpOffset;
        return;
      }

      // scroll by slide size
      if (typeof this.options.step === 'number' && this.options.step > 0) {
        this.slideDimensions = [];
        this.slides.each(
          $.proxy(function (ind, obj) {
            self.slideDimensions.push($(obj)[self.fullSizeFunction](true));
          }, this)
        );

        // calculate steps count
        this.stepOffsets = [0];
        this.stepsCount = 1;
        tmpOffset = tmpStep = 0;
        while (tmpOffset > this.maxOffset) {
          tmpOffset -= this.getSlideSize(tmpStep, tmpStep + this.options.step);
          tmpStep += this.options.step;
          this.stepOffsets.push(Math.max(tmpOffset, this.maxOffset));
          this.stepsCount++;
        }
      }
      // scroll by mask size
      else {
        // define step size
        this.stepSize = this.maskSize;

        // calculate steps count
        this.stepsCount = 1;
        tmpOffset = 0;
        while (tmpOffset > this.maxOffset) {
          tmpOffset -= this.stepSize;
          this.stepsCount++;
        }
      }
    },
    getSumSize: function () {
      var sum = 0;
      this.slides.each(
        $.proxy(function (ind, obj) {
          sum += $(obj)[this.fullSizeFunction](true);
        }, this)
      );

      this.slider.css(this.innerSizeFunction, sum);
      return sum;
    },
    getStepOffset: function (step) {
      step = step || this.currentStep;

      if (typeof this.options.step === 'number') {
        return this.stepOffsets[this.currentStep];
      } else {
        return Math.min(
          0,
          Math.max(-this.currentStep * this.stepSize, this.maxOffset)
        );
      }
    },
    getSlideSize: function (i1, i2) {
      var sum = 0;
      for (var i = i1; i < Math.min(i2, this.slideDimensions.length); i++) {
        sum += this.slideDimensions[i];
      }
      return sum;
    },
    buildPagination: function () {
      if (typeof this.options.generatePagination === 'string') {
        if (!this.pagerHolder) {
          this.pagerHolder = this.gallery.find(this.options.generatePagination);
        }
        if (this.pagerHolder.length && this.oldStepsCount != this.stepsCount) {
          this.oldStepsCount = this.stepsCount;
          this.pagerHolder.empty();
          this.pagerList = $(this.options.pagerList).appendTo(this.pagerHolder);
          for (var i = 0; i < this.stepsCount; i++) {
            $(this.options.pagerListItem)
              .appendTo(this.pagerList)
              .find(this.options.pagerListItemText)
              .text(i + 1);
          }
          this.pagerLinks = this.pagerList.children();
          this.attachPaginationEvents();
        }
      }
    },
    attachPaginationEvents: function () {
      var self = this;
      this.pagerLinksHandler = function (e) {
        e.preventDefault();
        self.numSlide(self.pagerLinks.index(e.currentTarget));
      };
      this.pagerLinks.bind(this.options.event, this.pagerLinksHandler);
    },
    prevSlide: function () {
      if (!(this.options.disableWhileAnimating && this.galleryAnimating)) {
        if (this.currentStep > 0) {
          this.currentStep--;
          this.switchSlide();
        } else if (this.options.circularRotation) {
          this.currentStep = this.stepsCount - 1;
          this.switchSlide();
        }
      }
    },
    nextSlide: function (fromAutoRotation) {
      if (!(this.options.disableWhileAnimating && this.galleryAnimating)) {
        if (this.currentStep < this.stepsCount - 1) {
          this.currentStep++;
          this.switchSlide();
        } else if (this.options.circularRotation || fromAutoRotation === true) {
          this.currentStep = 0;
          this.switchSlide();
        }
      }
    },
    numSlide: function (c) {
      if (this.currentStep != c) {
        this.currentStep = c;
        this.switchSlide();
      }
    },
    switchSlide: function () {
      var self = this;
      this.galleryAnimating = true;
      this.tmpProps = {};
      this.tmpProps[this.animProperty] = this.getStepOffset();

      this.slider.stop().animate(this.tmpProps, {
        duration: this.options.animSpeed,
        complete: function () {
          // animation complete
          self.galleryAnimating = false;
          if (self.resizeQueue) {
            self.onWindowResize();
          }

          // onchange callback
          self.makeCallback('onChange', self);
          self.autoRotate();
        },
      });
      this.refreshState();

      // onchange callback
      this.makeCallback('onBeforeChange', this);
    },
    refreshState: function (initial) {
      if (this.options.step === 1 || this.stepsCount === this.slides.length) {
        this.slides
          .removeClass(this.options.activeClass)
          .eq(this.currentStep)
          .addClass(this.options.activeClass);
      }
      this.pagerLinks
        .removeClass(this.options.activeClass)
        .eq(this.currentStep)
        .addClass(this.options.activeClass);
      this.curNum.html(this.currentStep + 1);
      this.allNum.html(this.stepsCount);

      // initial refresh
      if (this.options.maskAutoSize && typeof this.options.step === 'number') {
        this.tmpProps = {};
        this.tmpProps[this.maskSizeProperty] = this.slides
          .eq(Math.min(this.currentStep, this.slides.length - 1))
          [this.slideSizeFunction](true);
        this.mask.stop()[initial ? 'css' : 'animate'](this.tmpProps);
      }

      // disabled state
      if (!this.options.circularRotation) {
        this.btnPrev.add(this.btnNext).removeClass(this.options.disabledClass);
        if (this.currentStep === 0)
          this.btnPrev.addClass(this.options.disabledClass);
        if (this.currentStep === this.stepsCount - 1)
          this.btnNext.addClass(this.options.disabledClass);
      }

      // add class if not enough slides
      this.gallery.toggleClass(
        'not-enough-slides',
        this.sumSize <= this.maskSize
      );
    },
    startRotation: function () {
      this.options.autoRotation = true;
      this.galleryHover = false;
      this.autoRotationStopped = false;
      this.resumeRotation();
    },
    stopRotation: function () {
      this.galleryHover = true;
      this.autoRotationStopped = true;
      this.pauseRotation();
    },
    pauseRotation: function () {
      this.gallery.addClass(this.options.autorotationDisabledClass);
      this.gallery.removeClass(this.options.autorotationActiveClass);
      clearTimeout(this.timer);
    },
    resumeRotation: function () {
      if (!this.autoRotationStopped) {
        this.gallery.addClass(this.options.autorotationActiveClass);
        this.gallery.removeClass(this.options.autorotationDisabledClass);
        this.autoRotate();
      }
    },
    autoRotate: function () {
      var self = this;
      clearTimeout(this.timer);
      if (
        this.options.autoRotation &&
        !this.galleryHover &&
        !this.autoRotationStopped
      ) {
        this.timer = setTimeout(function () {
          self.nextSlide(true);
        }, this.options.switchTime);
      } else {
        this.pauseRotation();
      }
    },
    bindHandlers: function (handlersList) {
      var self = this;
      $.each(handlersList, function (index, handler) {
        var origHandler = self[handler];
        self[handler] = function () {
          return origHandler.apply(self, arguments);
        };
      });
    },
    makeCallback: function (name) {
      if (typeof this.options[name] === 'function') {
        var args = Array.prototype.slice.call(arguments);
        args.shift();
        this.options[name].apply(this, args);
      }
    },
    destroy: function () {
      // destroy handler
      this.isInit = false;
      $(window).unbind('load resize orientationchange', this.onWindowResize);
      this.btnPrev.unbind(this.options.event, this.prevSlideHandler);
      this.btnNext.unbind(this.options.event, this.nextSlideHandler);
      this.pagerLinks.unbind(this.options.event, this.pagerLinksHandler);
      this.gallery.unbind('mouseenter', this.hoverHandler);
      this.gallery.unbind('mouseleave', this.leaveHandler);

      // autorotation buttons handlers
      this.stopRotation();
      this.btnPlay.unbind(this.options.event, this.btnPlayHandler);
      this.btnPause.unbind(this.options.event, this.btnPauseHandler);
      this.btnPlayPause.unbind(this.options.event, this.btnPlayPauseHandler);

      // destroy swipe handler
      if (this.swipeHandler) {
        this.swipeHandler.destroy();
      }

      // remove inline styles, classes and pagination
      var unneededClasses = [
        this.options.galleryReadyClass,
        this.options.autorotationActiveClass,
        this.options.autorotationDisabledClass,
      ];
      this.gallery
        .removeClass(unneededClasses.join(' '))
        .removeData('ScrollGallery');
      this.slider.add(this.slides).add(this.mask).removeAttr('style');
      this.slides.removeClass(this.options.activeClass);
      if (typeof this.options.generatePagination === 'string') {
        this.pagerHolder.empty();
      }
    },
  };

  // jquery plugin
  $.fn.scrollGallery = function (opt) {
    var args = Array.prototype.slice.call(arguments);
    var method = args[0];

    return this.each(function () {
      var $holder = jQuery(this);
      var instance = $holder.data('ScrollGallery');

      if (typeof opt === 'object' || typeof opt === 'undefined') {
        $holder.data(
          'ScrollGallery',
          new ScrollGallery(
            $.extend(
              {
                holder: this,
              },
              opt
            )
          )
        );
      } else if (typeof method === 'string' && instance) {
        if (typeof instance[method] === 'function') {
          args.shift();
          instance[method].apply(instance, args);
        }
      }
    });
  };
})(jQuery);

/*
 * jQuery Accordion plugin
 */
(function (root, factory) {
  'use strict';
  if (typeof define === 'function' && define.amd) {
    define(['jquery'], factory);
  } else if (typeof exports === 'object') {
    module.exports = factory(require('jquery'));
  } else {
    root.SlideAccordion = factory(jQuery);
  }
})(this, function ($) {
  'use strict';
  var accHiddenClass = 'js-acc-hidden';

  function SlideAccordion(options) {
    this.options = $.extend(
      true,
      {
        allowClickWhenExpanded: false,
        activeClass: 'active',
        opener: '.opener',
        slider: '.slide',
        animSpeed: 300,
        collapsible: true,
        event: 'click',
        scrollToActiveItem: {
          enable: false,
          breakpoint: 767, // max-width
          animSpeed: 600,
          extraOffset: null,
        },
      },
      options
    );
    this.init();
  }

  SlideAccordion.prototype = {
    init: function () {
      if (this.options.holder) {
        this.findElements();
        this.setStateOnInit();
        this.attachEvents();
        this.makeCallback('onInit');
      }
    },

    findElements: function () {
      this.$holder = $(this.options.holder).data('SlideAccordion', this);
      this.$items = this.$holder.find(':has(' + this.options.slider + ')');
    },

    setStateOnInit: function () {
      var self = this;

      this.$items.each(function () {
        if (!$(this).hasClass(self.options.activeClass)) {
          $(this).find(self.options.slider).addClass(accHiddenClass);
        }
      });
    },

    attachEvents: function () {
      var self = this;

      this.accordionToggle = function (e) {
        var $item = jQuery(this).closest(self.$items);
        var $actiItem = self.getActiveItem($item);
        if (
          !self.options.allowClickWhenExpanded ||
          !$item.hasClass(self.options.activeClass) ||
          $(e.target).hasClass('icon-opener')
        ) {
          e.preventDefault();
          self.toggle($item, $actiItem);
        }
      };

      this.$items.on(
        this.options.event,
        this.options.opener,
        this.accordionToggle
      );
    },

    toggle: function ($item, $prevItem) {
      if (!$item.hasClass(this.options.activeClass)) {
        this.show($item);
      } else if (this.options.collapsible) {
        this.hide($item, true);
      }

      if (!$item.is($prevItem) && $prevItem.length) {
        this.hide($prevItem);
      }

      this.makeCallback('beforeToggle');
    },

    show: function ($item) {
      var $slider = $item.find(this.options.slider);

      $item.addClass(this.options.activeClass);
      $slider
        .stop()
        .hide()
        .removeClass('hidden')
        .removeClass(accHiddenClass)
        .slideDown({
          duration: this.options.animSpeed,
          complete: function () {
            $slider.removeAttr('style');
            if (
              this.options.scrollToActiveItem.enable &&
              window.innerWidth <= this.options.scrollToActiveItem.breakpoint
            ) {
              this.goToItem($item);
            }
            this.makeCallback('onShow', $item);
          }.bind(this),
        });

      this.makeCallback('beforeShow', $item);
    },

    hide: function ($item, flag) {
      var $slider = $item.find(this.options.slider);

      $item.removeClass(this.options.activeClass);
      $slider
        .stop()
        .show()
        .slideUp({
          duration: this.options.animSpeed,
          complete: function () {
            $slider.addClass(accHiddenClass);
            $slider.removeAttr('style');
            this.makeCallback('onHide', $item);
            if (flag) {
              this.makeCallback('onItemToggle', $item);
            }
          }.bind(this),
        });

      this.makeCallback('beforeHide', $item);
    },

    goToItem: function ($item) {
      var itemOffset = $item.offset().top;

      if (itemOffset < $(window).scrollTop()) {
        // handle extra offset
        if (typeof this.options.scrollToActiveItem.extraOffset === 'number') {
          itemOffset -= this.options.scrollToActiveItem.extraOffset;
        } else if (
          typeof this.options.scrollToActiveItem.extraOffset === 'function'
        ) {
          itemOffset -= this.options.scrollToActiveItem.extraOffset();
        }

        $('body, html').animate(
          {
            scrollTop: itemOffset,
          },
          this.options.scrollToActiveItem.animSpeed
        );
      }
    },

    getActiveItem: function ($item) {
      return $item.siblings().filter('.' + this.options.activeClass);
    },

    makeCallback: function (name) {
      if (typeof this.options[name] === 'function') {
        var args = Array.prototype.slice.call(arguments);
        args.shift();
        this.options[name].apply(this, args);
      }
    },

    destroy: function () {
      this.$holder.removeData('SlideAccordion');
      this.$items.off(
        this.options.event,
        this.options.opener,
        this.accordionToggle
      );
      this.$items.removeClass(this.options.activeClass).each(
        function (i, item) {
          $(item)
            .find(this.options.slider)
            .removeAttr('style')
            .removeClass(accHiddenClass);
        }.bind(this)
      );
      this.makeCallback('onDestroy');
    },
  };

  $.fn.slideAccordion = function (opt) {
    var args = Array.prototype.slice.call(arguments);
    var method = args[0];

    return this.each(function () {
      var $holder = jQuery(this);
      var instance = $holder.data('SlideAccordion');

      if (typeof opt === 'object' || typeof opt === 'undefined') {
        new SlideAccordion(
          $.extend(
            true,
            {
              holder: this,
            },
            opt
          )
        );
      } else if (typeof method === 'string' && instance) {
        if (typeof instance[method] === 'function') {
          args.shift();
          instance[method].apply(instance, args);
        }
      }
    });
  };

  (function () {
    var tabStyleSheet = $('<style type="text/css">')[0];
    var tabStyleRule = '.' + accHiddenClass;
    tabStyleRule +=
      '{position:absolute !important;left:-9999px !important;top:-9999px !important;display:block !important; width: 100% !important;}';
    if (tabStyleSheet.styleSheet) {
      tabStyleSheet.styleSheet.cssText = tabStyleRule;
    } else {
      tabStyleSheet.appendChild(document.createTextNode(tabStyleRule));
    }
    $('head').append(tabStyleSheet);
  })();

  return SlideAccordion;
});

/*
 * jQuery Open/Close plugin
 */
(function ($) {
  function OpenClose(options) {
    this.options = $.extend(
      {
        addClassBeforeAnimation: true,
        hideOnClickOutside: false,
        activeClass: 'active',
        opener: '.opener',
        slider: '.slide',
        animSpeed: 400,
        effect: 'fade',
        event: 'click',
      },
      options
    );
    this.init();
  }

  OpenClose.prototype = {
    init: function () {
      if (this.options.holder) {
        this.findElements();
        this.attachEvents();
        this.makeCallback('onInit', this);
      }
    },
    findElements: function () {
      this.holder = $(this.options.holder);
      this.opener = this.holder.find(this.options.opener);
      this.slider = this.holder.find(this.options.slider);
    },
    attachEvents: function () {
      // add handler
      var self = this;
      this.eventHandler = function (e) {
        e.preventDefault();
        if (self.slider.hasClass(slideHiddenClass)) {
          self.showSlide();
        } else {
          self.hideSlide();
        }
      };
      self.opener.on(self.options.event, this.eventHandler);

      // hover mode handler
      if (self.options.event === 'hover') {
        self.opener.on('mouseenter', function () {
          if (!self.holder.hasClass(self.options.activeClass)) {
            self.showSlide();
          }
        });
        self.holder.on('mouseleave', function () {
          self.hideSlide();
        });
      }

      // outside click handler
      self.outsideClickHandler = function (e) {
        if (self.options.hideOnClickOutside) {
          var target = $(e.target);
          if (!target.is(self.holder) && !target.closest(self.holder).length) {
            self.hideSlide();
          }
        }
      };

      // set initial styles
      if (this.holder.hasClass(this.options.activeClass)) {
        $(document).on('click touchstart', self.outsideClickHandler);
      } else {
        this.slider.addClass(slideHiddenClass);
      }
    },
    showSlide: function () {
      var self = this;
      if (self.options.addClassBeforeAnimation) {
        self.holder.addClass(self.options.activeClass);
      }
      self.slider.removeClass(slideHiddenClass);
      $(document).on('click touchstart', self.outsideClickHandler);

      self.makeCallback('animStart', true);
      toggleEffects[self.options.effect].show({
        box: self.slider,
        speed: self.options.animSpeed,
        complete: function () {
          if (!self.options.addClassBeforeAnimation) {
            self.holder.addClass(self.options.activeClass);
          }
          self.makeCallback('animEnd', true);
        },
      });
    },
    hideSlide: function (cb) {
      var self = this;
      if (self.options.addClassBeforeAnimation) {
        self.holder.removeClass(self.options.activeClass);
      }
      $(document).off('click touchstart', self.outsideClickHandler);

      self.makeCallback('animStart', false);
      toggleEffects[self.options.effect].hide({
        box: self.slider,
        speed: self.options.animSpeed,
        complete: function () {
          if (!self.options.addClassBeforeAnimation) {
            self.holder.removeClass(self.options.activeClass);
          }
          self.slider.addClass(slideHiddenClass);
          self.makeCallback('animEnd', false);
          if (typeof cb == 'function') cb();
        },
      });
    },
    destroy: function () {
      this.slider.removeClass(slideHiddenClass).css({
        display: '',
      });
      this.opener.off(this.options.event, this.eventHandler);
      this.holder.removeClass(this.options.activeClass).removeData('OpenClose');
      $(document).off('click touchstart', this.outsideClickHandler);
    },
    makeCallback: function (name) {
      if (typeof this.options[name] === 'function') {
        var args = Array.prototype.slice.call(arguments);
        args.shift();
        this.options[name].apply(this, args);
      }
    },
  };

  // add stylesheet for slide on DOMReady
  var slideHiddenClass = 'js-slide-hidden';
  (function () {
    var tabStyleSheet = $('<style type="text/css">')[0];
    var tabStyleRule = '.' + slideHiddenClass;
    tabStyleRule +=
      '{position:absolute !important;left:-9999px !important;top:-9999px !important;display:block !important}';
    if (tabStyleSheet.styleSheet) {
      tabStyleSheet.styleSheet.cssText = tabStyleRule;
    } else {
      tabStyleSheet.appendChild(document.createTextNode(tabStyleRule));
    }
    $('head').append(tabStyleSheet);
  })();

  // animation effects
  var toggleEffects = {
    slide: {
      show: function (o) {
        o.box.stop(true).hide().slideDown(o.speed, o.complete);
      },
      hide: function (o) {
        o.box.stop(true).slideUp(o.speed, o.complete);
      },
    },
    fade: {
      show: function (o) {
        o.box.stop(true).hide().fadeIn(o.speed, o.complete);
      },
      hide: function (o) {
        o.box.stop(true).fadeOut(o.speed, o.complete);
      },
    },
    none: {
      show: function (o) {
        o.box.hide().show(0, o.complete);
      },
      hide: function (o) {
        o.box.hide(0, o.complete);
      },
    },
  };

  // jQuery plugin interface
  $.fn.openClose = function (opt) {
    var args = Array.prototype.slice.call(arguments);
    var method = args[0];

    return this.each(function () {
      var $holder = jQuery(this);
      var instance = $holder.data('OpenClose');

      if (typeof opt === 'object' || typeof opt === 'undefined') {
        $holder.data(
          'OpenClose',
          new OpenClose(
            $.extend(
              {
                holder: this,
              },
              opt
            )
          )
        );
      } else if (typeof method === 'string' && instance) {
        if (typeof instance[method] === 'function') {
          args.shift();
          instance[method].apply(instance, args);
        }
      }
    });
  };
})(jQuery);

/*
 * Simple Mobile Navigation
 */
(function ($) {
  function MobileNav(options) {
    this.options = $.extend(
      {
        container: null,
        hideOnClickOutside: false,
        menuActiveClass: 'nav-active',
        menuOpener: '.nav-opener',
        menuDrop: '.nav-drop',
        toggleEvent: 'click',
        outsideClickEvent: 'click touchstart pointerdown MSPointerDown',
      },
      options
    );
    this.initStructure();
    this.attachEvents();
  }

  MobileNav.prototype = {
    initStructure: function () {
      this.page = $('html');
      this.container = $(this.options.container);
      this.opener = this.container.find(this.options.menuOpener);
      this.drop = this.container.find(this.options.menuDrop);
    },
    attachEvents: function () {
      var self = this;

      if (activateResizeHandler) {
        activateResizeHandler();
        activateResizeHandler = null;
      }

      this.outsideClickHandler = function (e) {
        if (self.isOpened()) {
          var target = $(e.target);
          if (
            !target.closest(self.opener).length &&
            !target.closest(self.drop).length
          ) {
            self.hide();
          }
        }
      };

      this.openerClickHandler = function (e) {
        e.preventDefault();
        self.toggle();
      };

      this.opener.on(this.options.toggleEvent, this.openerClickHandler);
    },
    isOpened: function () {
      return this.container.hasClass(this.options.menuActiveClass);
    },
    show: function () {
      this.container.addClass(this.options.menuActiveClass);
      if (this.options.hideOnClickOutside) {
        this.page.on(this.options.outsideClickEvent, this.outsideClickHandler);
      }
    },
    hide: function () {
      this.container.removeClass(this.options.menuActiveClass);
      if (this.options.hideOnClickOutside) {
        this.page.off(this.options.outsideClickEvent, this.outsideClickHandler);
      }
    },
    toggle: function () {
      if (this.isOpened()) {
        this.hide();
      } else {
        this.show();
      }
    },
    destroy: function () {
      this.container.removeClass(this.options.menuActiveClass);
      this.opener.off(this.options.toggleEvent, this.clickHandler);
      this.page.off(this.options.outsideClickEvent, this.outsideClickHandler);
    },
  };

  var activateResizeHandler = function () {
    var win = $(window),
      doc = $('html'),
      resizeClass = 'resize-active',
      flag,
      timer;
    var removeClassHandler = function () {
      flag = false;
      doc.removeClass(resizeClass);
    };
    var resizeHandler = function () {
      if (!flag) {
        flag = true;
        doc.addClass(resizeClass);
      }
      clearTimeout(timer);
      timer = setTimeout(removeClassHandler, 500);
    };
    win.on('resize orientationchange', resizeHandler);
  };

  $.fn.mobileNav = function (opt) {
    var args = Array.prototype.slice.call(arguments);
    var method = args[0];

    return this.each(function () {
      var $container = jQuery(this);
      var instance = $container.data('MobileNav');

      if (typeof opt === 'object' || typeof opt === 'undefined') {
        $container.data(
          'MobileNav',
          new MobileNav(
            $.extend(
              {
                container: this,
              },
              opt
            )
          )
        );
      } else if (typeof method === 'string' && instance) {
        if (typeof instance[method] === 'function') {
          args.shift();
          instance[method].apply(instance, args);
        }
      }
    });
  };
})(jQuery);

// navigation accesibility module
function TouchNav(opt) {
  this.options = {
    hoverClass: 'hover',
    menuItems: 'li',
    menuOpener: 'a',
    menuDrop: 'ul',
    navBlock: null,
  };
  for (var p in opt) {
    if (opt.hasOwnProperty(p)) {
      this.options[p] = opt[p];
    }
  }
  this.init();
}

TouchNav.isActiveOn = function (elem) {
  return elem && elem.touchNavActive;
};
TouchNav.prototype = {
  init: function () {
    if (typeof this.options.navBlock === 'string') {
      this.menu = document.getElementById(this.options.navBlock);
    } else if (typeof this.options.navBlock === 'object') {
      this.menu = this.options.navBlock;
    }
    if (this.menu) {
      this.addEvents();
    }
  },
  addEvents: function () {
    // attach event handlers
    var self = this;
    var touchEvent =
      (navigator.pointerEnabled && 'pointerdown') ||
      (navigator.msPointerEnabled && 'MSPointerDown') ||
      (this.isTouchDevice && 'touchstart');
    this.menuItems = lib.queryElementsBySelector(
      this.options.menuItems,
      this.menu
    );

    var initMenuItem = function (item) {
      var currentDrop = lib.queryElementsBySelector(
          self.options.menuDrop,
          item
        )[0],
        currentOpener = lib.queryElementsBySelector(
          self.options.menuOpener,
          item
        )[0];

      // only for touch input devices
      if (
        currentDrop &&
        currentOpener &&
        (self.isTouchDevice || self.isPointerDevice)
      ) {
        lib.event.add(
          currentOpener,
          'click',
          lib.bind(self.clickHandler, self)
        );
        lib.event.add(
          currentOpener,
          'mousedown',
          lib.bind(self.mousedownHandler, self)
        );
        lib.event.add(currentOpener, touchEvent, function (e) {
          if (!self.isTouchPointerEvent(e)) {
            self.preventCurrentClick = false;
            return;
          }
          self.touchFlag = true;
          self.currentItem = item;
          self.currentLink = currentOpener;
          self.pressHandler.apply(self, arguments);
        });
      }
      // for desktop computers and touch devices
      jQuery(item).bind('mouseenter', function () {
        if (!self.touchFlag) {
          self.currentItem = item;
          self.mouseoverHandler();
        }
      });
      jQuery(item).bind('mouseleave', function () {
        if (!self.touchFlag) {
          self.currentItem = item;
          self.mouseoutHandler();
        }
      });
      item.touchNavActive = true;
    };

    // add handlers for all menu items
    for (var i = 0; i < this.menuItems.length; i++) {
      initMenuItem(self.menuItems[i]);
    }

    // hide dropdowns when clicking outside navigation
    if (this.isTouchDevice || this.isPointerDevice) {
      lib.event.add(
        document.documentElement,
        'mousedown',
        lib.bind(this.clickOutsideHandler, this)
      );
      lib.event.add(
        document.documentElement,
        touchEvent,
        lib.bind(this.clickOutsideHandler, this)
      );
    }
  },
  mousedownHandler: function (e) {
    if (this.touchFlag) {
      e.preventDefault();
      this.touchFlag = false;
      this.preventCurrentClick = false;
    }
  },
  mouseoverHandler: function () {
    lib.addClass(this.currentItem, this.options.hoverClass);
    jQuery(this.currentItem).trigger('itemhover');
  },
  mouseoutHandler: function () {
    lib.removeClass(this.currentItem, this.options.hoverClass);
    jQuery(this.currentItem).trigger('itemleave');
  },
  hideActiveDropdown: function () {
    for (var i = 0; i < this.menuItems.length; i++) {
      if (lib.hasClass(this.menuItems[i], this.options.hoverClass)) {
        lib.removeClass(this.menuItems[i], this.options.hoverClass);
        jQuery(this.menuItems[i]).trigger('itemleave');
      }
    }
    this.activeParent = null;
  },
  pressHandler: function (e) {
    if (this.destroyed) return;
    // hide previous drop (if active)
    if (this.currentItem !== this.activeParent) {
      if (
        this.activeParent &&
        this.currentItem.parentNode === this.activeParent.parentNode
      ) {
        lib.removeClass(this.activeParent, this.options.hoverClass);
      } else if (!this.isParent(this.activeParent, this.currentLink)) {
        this.hideActiveDropdown();
      }
    }
    // handle current drop
    this.activeParent = this.currentItem;
    if (lib.hasClass(this.currentItem, this.options.hoverClass)) {
      this.preventCurrentClick = false;
    } else {
      e.preventDefault();
      this.preventCurrentClick = true;
      lib.addClass(this.currentItem, this.options.hoverClass);
      jQuery(this.currentItem).trigger('itemhover');
    }
  },
  clickHandler: function (e) {
    // prevent first click on link
    if (this.preventCurrentClick) {
      e.preventDefault();
    }
  },
  clickOutsideHandler: function (event) {
    var e = event.changedTouches ? event.changedTouches[0] : event;
    if (this.activeParent && !this.isParent(this.menu, e.target)) {
      this.hideActiveDropdown();
      this.touchFlag = false;
    }
  },
  isParent: function (parent, child) {
    while (child.parentNode) {
      if (child.parentNode == parent) {
        return true;
      }
      child = child.parentNode;
    }
    return false;
  },
  isTouchPointerEvent: function (e) {
    return (
      e.type.indexOf('touch') > -1 ||
      (navigator.pointerEnabled && e.pointerType === 'touch') ||
      (navigator.msPointerEnabled && e.pointerType == e.MSPOINTER_TYPE_TOUCH)
    );
  },
  isPointerDevice: (function () {
    return !!(navigator.pointerEnabled || navigator.msPointerEnabled);
  })(),
  isTouchDevice: (function () {
    return !!(
      'ontouchstart' in window ||
      (window.DocumentTouch && document instanceof DocumentTouch)
    );
  })(),
  destroy: function () {
    var self = this;
    this.destroyed = true;
    var touchEvent =
      (navigator.pointerEnabled && 'pointerdown') ||
      (navigator.msPointerEnabled && 'MSPointerDown') ||
      (this.isTouchDevice && 'touchstart');

    function destroyMenuItem(item) {
      var currentDrop = lib.queryElementsBySelector(
          self.options.menuDrop,
          item
        )[0],
        currentOpener = lib.queryElementsBySelector(
          self.options.menuOpener,
          item
        )[0];

      // only for touch input devices
      if (
        currentDrop &&
        currentOpener &&
        (self.isTouchDevice || self.isPointerDevice)
      ) {
        lib.event.remove(
          currentOpener,
          'click',
          lib.bind(self.clickHandler, self)
        );
        lib.event.remove(
          currentOpener,
          'mousedown',
          lib.bind(self.mousedownHandler, self)
        );
        lib.event.remove(currentOpener, touchEvent);
      }
      // for desktop computers and touch devices
      jQuery(item).unbind('mouseenter');
      jQuery(item).unbind('mouseleave');

      item.touchNavActive = false;
    }

    for (var i = 0; i < this.menuItems.length; i++) {
      destroyMenuItem(self.menuItems[i]);
    }
    if (this.isTouchDevice || this.isPointerDevice) {
      lib.event.remove(
        document.documentElement,
        'mousedown',
        lib.bind(this.clickOutsideHandler, this)
      );
      lib.event.remove(
        document.documentElement,
        touchEvent,
        lib.bind(this.clickOutsideHandler, this)
      );
    }
  },
};

/*
 * jQuery retina cover plugin
 */
(function ($) {
  'use strict';

  var styleRules = {};
  var templates = {
    '2x': [
      '(-webkit-min-device-pixel-ratio: 1.5)',
      '(min-resolution: 192dpi)',
      '(min-device-pixel-ratio: 1.5)',
      '(min-resolution: 1.5dppx)',
    ],
    '3x': [
      '(-webkit-min-device-pixel-ratio: 3)',
      '(min-resolution: 384dpi)',
      '(min-device-pixel-ratio: 3)',
      '(min-resolution: 3dppx)',
    ],
  };

  function addSimple(imageSrc, media, id) {
    var style = buildRule(id, imageSrc);

    addRule(media, style);
  }

  function addRetina(imageData, media, id) {
    var currentRules = templates[imageData[1]].slice();
    var patchedRules = currentRules;
    var style = buildRule(id, imageData[0]);

    if (media !== 'default') {
      patchedRules = $.map(currentRules, function (ele, i) {
        return ele + ' and ' + media;
      });
    }

    media = patchedRules.join(',');

    addRule(media, style);
  }

  function buildRule(id, src) {
    return '#' + id + '{background-image: url("' + src + '");}';
  }

  function addRule(media, rule) {
    var $styleTag = styleRules[media];
    var styleTagData;
    var rules = '';

    if (media === 'default') {
      rules = rule + ' ';
    } else {
      rules = '@media ' + media + '{' + rule + '}';
    }

    if (!$styleTag) {
      styleRules[media] = $('<style>').text(rules).appendTo('head');
    } else {
      styleTagData = $styleTag.text();
      styleTagData =
        styleTagData.substring(0, styleTagData.length - 2) + ' }' + rule + '}';
      $styleTag.text(styleTagData);
    }
  }

  $.fn.retinaCover = function () {
    return this.each(function () {
      var $block = $(this);
      var $items = $block.children('[data-srcset]');
      var id = 'bg-stretch' + Date.now() + (Math.random() * 1000).toFixed(0);

      if ($items.length) {
        $block.attr('id', id);

        $items.each(function () {
          var $item = $(this);
          var data = $item.data('srcset').split(', ');
          var media = $item.data('media') || 'default';
          var dataLength = data.length;
          var itemData;
          var i;

          for (i = 0; i < dataLength; i++) {
            itemData = data[i].split(' ');

            if (itemData.length === 1) {
              addSimple(itemData[0], media, id);
            } else {
              addRetina(itemData, media, id);
            }
          }
        });
      }

      $items.detach();
    });
  };
})(jQuery);

/*! Hammer.JS - v2.0.8 - 2016-04-23
 * http://hammerjs.github.io/
 *
 * Copyright (c) 2016 Jorik Tangelder;
 * Licensed under the MIT license */
!(function (a, b, c, d) {
  'use strict';

  function e(a, b, c) {
    return setTimeout(j(a, c), b);
  }

  function f(a, b, c) {
    return Array.isArray(a) ? (g(a, c[b], c), !0) : !1;
  }

  function g(a, b, c) {
    var e;
    if (a)
      if (a.forEach) a.forEach(b, c);
      else if (a.length !== d)
        for (e = 0; e < a.length; ) b.call(c, a[e], e, a), e++;
      else for (e in a) a.hasOwnProperty(e) && b.call(c, a[e], e, a);
  }

  function h(b, c, d) {
    var e = 'DEPRECATED METHOD: ' + c + '\n' + d + ' AT \n';
    return function () {
      var c = new Error('get-stack-trace'),
        d =
          c && c.stack
            ? c.stack
                .replace(/^[^\(]+?[\n$]/gm, '')
                .replace(/^\s+at\s+/gm, '')
                .replace(/^Object.<anonymous>\s*\(/gm, '{anonymous}()@')
            : 'Unknown Stack Trace',
        f = a.console && (a.console.warn || a.console.log);
      return f && f.call(a.console, e, d), b.apply(this, arguments);
    };
  }

  function i(a, b, c) {
    var d,
      e = b.prototype;
    (d = a.prototype = Object.create(e)),
      (d.constructor = a),
      (d._super = e),
      c && la(d, c);
  }

  function j(a, b) {
    return function () {
      return a.apply(b, arguments);
    };
  }

  function k(a, b) {
    return typeof a == oa ? a.apply(b ? b[0] || d : d, b) : a;
  }

  function l(a, b) {
    return a === d ? b : a;
  }

  function m(a, b, c) {
    g(q(b), function (b) {
      a.addEventListener(b, c, !1);
    });
  }

  function n(a, b, c) {
    g(q(b), function (b) {
      a.removeEventListener(b, c, !1);
    });
  }

  function o(a, b) {
    for (; a; ) {
      if (a == b) return !0;
      a = a.parentNode;
    }
    return !1;
  }

  function p(a, b) {
    return a.indexOf(b) > -1;
  }

  function q(a) {
    return a.trim().split(/\s+/g);
  }

  function r(a, b, c) {
    if (a.indexOf && !c) return a.indexOf(b);
    for (var d = 0; d < a.length; ) {
      if ((c && a[d][c] == b) || (!c && a[d] === b)) return d;
      d++;
    }
    return -1;
  }

  function s(a) {
    return Array.prototype.slice.call(a, 0);
  }

  function t(a, b, c) {
    for (var d = [], e = [], f = 0; f < a.length; ) {
      var g = b ? a[f][b] : a[f];
      r(e, g) < 0 && d.push(a[f]), (e[f] = g), f++;
    }
    return (
      c &&
        (d = b
          ? d.sort(function (a, c) {
              return a[b] > c[b];
            })
          : d.sort()),
      d
    );
  }

  function u(a, b) {
    for (
      var c, e, f = b[0].toUpperCase() + b.slice(1), g = 0;
      g < ma.length;

    ) {
      if (((c = ma[g]), (e = c ? c + f : b), e in a)) return e;
      g++;
    }
    return d;
  }

  function v() {
    return ua++;
  }

  function w(b) {
    var c = b.ownerDocument || b;
    return c.defaultView || c.parentWindow || a;
  }

  function x(a, b) {
    var c = this;
    (this.manager = a),
      (this.callback = b),
      (this.element = a.element),
      (this.target = a.options.inputTarget),
      (this.domHandler = function (b) {
        k(a.options.enable, [a]) && c.handler(b);
      }),
      this.init();
  }

  function y(a) {
    var b,
      c = a.options.inputClass;
    return new (b = c ? c : xa ? M : ya ? P : wa ? R : L)(a, z);
  }

  function z(a, b, c) {
    var d = c.pointers.length,
      e = c.changedPointers.length,
      f = b & Ea && d - e === 0,
      g = b & (Ga | Ha) && d - e === 0;
    (c.isFirst = !!f),
      (c.isFinal = !!g),
      f && (a.session = {}),
      (c.eventType = b),
      A(a, c),
      a.emit('hammer.input', c),
      a.recognize(c),
      (a.session.prevInput = c);
  }

  function A(a, b) {
    var c = a.session,
      d = b.pointers,
      e = d.length;
    c.firstInput || (c.firstInput = D(b)),
      e > 1 && !c.firstMultiple
        ? (c.firstMultiple = D(b))
        : 1 === e && (c.firstMultiple = !1);
    var f = c.firstInput,
      g = c.firstMultiple,
      h = g ? g.center : f.center,
      i = (b.center = E(d));
    (b.timeStamp = ra()),
      (b.deltaTime = b.timeStamp - f.timeStamp),
      (b.angle = I(h, i)),
      (b.distance = H(h, i)),
      B(c, b),
      (b.offsetDirection = G(b.deltaX, b.deltaY));
    var j = F(b.deltaTime, b.deltaX, b.deltaY);
    (b.overallVelocityX = j.x),
      (b.overallVelocityY = j.y),
      (b.overallVelocity = qa(j.x) > qa(j.y) ? j.x : j.y),
      (b.scale = g ? K(g.pointers, d) : 1),
      (b.rotation = g ? J(g.pointers, d) : 0),
      (b.maxPointers = c.prevInput
        ? b.pointers.length > c.prevInput.maxPointers
          ? b.pointers.length
          : c.prevInput.maxPointers
        : b.pointers.length),
      C(c, b);
    var k = a.element;
    o(b.srcEvent.target, k) && (k = b.srcEvent.target), (b.target = k);
  }

  function B(a, b) {
    var c = b.center,
      d = a.offsetDelta || {},
      e = a.prevDelta || {},
      f = a.prevInput || {};
    (b.eventType !== Ea && f.eventType !== Ga) ||
      ((e = a.prevDelta =
        {
          x: f.deltaX || 0,
          y: f.deltaY || 0,
        }),
      (d = a.offsetDelta = { x: c.x, y: c.y })),
      (b.deltaX = e.x + (c.x - d.x)),
      (b.deltaY = e.y + (c.y - d.y));
  }

  function C(a, b) {
    var c,
      e,
      f,
      g,
      h = a.lastInterval || b,
      i = b.timeStamp - h.timeStamp;
    if (b.eventType != Ha && (i > Da || h.velocity === d)) {
      var j = b.deltaX - h.deltaX,
        k = b.deltaY - h.deltaY,
        l = F(i, j, k);
      (e = l.x),
        (f = l.y),
        (c = qa(l.x) > qa(l.y) ? l.x : l.y),
        (g = G(j, k)),
        (a.lastInterval = b);
    } else
      (c = h.velocity), (e = h.velocityX), (f = h.velocityY), (g = h.direction);
    (b.velocity = c), (b.velocityX = e), (b.velocityY = f), (b.direction = g);
  }

  function D(a) {
    for (var b = [], c = 0; c < a.pointers.length; )
      (b[c] = {
        clientX: pa(a.pointers[c].clientX),
        clientY: pa(a.pointers[c].clientY),
      }),
        c++;
    return {
      timeStamp: ra(),
      pointers: b,
      center: E(b),
      deltaX: a.deltaX,
      deltaY: a.deltaY,
    };
  }

  function E(a) {
    var b = a.length;
    if (1 === b) return { x: pa(a[0].clientX), y: pa(a[0].clientY) };
    for (var c = 0, d = 0, e = 0; b > e; )
      (c += a[e].clientX), (d += a[e].clientY), e++;
    return { x: pa(c / b), y: pa(d / b) };
  }

  function F(a, b, c) {
    return { x: b / a || 0, y: c / a || 0 };
  }

  function G(a, b) {
    return a === b ? Ia : qa(a) >= qa(b) ? (0 > a ? Ja : Ka) : 0 > b ? La : Ma;
  }

  function H(a, b, c) {
    c || (c = Qa);
    var d = b[c[0]] - a[c[0]],
      e = b[c[1]] - a[c[1]];
    return Math.sqrt(d * d + e * e);
  }

  function I(a, b, c) {
    c || (c = Qa);
    var d = b[c[0]] - a[c[0]],
      e = b[c[1]] - a[c[1]];
    return (180 * Math.atan2(e, d)) / Math.PI;
  }

  function J(a, b) {
    return I(b[1], b[0], Ra) + I(a[1], a[0], Ra);
  }

  function K(a, b) {
    return H(b[0], b[1], Ra) / H(a[0], a[1], Ra);
  }

  function L() {
    (this.evEl = Ta),
      (this.evWin = Ua),
      (this.pressed = !1),
      x.apply(this, arguments);
  }

  function M() {
    (this.evEl = Xa),
      (this.evWin = Ya),
      x.apply(this, arguments),
      (this.store = this.manager.session.pointerEvents = []);
  }

  function N() {
    (this.evTarget = $a),
      (this.evWin = _a),
      (this.started = !1),
      x.apply(this, arguments);
  }

  function O(a, b) {
    var c = s(a.touches),
      d = s(a.changedTouches);
    return b & (Ga | Ha) && (c = t(c.concat(d), 'identifier', !0)), [c, d];
  }

  function P() {
    (this.evTarget = bb), (this.targetIds = {}), x.apply(this, arguments);
  }

  function Q(a, b) {
    var c = s(a.touches),
      d = this.targetIds;
    if (b & (Ea | Fa) && 1 === c.length)
      return (d[c[0].identifier] = !0), [c, c];
    var e,
      f,
      g = s(a.changedTouches),
      h = [],
      i = this.target;
    if (
      ((f = c.filter(function (a) {
        return o(a.target, i);
      })),
      b === Ea)
    )
      for (e = 0; e < f.length; ) (d[f[e].identifier] = !0), e++;
    for (e = 0; e < g.length; )
      d[g[e].identifier] && h.push(g[e]),
        b & (Ga | Ha) && delete d[g[e].identifier],
        e++;
    return h.length ? [t(f.concat(h), 'identifier', !0), h] : void 0;
  }

  function R() {
    x.apply(this, arguments);
    var a = j(this.handler, this);
    (this.touch = new P(this.manager, a)),
      (this.mouse = new L(this.manager, a)),
      (this.primaryTouch = null),
      (this.lastTouches = []);
  }

  function S(a, b) {
    a & Ea
      ? ((this.primaryTouch = b.changedPointers[0].identifier), T.call(this, b))
      : a & (Ga | Ha) && T.call(this, b);
  }

  function T(a) {
    var b = a.changedPointers[0];
    if (b.identifier === this.primaryTouch) {
      var c = { x: b.clientX, y: b.clientY };
      this.lastTouches.push(c);
      var d = this.lastTouches,
        e = function () {
          var a = d.indexOf(c);
          a > -1 && d.splice(a, 1);
        };
      setTimeout(e, cb);
    }
  }

  function U(a) {
    for (
      var b = a.srcEvent.clientX, c = a.srcEvent.clientY, d = 0;
      d < this.lastTouches.length;
      d++
    ) {
      var e = this.lastTouches[d],
        f = Math.abs(b - e.x),
        g = Math.abs(c - e.y);
      if (db >= f && db >= g) return !0;
    }
    return !1;
  }

  function V(a, b) {
    (this.manager = a), this.set(b);
  }

  function W(a) {
    if (p(a, jb)) return jb;
    var b = p(a, kb),
      c = p(a, lb);
    return b && c ? jb : b || c ? (b ? kb : lb) : p(a, ib) ? ib : hb;
  }

  function X() {
    if (!fb) return !1;
    var b = {},
      c = a.CSS && a.CSS.supports;
    return (
      ['auto', 'manipulation', 'pan-y', 'pan-x', 'pan-x pan-y', 'none'].forEach(
        function (d) {
          b[d] = c ? a.CSS.supports('touch-action', d) : !0;
        }
      ),
      b
    );
  }

  function Y(a) {
    (this.options = la({}, this.defaults, a || {})),
      (this.id = v()),
      (this.manager = null),
      (this.options.enable = l(this.options.enable, !0)),
      (this.state = nb),
      (this.simultaneous = {}),
      (this.requireFail = []);
  }

  function Z(a) {
    return a & sb
      ? 'cancel'
      : a & qb
      ? 'end'
      : a & pb
      ? 'move'
      : a & ob
      ? 'start'
      : '';
  }

  function $(a) {
    return a == Ma
      ? 'down'
      : a == La
      ? 'up'
      : a == Ja
      ? 'left'
      : a == Ka
      ? 'right'
      : '';
  }

  function _(a, b) {
    var c = b.manager;
    return c ? c.get(a) : a;
  }

  function aa() {
    Y.apply(this, arguments);
  }

  function ba() {
    aa.apply(this, arguments), (this.pX = null), (this.pY = null);
  }

  function ca() {
    aa.apply(this, arguments);
  }

  function da() {
    Y.apply(this, arguments), (this._timer = null), (this._input = null);
  }

  function ea() {
    aa.apply(this, arguments);
  }

  function fa() {
    aa.apply(this, arguments);
  }

  function ga() {
    Y.apply(this, arguments),
      (this.pTime = !1),
      (this.pCenter = !1),
      (this._timer = null),
      (this._input = null),
      (this.count = 0);
  }

  function ha(a, b) {
    return (
      (b = b || {}),
      (b.recognizers = l(b.recognizers, ha.defaults.preset)),
      new ia(a, b)
    );
  }

  function ia(a, b) {
    (this.options = la({}, ha.defaults, b || {})),
      (this.options.inputTarget = this.options.inputTarget || a),
      (this.handlers = {}),
      (this.session = {}),
      (this.recognizers = []),
      (this.oldCssProps = {}),
      (this.element = a),
      (this.input = y(this)),
      (this.touchAction = new V(this, this.options.touchAction)),
      ja(this, !0),
      g(
        this.options.recognizers,
        function (a) {
          var b = this.add(new a[0](a[1]));
          a[2] && b.recognizeWith(a[2]), a[3] && b.requireFailure(a[3]);
        },
        this
      );
  }

  function ja(a, b) {
    var c = a.element;
    if (c.style) {
      var d;
      g(a.options.cssProps, function (e, f) {
        (d = u(c.style, f)),
          b
            ? ((a.oldCssProps[d] = c.style[d]), (c.style[d] = e))
            : (c.style[d] = a.oldCssProps[d] || '');
      }),
        b || (a.oldCssProps = {});
    }
  }

  function ka(a, c) {
    var d = b.createEvent('Event');
    d.initEvent(a, !0, !0), (d.gesture = c), c.target.dispatchEvent(d);
  }

  var la,
    ma = ['', 'webkit', 'Moz', 'MS', 'ms', 'o'],
    na = b.createElement('div'),
    oa = 'function',
    pa = Math.round,
    qa = Math.abs,
    ra = Date.now;
  la =
    'function' != typeof Object.assign
      ? function (a) {
          if (a === d || null === a)
            throw new TypeError('Cannot convert undefined or null to object');
          for (var b = Object(a), c = 1; c < arguments.length; c++) {
            var e = arguments[c];
            if (e !== d && null !== e)
              for (var f in e) e.hasOwnProperty(f) && (b[f] = e[f]);
          }
          return b;
        }
      : Object.assign;
  var sa = h(
      function (a, b, c) {
        for (var e = Object.keys(b), f = 0; f < e.length; )
          (!c || (c && a[e[f]] === d)) && (a[e[f]] = b[e[f]]), f++;
        return a;
      },
      'extend',
      'Use `assign`.'
    ),
    ta = h(
      function (a, b) {
        return sa(a, b, !0);
      },
      'merge',
      'Use `assign`.'
    ),
    ua = 1,
    va = /mobile|tablet|ip(ad|hone|od)|android/i,
    wa = 'ontouchstart' in a,
    xa = u(a, 'PointerEvent') !== d,
    ya = wa && va.test(navigator.userAgent),
    za = 'touch',
    Aa = 'pen',
    Ba = 'mouse',
    Ca = 'kinect',
    Da = 25,
    Ea = 1,
    Fa = 2,
    Ga = 4,
    Ha = 8,
    Ia = 1,
    Ja = 2,
    Ka = 4,
    La = 8,
    Ma = 16,
    Na = Ja | Ka,
    Oa = La | Ma,
    Pa = Na | Oa,
    Qa = ['x', 'y'],
    Ra = ['clientX', 'clientY'];
  x.prototype = {
    handler: function () {},
    init: function () {
      this.evEl && m(this.element, this.evEl, this.domHandler),
        this.evTarget && m(this.target, this.evTarget, this.domHandler),
        this.evWin && m(w(this.element), this.evWin, this.domHandler);
    },
    destroy: function () {
      this.evEl && n(this.element, this.evEl, this.domHandler),
        this.evTarget && n(this.target, this.evTarget, this.domHandler),
        this.evWin && n(w(this.element), this.evWin, this.domHandler);
    },
  };
  var Sa = { mousedown: Ea, mousemove: Fa, mouseup: Ga },
    Ta = 'mousedown',
    Ua = 'mousemove mouseup';
  i(L, x, {
    handler: function (a) {
      var b = Sa[a.type];
      b & Ea && 0 === a.button && (this.pressed = !0),
        b & Fa && 1 !== a.which && (b = Ga),
        this.pressed &&
          (b & Ga && (this.pressed = !1),
          this.callback(this.manager, b, {
            pointers: [a],
            changedPointers: [a],
            pointerType: Ba,
            srcEvent: a,
          }));
    },
  });
  var Va = {
      pointerdown: Ea,
      pointermove: Fa,
      pointerup: Ga,
      pointercancel: Ha,
      pointerout: Ha,
    },
    Wa = { 2: za, 3: Aa, 4: Ba, 5: Ca },
    Xa = 'pointerdown',
    Ya = 'pointermove pointerup pointercancel';
  a.MSPointerEvent &&
    !a.PointerEvent &&
    ((Xa = 'MSPointerDown'),
    (Ya = 'MSPointerMove MSPointerUp MSPointerCancel')),
    i(M, x, {
      handler: function (a) {
        var b = this.store,
          c = !1,
          d = a.type.toLowerCase().replace('ms', ''),
          e = Va[d],
          f = Wa[a.pointerType] || a.pointerType,
          g = f == za,
          h = r(b, a.pointerId, 'pointerId');
        e & Ea && (0 === a.button || g)
          ? 0 > h && (b.push(a), (h = b.length - 1))
          : e & (Ga | Ha) && (c = !0),
          0 > h ||
            ((b[h] = a),
            this.callback(this.manager, e, {
              pointers: b,
              changedPointers: [a],
              pointerType: f,
              srcEvent: a,
            }),
            c && b.splice(h, 1));
      },
    });
  var Za = { touchstart: Ea, touchmove: Fa, touchend: Ga, touchcancel: Ha },
    $a = 'touchstart',
    _a = 'touchstart touchmove touchend touchcancel';
  i(N, x, {
    handler: function (a) {
      var b = Za[a.type];
      if ((b === Ea && (this.started = !0), this.started)) {
        var c = O.call(this, a, b);
        b & (Ga | Ha) && c[0].length - c[1].length === 0 && (this.started = !1),
          this.callback(this.manager, b, {
            pointers: c[0],
            changedPointers: c[1],
            pointerType: za,
            srcEvent: a,
          });
      }
    },
  });
  var ab = { touchstart: Ea, touchmove: Fa, touchend: Ga, touchcancel: Ha },
    bb = 'touchstart touchmove touchend touchcancel';
  i(P, x, {
    handler: function (a) {
      var b = ab[a.type],
        c = Q.call(this, a, b);
      c &&
        this.callback(this.manager, b, {
          pointers: c[0],
          changedPointers: c[1],
          pointerType: za,
          srcEvent: a,
        });
    },
  });
  var cb = 2500,
    db = 25;
  i(R, x, {
    handler: function (a, b, c) {
      var d = c.pointerType == za,
        e = c.pointerType == Ba;
      if (
        !(e && c.sourceCapabilities && c.sourceCapabilities.firesTouchEvents)
      ) {
        if (d) S.call(this, b, c);
        else if (e && U.call(this, c)) return;
        this.callback(a, b, c);
      }
    },
    destroy: function () {
      this.touch.destroy(), this.mouse.destroy();
    },
  });
  var eb = u(na.style, 'touchAction'),
    fb = eb !== d,
    gb = 'compute',
    hb = 'auto',
    ib = 'manipulation',
    jb = 'none',
    kb = 'pan-x',
    lb = 'pan-y',
    mb = X();
  V.prototype = {
    set: function (a) {
      a == gb && (a = this.compute()),
        fb &&
          this.manager.element.style &&
          mb[a] &&
          (this.manager.element.style[eb] = a),
        (this.actions = a.toLowerCase().trim());
    },
    update: function () {
      this.set(this.manager.options.touchAction);
    },
    compute: function () {
      var a = [];
      return (
        g(this.manager.recognizers, function (b) {
          k(b.options.enable, [b]) && (a = a.concat(b.getTouchAction()));
        }),
        W(a.join(' '))
      );
    },
    preventDefaults: function (a) {
      var b = a.srcEvent,
        c = a.offsetDirection;
      if (this.manager.session.prevented) return void b.preventDefault();
      var d = this.actions,
        e = p(d, jb) && !mb[jb],
        f = p(d, lb) && !mb[lb],
        g = p(d, kb) && !mb[kb];
      if (e) {
        var h = 1 === a.pointers.length,
          i = a.distance < 2,
          j = a.deltaTime < 250;
        if (h && i && j) return;
      }
      return g && f
        ? void 0
        : e || (f && c & Na) || (g && c & Oa)
        ? this.preventSrc(b)
        : void 0;
    },
    preventSrc: function (a) {
      (this.manager.session.prevented = !0), a.preventDefault();
    },
  };
  var nb = 1,
    ob = 2,
    pb = 4,
    qb = 8,
    rb = qb,
    sb = 16,
    tb = 32;
  (Y.prototype = {
    defaults: {},
    set: function (a) {
      return (
        la(this.options, a),
        this.manager && this.manager.touchAction.update(),
        this
      );
    },
    recognizeWith: function (a) {
      if (f(a, 'recognizeWith', this)) return this;
      var b = this.simultaneous;
      return (
        (a = _(a, this)),
        b[a.id] || ((b[a.id] = a), a.recognizeWith(this)),
        this
      );
    },
    dropRecognizeWith: function (a) {
      return f(a, 'dropRecognizeWith', this)
        ? this
        : ((a = _(a, this)), delete this.simultaneous[a.id], this);
    },
    requireFailure: function (a) {
      if (f(a, 'requireFailure', this)) return this;
      var b = this.requireFail;
      return (
        (a = _(a, this)),
        -1 === r(b, a) && (b.push(a), a.requireFailure(this)),
        this
      );
    },
    dropRequireFailure: function (a) {
      if (f(a, 'dropRequireFailure', this)) return this;
      a = _(a, this);
      var b = r(this.requireFail, a);
      return b > -1 && this.requireFail.splice(b, 1), this;
    },
    hasRequireFailures: function () {
      return this.requireFail.length > 0;
    },
    canRecognizeWith: function (a) {
      return !!this.simultaneous[a.id];
    },
    emit: function (a) {
      function b(b) {
        c.manager.emit(b, a);
      }

      var c = this,
        d = this.state;
      qb > d && b(c.options.event + Z(d)),
        b(c.options.event),
        a.additionalEvent && b(a.additionalEvent),
        d >= qb && b(c.options.event + Z(d));
    },
    tryEmit: function (a) {
      return this.canEmit() ? this.emit(a) : void (this.state = tb);
    },
    canEmit: function () {
      for (var a = 0; a < this.requireFail.length; ) {
        if (!(this.requireFail[a].state & (tb | nb))) return !1;
        a++;
      }
      return !0;
    },
    recognize: function (a) {
      var b = la({}, a);
      return k(this.options.enable, [this, b])
        ? (this.state & (rb | sb | tb) && (this.state = nb),
          (this.state = this.process(b)),
          void (this.state & (ob | pb | qb | sb) && this.tryEmit(b)))
        : (this.reset(), void (this.state = tb));
    },
    process: function (a) {},
    getTouchAction: function () {},
    reset: function () {},
  }),
    i(aa, Y, {
      defaults: { pointers: 1 },
      attrTest: function (a) {
        var b = this.options.pointers;
        return 0 === b || a.pointers.length === b;
      },
      process: function (a) {
        var b = this.state,
          c = a.eventType,
          d = b & (ob | pb),
          e = this.attrTest(a);
        return d && (c & Ha || !e)
          ? b | sb
          : d || e
          ? c & Ga
            ? b | qb
            : b & ob
            ? b | pb
            : ob
          : tb;
      },
    }),
    i(ba, aa, {
      defaults: { event: 'pan', threshold: 10, pointers: 1, direction: Pa },
      getTouchAction: function () {
        var a = this.options.direction,
          b = [];
        return a & Na && b.push(lb), a & Oa && b.push(kb), b;
      },
      directionTest: function (a) {
        var b = this.options,
          c = !0,
          d = a.distance,
          e = a.direction,
          f = a.deltaX,
          g = a.deltaY;
        return (
          e & b.direction ||
            (b.direction & Na
              ? ((e = 0 === f ? Ia : 0 > f ? Ja : Ka),
                (c = f != this.pX),
                (d = Math.abs(a.deltaX)))
              : ((e = 0 === g ? Ia : 0 > g ? La : Ma),
                (c = g != this.pY),
                (d = Math.abs(a.deltaY)))),
          (a.direction = e),
          c && d > b.threshold && e & b.direction
        );
      },
      attrTest: function (a) {
        return (
          aa.prototype.attrTest.call(this, a) &&
          (this.state & ob || (!(this.state & ob) && this.directionTest(a)))
        );
      },
      emit: function (a) {
        (this.pX = a.deltaX), (this.pY = a.deltaY);
        var b = $(a.direction);
        b && (a.additionalEvent = this.options.event + b),
          this._super.emit.call(this, a);
      },
    }),
    i(ca, aa, {
      defaults: { event: 'pinch', threshold: 0, pointers: 2 },
      getTouchAction: function () {
        return [jb];
      },
      attrTest: function (a) {
        return (
          this._super.attrTest.call(this, a) &&
          (Math.abs(a.scale - 1) > this.options.threshold || this.state & ob)
        );
      },
      emit: function (a) {
        if (1 !== a.scale) {
          var b = a.scale < 1 ? 'in' : 'out';
          a.additionalEvent = this.options.event + b;
        }
        this._super.emit.call(this, a);
      },
    }),
    i(da, Y, {
      defaults: { event: 'press', pointers: 1, time: 251, threshold: 9 },
      getTouchAction: function () {
        return [hb];
      },
      process: function (a) {
        var b = this.options,
          c = a.pointers.length === b.pointers,
          d = a.distance < b.threshold,
          f = a.deltaTime > b.time;
        if (((this._input = a), !d || !c || (a.eventType & (Ga | Ha) && !f)))
          this.reset();
        else if (a.eventType & Ea)
          this.reset(),
            (this._timer = e(
              function () {
                (this.state = rb), this.tryEmit();
              },
              b.time,
              this
            ));
        else if (a.eventType & Ga) return rb;
        return tb;
      },
      reset: function () {
        clearTimeout(this._timer);
      },
      emit: function (a) {
        this.state === rb &&
          (a && a.eventType & Ga
            ? this.manager.emit(this.options.event + 'up', a)
            : ((this._input.timeStamp = ra()),
              this.manager.emit(this.options.event, this._input)));
      },
    }),
    i(ea, aa, {
      defaults: { event: 'rotate', threshold: 0, pointers: 2 },
      getTouchAction: function () {
        return [jb];
      },
      attrTest: function (a) {
        return (
          this._super.attrTest.call(this, a) &&
          (Math.abs(a.rotation) > this.options.threshold || this.state & ob)
        );
      },
    }),
    i(fa, aa, {
      defaults: {
        event: 'swipe',
        threshold: 10,
        velocity: 0.3,
        direction: Na | Oa,
        pointers: 1,
      },
      getTouchAction: function () {
        return ba.prototype.getTouchAction.call(this);
      },
      attrTest: function (a) {
        var b,
          c = this.options.direction;
        return (
          c & (Na | Oa)
            ? (b = a.overallVelocity)
            : c & Na
            ? (b = a.overallVelocityX)
            : c & Oa && (b = a.overallVelocityY),
          this._super.attrTest.call(this, a) &&
            c & a.offsetDirection &&
            a.distance > this.options.threshold &&
            a.maxPointers == this.options.pointers &&
            qa(b) > this.options.velocity &&
            a.eventType & Ga
        );
      },
      emit: function (a) {
        var b = $(a.offsetDirection);
        b && this.manager.emit(this.options.event + b, a),
          this.manager.emit(this.options.event, a);
      },
    }),
    i(ga, Y, {
      defaults: {
        event: 'tap',
        pointers: 1,
        taps: 1,
        interval: 300,
        time: 250,
        threshold: 9,
        posThreshold: 10,
      },
      getTouchAction: function () {
        return [ib];
      },
      process: function (a) {
        var b = this.options,
          c = a.pointers.length === b.pointers,
          d = a.distance < b.threshold,
          f = a.deltaTime < b.time;
        if ((this.reset(), a.eventType & Ea && 0 === this.count))
          return this.failTimeout();
        if (d && f && c) {
          if (a.eventType != Ga) return this.failTimeout();
          var g = this.pTime ? a.timeStamp - this.pTime < b.interval : !0,
            h = !this.pCenter || H(this.pCenter, a.center) < b.posThreshold;
          (this.pTime = a.timeStamp),
            (this.pCenter = a.center),
            h && g ? (this.count += 1) : (this.count = 1),
            (this._input = a);
          var i = this.count % b.taps;
          if (0 === i)
            return this.hasRequireFailures()
              ? ((this._timer = e(
                  function () {
                    (this.state = rb), this.tryEmit();
                  },
                  b.interval,
                  this
                )),
                ob)
              : rb;
        }
        return tb;
      },
      failTimeout: function () {
        return (
          (this._timer = e(
            function () {
              this.state = tb;
            },
            this.options.interval,
            this
          )),
          tb
        );
      },
      reset: function () {
        clearTimeout(this._timer);
      },
      emit: function () {
        this.state == rb &&
          ((this._input.tapCount = this.count),
          this.manager.emit(this.options.event, this._input));
      },
    }),
    (ha.VERSION = '2.0.8'),
    (ha.defaults = {
      domEvents: !1,
      touchAction: gb,
      enable: !0,
      inputTarget: null,
      inputClass: null,
      preset: [
        [ea, { enable: !1 }],
        [ca, { enable: !1 }, ['rotate']],
        [fa, { direction: Na }],
        [ba, { direction: Na }, ['swipe']],
        [ga],
        [
          ga,
          {
            event: 'doubletap',
            taps: 2,
          },
          ['tap'],
        ],
        [da],
      ],
      cssProps: {
        userSelect: 'none',
        touchSelect: 'none',
        touchCallout: 'none',
        contentZooming: 'none',
        userDrag: 'none',
        tapHighlightColor: 'rgba(0,0,0,0)',
      },
    });
  var ub = 1,
    vb = 2;
  (ia.prototype = {
    set: function (a) {
      return (
        la(this.options, a),
        a.touchAction && this.touchAction.update(),
        a.inputTarget &&
          (this.input.destroy(),
          (this.input.target = a.inputTarget),
          this.input.init()),
        this
      );
    },
    stop: function (a) {
      this.session.stopped = a ? vb : ub;
    },
    recognize: function (a) {
      var b = this.session;
      if (!b.stopped) {
        this.touchAction.preventDefaults(a);
        var c,
          d = this.recognizers,
          e = b.curRecognizer;
        (!e || (e && e.state & rb)) && (e = b.curRecognizer = null);
        for (var f = 0; f < d.length; )
          (c = d[f]),
            b.stopped === vb || (e && c != e && !c.canRecognizeWith(e))
              ? c.reset()
              : c.recognize(a),
            !e && c.state & (ob | pb | qb) && (e = b.curRecognizer = c),
            f++;
      }
    },
    get: function (a) {
      if (a instanceof Y) return a;
      for (var b = this.recognizers, c = 0; c < b.length; c++)
        if (b[c].options.event == a) return b[c];
      return null;
    },
    add: function (a) {
      if (f(a, 'add', this)) return this;
      var b = this.get(a.options.event);
      return (
        b && this.remove(b),
        this.recognizers.push(a),
        (a.manager = this),
        this.touchAction.update(),
        a
      );
    },
    remove: function (a) {
      if (f(a, 'remove', this)) return this;
      if ((a = this.get(a))) {
        var b = this.recognizers,
          c = r(b, a);
        -1 !== c && (b.splice(c, 1), this.touchAction.update());
      }
      return this;
    },
    on: function (a, b) {
      if (a !== d && b !== d) {
        var c = this.handlers;
        return (
          g(q(a), function (a) {
            (c[a] = c[a] || []), c[a].push(b);
          }),
          this
        );
      }
    },
    off: function (a, b) {
      if (a !== d) {
        var c = this.handlers;
        return (
          g(q(a), function (a) {
            b ? c[a] && c[a].splice(r(c[a], b), 1) : delete c[a];
          }),
          this
        );
      }
    },
    emit: function (a, b) {
      this.options.domEvents && ka(a, b);
      var c = this.handlers[a] && this.handlers[a].slice();
      if (c && c.length) {
        (b.type = a),
          (b.preventDefault = function () {
            b.srcEvent.preventDefault();
          });
        for (var d = 0; d < c.length; ) c[d](b), d++;
      }
    },
    destroy: function () {
      this.element && ja(this, !1),
        (this.handlers = {}),
        (this.session = {}),
        this.input.destroy(),
        (this.element = null);
    },
  }),
    la(ha, {
      INPUT_START: Ea,
      INPUT_MOVE: Fa,
      INPUT_END: Ga,
      INPUT_CANCEL: Ha,
      STATE_POSSIBLE: nb,
      STATE_BEGAN: ob,
      STATE_CHANGED: pb,
      STATE_ENDED: qb,
      STATE_RECOGNIZED: rb,
      STATE_CANCELLED: sb,
      STATE_FAILED: tb,
      DIRECTION_NONE: Ia,
      DIRECTION_LEFT: Ja,
      DIRECTION_RIGHT: Ka,
      DIRECTION_UP: La,
      DIRECTION_DOWN: Ma,
      DIRECTION_HORIZONTAL: Na,
      DIRECTION_VERTICAL: Oa,
      DIRECTION_ALL: Pa,
      Manager: ia,
      Input: x,
      TouchAction: V,
      TouchInput: P,
      MouseInput: L,
      PointerEventInput: M,
      TouchMouseInput: R,
      SingleTouchInput: N,
      Recognizer: Y,
      AttrRecognizer: aa,
      Tap: ga,
      Pan: ba,
      Swipe: fa,
      Pinch: ca,
      Rotate: ea,
      Press: da,
      on: m,
      off: n,
      each: g,
      merge: ta,
      extend: sa,
      assign: la,
      inherit: i,
      bindFn: j,
      prefixed: u,
    });
  var wb = 'undefined' != typeof a ? a : 'undefined' != typeof self ? self : {};
  (wb.Hammer = ha),
    'function' == typeof define && define.amd
      ? define(function () {
          return ha;
        })
      : 'undefined' != typeof module && module.exports
      ? (module.exports = ha)
      : (a[c] = ha);
})(window, document, 'Hammer');

/*
 * Utility module
 */
lib = {
  hasClass: function (el, cls) {
    return el && el.className
      ? el.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
      : false;
  },
  addClass: function (el, cls) {
    if (el && !this.hasClass(el, cls)) el.className += ' ' + cls;
  },
  removeClass: function (el, cls) {
    if (el && this.hasClass(el, cls)) {
      el.className = el.className.replace(
        new RegExp('(\\s|^)' + cls + '(\\s|$)'),
        ' '
      );
    }
  },
  extend: function (obj) {
    for (var i = 1; i < arguments.length; i++) {
      for (var p in arguments[i]) {
        if (arguments[i].hasOwnProperty(p)) {
          obj[p] = arguments[i][p];
        }
      }
    }
    return obj;
  },
  each: function (obj, callback) {
    var property, len;
    if (typeof obj.length === 'number') {
      for (property = 0, len = obj.length; property < len; property++) {
        if (callback.call(obj[property], property, obj[property]) === false) {
          break;
        }
      }
    } else {
      for (property in obj) {
        if (obj.hasOwnProperty(property)) {
          if (callback.call(obj[property], property, obj[property]) === false) {
            break;
          }
        }
      }
    }
  },
  event: (function () {
    var fixEvent = function (e) {
      e = e || window.event;
      if (e.isFixed) return e;
      else e.isFixed = true;
      if (!e.target) e.target = e.srcElement;
      e.preventDefault =
        e.preventDefault ||
        function () {
          this.returnValue = false;
        };
      e.stopPropagation =
        e.stopPropagation ||
        function () {
          this.cancelBubble = true;
        };
      return e;
    };
    return {
      add: function (elem, event, handler) {
        if (!elem.events) {
          elem.events = {};
          elem.handle = function (e) {
            var ret,
              handlers = elem.events[e.type];
            e = fixEvent(e);
            for (var i = 0, len = handlers.length; i < len; i++) {
              if (handlers[i]) {
                ret = handlers[i].call(elem, e);
                if (ret === false) {
                  e.preventDefault();
                  e.stopPropagation();
                }
              }
            }
          };
        }
        if (!elem.events[event]) {
          elem.events[event] = [];
          if (elem.addEventListener)
            elem.addEventListener(event, elem.handle, false);
          else if (elem.attachEvent)
            elem.attachEvent('on' + event, elem.handle);
        }
        elem.events[event].push(handler);
      },
      remove: function (elem, event, handler) {
        var handlers = elem.events[event];
        for (var i = handlers.length - 1; i >= 0; i--) {
          if (handlers[i] === handler) {
            handlers.splice(i, 1);
          }
        }
        if (!handlers.length) {
          delete elem.events[event];
          if (elem.removeEventListener)
            elem.removeEventListener(event, elem.handle, false);
          else if (elem.detachEvent)
            elem.detachEvent('on' + event, elem.handle);
        }
      },
    };
  })(),
  queryElementsBySelector: function (selector, scope) {
    scope = scope || document;
    if (!selector) return [];
    if (selector === '>*') return scope.children;
    if (typeof document.querySelectorAll === 'function') {
      return scope.querySelectorAll(selector);
    }
    var selectors = selector.split(',');
    var resultList = [];
    for (var s = 0; s < selectors.length; s++) {
      var currentContext = [scope || document];
      var tokens = selectors[s]
        .replace(/^\s+/, '')
        .replace(/\s+$/, '')
        .split(' ');
      for (var i = 0; i < tokens.length; i++) {
        token = tokens[i].replace(/^\s+/, '').replace(/\s+$/, '');
        if (token.indexOf('#') > -1) {
          var bits = token.split('#'),
            tagName = bits[0],
            id = bits[1];
          var element = document.getElementById(id);
          if (element && tagName && element.nodeName.toLowerCase() != tagName) {
            return [];
          }
          currentContext = element ? [element] : [];
          continue;
        }
        if (token.indexOf('.') > -1) {
          var bits = token.split('.'),
            tagName = bits[0] || '*',
            className = bits[1],
            found = [],
            foundCount = 0;
          for (var h = 0; h < currentContext.length; h++) {
            var elements;
            if (tagName == '*') {
              elements = currentContext[h].getElementsByTagName('*');
            } else {
              elements = currentContext[h].getElementsByTagName(tagName);
            }
            for (var j = 0; j < elements.length; j++) {
              found[foundCount++] = elements[j];
            }
          }
          currentContext = [];
          var currentContextIndex = 0;
          for (var k = 0; k < found.length; k++) {
            if (
              found[k].className &&
              found[k].className.match(
                new RegExp('(\\s|^)' + className + '(\\s|$)')
              )
            ) {
              currentContext[currentContextIndex++] = found[k];
            }
          }
          continue;
        }
        if (token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/)) {
          var tagName = RegExp.$1 || '*',
            attrName = RegExp.$2,
            attrOperator = RegExp.$3,
            attrValue = RegExp.$4;
          if (
            attrName.toLowerCase() == 'for' &&
            this.browser.msie &&
            this.browser.version < 8
          ) {
            attrName = 'htmlFor';
          }
          var found = [],
            foundCount = 0;
          for (var h = 0; h < currentContext.length; h++) {
            var elements;
            if (tagName == '*') {
              elements = currentContext[h].getElementsByTagName('*');
            } else {
              elements = currentContext[h].getElementsByTagName(tagName);
            }
            for (var j = 0; elements[j]; j++) {
              found[foundCount++] = elements[j];
            }
          }
          currentContext = [];
          var currentContextIndex = 0,
            checkFunction;
          switch (attrOperator) {
            case '=':
              checkFunction = function (e) {
                return e.getAttribute(attrName) == attrValue;
              };
              break;
            case '~':
              checkFunction = function (e) {
                return e
                  .getAttribute(attrName)
                  .match(new RegExp('(\\s|^)' + attrValue + '(\\s|$)'));
              };
              break;
            case '|':
              checkFunction = function (e) {
                return e
                  .getAttribute(attrName)
                  .match(new RegExp('^' + attrValue + '-?'));
              };
              break;
            case '^':
              checkFunction = function (e) {
                return e.getAttribute(attrName).indexOf(attrValue) == 0;
              };
              break;
            case '$':
              checkFunction = function (e) {
                return (
                  e.getAttribute(attrName).lastIndexOf(attrValue) ==
                  e.getAttribute(attrName).length - attrValue.length
                );
              };
              break;
            case '*':
              checkFunction = function (e) {
                return e.getAttribute(attrName).indexOf(attrValue) > -1;
              };
              break;
            default:
              checkFunction = function (e) {
                return e.getAttribute(attrName);
              };
          }
          currentContext = [];
          var currentContextIndex = 0;
          for (var k = 0; k < found.length; k++) {
            if (checkFunction(found[k])) {
              currentContext[currentContextIndex++] = found[k];
            }
          }
          continue;
        }
        tagName = token;
        var found = [],
          foundCount = 0;
        for (var h = 0; h < currentContext.length; h++) {
          var elements = currentContext[h].getElementsByTagName(tagName);
          for (var j = 0; j < elements.length; j++) {
            found[foundCount++] = elements[j];
          }
        }
        currentContext = found;
      }
      resultList = [].concat(resultList, currentContext);
    }
    return resultList;
  },
  trim: function (str) {
    return str.replace(/^\s+/, '').replace(/\s+$/, '');
  },
  bind: function (f, scope, forceArgs) {
    return function () {
      return f.apply(
        scope,
        typeof forceArgs !== 'undefined' ? [forceArgs] : arguments
      );
    };
  },
};

/*!
 * JavaScript Custom Forms
 *
 * Copyright 2014-2015 PSD2HTML - http://psd2html.com/jcf
 * Released under the MIT license (LICENSE.txt)
 *
 * Version: 1.1.3
 */
(function (root, factory) {
  'use strict';
  if (typeof define === 'function' && define.amd) {
    define(['jquery'], factory);
  } else if (typeof exports === 'object') {
    module.exports = factory(require('jquery'));
  } else {
    root.jcf = factory(jQuery);
  }
})(this, function ($) {
  'use strict';

  // define version
  var version = '1.1.3';

  // private variables
  var customInstances = [];

  // default global options
  var commonOptions = {
    optionsKey: 'jcf',
    dataKey: 'jcf-instance',
    rtlClass: 'jcf-rtl',
    focusClass: 'jcf-focus',
    pressedClass: 'jcf-pressed',
    disabledClass: 'jcf-disabled',
    hiddenClass: 'jcf-hidden',
    resetAppearanceClass: 'jcf-reset-appearance',
    unselectableClass: 'jcf-unselectable',
  };

  // detect device type
  var isTouchDevice =
      'ontouchstart' in window ||
      (window.DocumentTouch && document instanceof window.DocumentTouch),
    isWinPhoneDevice = /Windows Phone/.test(navigator.userAgent);
  commonOptions.isMobileDevice = !!(isTouchDevice || isWinPhoneDevice);

  var isIOS = /(iPad|iPhone).*OS ([0-9_]*) .*/.exec(navigator.userAgent);
  if (isIOS) isIOS = parseFloat(isIOS[2].replace(/_/g, '.'));
  commonOptions.ios = isIOS;

  // create global stylesheet if custom forms are used
  var createStyleSheet = function () {
    var styleTag = $('<style>').appendTo('head'),
      styleSheet = styleTag.prop('sheet') || styleTag.prop('styleSheet');

    // crossbrowser style handling
    var addCSSRule = function (selector, rules, index) {
      if (styleSheet.insertRule) {
        styleSheet.insertRule(selector + '{' + rules + '}', index);
      } else {
        styleSheet.addRule(selector, rules, index);
      }
    };

    // add special rules
    addCSSRule(
      '.' + commonOptions.hiddenClass,
      'position:absolute !important;left:-9999px !important;height:1px !important;width:1px !important;margin:0 !important;border-width:0 !important;-webkit-appearance:none;-moz-appearance:none;appearance:none'
    );
    addCSSRule(
      '.' + commonOptions.rtlClass + ' .' + commonOptions.hiddenClass,
      'right:-9999px !important; left: auto !important'
    );
    addCSSRule(
      '.' + commonOptions.unselectableClass,
      '-webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; -webkit-tap-highlight-color: rgba(0,0,0,0);'
    );
    addCSSRule(
      '.' + commonOptions.resetAppearanceClass,
      'background: none; border: none; -webkit-appearance: none; appearance: none; opacity: 0; filter: alpha(opacity=0);'
    );

    // detect rtl pages
    var html = $('html'),
      body = $('body');
    if (html.css('direction') === 'rtl' || body.css('direction') === 'rtl') {
      html.addClass(commonOptions.rtlClass);
    }

    // handle form reset event
    html.on('reset', function () {
      setTimeout(function () {
        api.refreshAll();
      }, 0);
    });

    // mark stylesheet as created
    commonOptions.styleSheetCreated = true;
  };

  // simplified pointer events handler
  (function () {
    var pointerEventsSupported =
        navigator.pointerEnabled || navigator.msPointerEnabled,
      touchEventsSupported =
        'ontouchstart' in window ||
        (window.DocumentTouch && document instanceof window.DocumentTouch),
      eventList,
      eventMap = {},
      eventPrefix = 'jcf-';

    // detect events to attach
    if (pointerEventsSupported) {
      eventList = {
        pointerover: navigator.pointerEnabled ? 'pointerover' : 'MSPointerOver',
        pointerdown: navigator.pointerEnabled ? 'pointerdown' : 'MSPointerDown',
        pointermove: navigator.pointerEnabled ? 'pointermove' : 'MSPointerMove',
        pointerup: navigator.pointerEnabled ? 'pointerup' : 'MSPointerUp',
      };
    } else {
      eventList = {
        pointerover: 'mouseover',
        pointerdown: 'mousedown' + (touchEventsSupported ? ' touchstart' : ''),
        pointermove: 'mousemove' + (touchEventsSupported ? ' touchmove' : ''),
        pointerup: 'mouseup' + (touchEventsSupported ? ' touchend' : ''),
      };
    }

    // create event map
    $.each(eventList, function (targetEventName, fakeEventList) {
      $.each(fakeEventList.split(' '), function (index, fakeEventName) {
        eventMap[fakeEventName] = targetEventName;
      });
    });

    // jQuery event hooks
    $.each(eventList, function (eventName, eventHandlers) {
      eventHandlers = eventHandlers.split(' ');
      $.event.special[eventPrefix + eventName] = {
        setup: function () {
          var self = this;
          $.each(eventHandlers, function (index, fallbackEvent) {
            if (self.addEventListener)
              self.addEventListener(
                fallbackEvent,
                fixEvent,
                commonOptions.isMobileDevice ? { passive: false } : false
              );
            else self['on' + fallbackEvent] = fixEvent;
          });
        },
        teardown: function () {
          var self = this;
          $.each(eventHandlers, function (index, fallbackEvent) {
            if (self.addEventListener)
              self.removeEventListener(
                fallbackEvent,
                fixEvent,
                commonOptions.isMobileDevice ? { passive: false } : false
              );
            else self['on' + fallbackEvent] = null;
          });
        },
      };
    });

    // check that mouse event are not simulated by mobile browsers
    var lastTouch = null;
    var mouseEventSimulated = function (e) {
      var dx = Math.abs(e.pageX - lastTouch.x),
        dy = Math.abs(e.pageY - lastTouch.y),
        rangeDistance = 25;

      if (dx <= rangeDistance && dy <= rangeDistance) {
        return true;
      }
    };

    // normalize event
    var fixEvent = function (e) {
      var origEvent = e || window.event,
        touchEventData = null,
        targetEventName = eventMap[origEvent.type];

      e = $.event.fix(origEvent);
      e.type = eventPrefix + targetEventName;

      if (origEvent.pointerType) {
        switch (origEvent.pointerType) {
          case 2:
            e.pointerType = 'touch';
            break;
          case 3:
            e.pointerType = 'pen';
            break;
          case 4:
            e.pointerType = 'mouse';
            break;
          default:
            e.pointerType = origEvent.pointerType;
        }
      } else {
        e.pointerType = origEvent.type.substr(0, 5); // "mouse" or "touch" word length
      }

      if (!e.pageX && !e.pageY) {
        touchEventData = origEvent.changedTouches
          ? origEvent.changedTouches[0]
          : origEvent;
        e.pageX = touchEventData.pageX;
        e.pageY = touchEventData.pageY;
      }

      if (origEvent.type === 'touchend') {
        lastTouch = { x: e.pageX, y: e.pageY };
      }
      if (e.pointerType === 'mouse' && lastTouch && mouseEventSimulated(e)) {

      } else {
        return ($.event.dispatch || $.event.handle).call(this, e);
      }
    };
  })();

  // custom mousewheel/trackpad handler
  (function () {
    var wheelEvents = (
        'onwheel' in document || document.documentMode >= 9
          ? 'wheel'
          : 'mousewheel DOMMouseScroll'
      ).split(' '),
      shimEventName = 'jcf-mousewheel';

    $.event.special[shimEventName] = {
      setup: function () {
        var self = this;
        $.each(wheelEvents, function (index, fallbackEvent) {
          if (self.addEventListener)
            self.addEventListener(fallbackEvent, fixEvent, false);
          else self['on' + fallbackEvent] = fixEvent;
        });
      },
      teardown: function () {
        var self = this;
        $.each(wheelEvents, function (index, fallbackEvent) {
          if (self.addEventListener)
            self.removeEventListener(fallbackEvent, fixEvent, false);
          else self['on' + fallbackEvent] = null;
        });
      },
    };

    var fixEvent = function (e) {
      var origEvent = e || window.event;
      e = $.event.fix(origEvent);
      e.type = shimEventName;

      // old wheel events handler
      if ('detail' in origEvent) {
        e.deltaY = -origEvent.detail;
      }
      if ('wheelDelta' in origEvent) {
        e.deltaY = -origEvent.wheelDelta;
      }
      if ('wheelDeltaY' in origEvent) {
        e.deltaY = -origEvent.wheelDeltaY;
      }
      if ('wheelDeltaX' in origEvent) {
        e.deltaX = -origEvent.wheelDeltaX;
      }

      // modern wheel event handler
      if ('deltaY' in origEvent) {
        e.deltaY = origEvent.deltaY;
      }
      if ('deltaX' in origEvent) {
        e.deltaX = origEvent.deltaX;
      }

      // handle deltaMode for mouse wheel
      e.delta = e.deltaY || e.deltaX;
      if (origEvent.deltaMode === 1) {
        var lineHeight = 16;
        e.delta *= lineHeight;
        e.deltaY *= lineHeight;
        e.deltaX *= lineHeight;
      }

      return ($.event.dispatch || $.event.handle).call(this, e);
    };
  })();

  // extra module methods
  var moduleMixin = {
    // provide function for firing native events
    fireNativeEvent: function (elements, eventName) {
      $(elements).each(function () {
        var element = this,
          eventObject;
        if (element.dispatchEvent) {
          eventObject = document.createEvent('HTMLEvents');
          eventObject.initEvent(eventName, true, true);
          element.dispatchEvent(eventObject);
        } else if (document.createEventObject) {
          eventObject = document.createEventObject();
          eventObject.target = element;
          element.fireEvent('on' + eventName, eventObject);
        }
      });
    },
    // bind event handlers for module instance (functions beggining with "on")
    bindHandlers: function () {
      var self = this;
      $.each(self, function (propName, propValue) {
        if (propName.indexOf('on') === 0 && $.isFunction(propValue)) {
          // dont use $.proxy here because it doesn't create unique handler
          self[propName] = function () {
            return propValue.apply(self, arguments);
          };
        }
      });
    },
  };

  // public API
  var api = {
    version: version,
    modules: {},
    getOptions: function () {
      return $.extend({}, commonOptions);
    },
    setOptions: function (moduleName, moduleOptions) {
      if (arguments.length > 1) {
        // set module options
        if (this.modules[moduleName]) {
          $.extend(this.modules[moduleName].prototype.options, moduleOptions);
        }
      } else {
        // set common options
        $.extend(commonOptions, moduleName);
      }
    },
    addModule: function (proto) {
      // add module to list
      var Module = function (options) {
        // save instance to collection
        if (!options.element.data(commonOptions.dataKey)) {
          options.element.data(commonOptions.dataKey, this);
        }
        customInstances.push(this);

        // save options
        this.options = $.extend(
          {},
          commonOptions,
          this.options,
          getInlineOptions(options.element),
          options
        );

        // bind event handlers to instance
        this.bindHandlers();

        // call constructor
        this.init.apply(this, arguments);
      };

      // parse options from HTML attribute
      var getInlineOptions = function (element) {
        var dataOptions = element.data(commonOptions.optionsKey),
          attrOptions = element.attr(commonOptions.optionsKey);

        if (dataOptions) {
          return dataOptions;
        } else if (attrOptions) {
          try {
            return $.parseJSON(attrOptions);
          } catch (e) {
            // ignore invalid attributes
          }
        }
      };

      // set proto as prototype for new module
      Module.prototype = proto;

      // add mixin methods to module proto
      $.extend(proto, moduleMixin);
      if (proto.plugins) {
        $.each(proto.plugins, function (pluginName, plugin) {
          $.extend(plugin.prototype, moduleMixin);
        });
      }

      // override destroy method
      var originalDestroy = Module.prototype.destroy;
      Module.prototype.destroy = function () {
        this.options.element.removeData(this.options.dataKey);

        for (var i = customInstances.length - 1; i >= 0; i--) {
          if (customInstances[i] === this) {
            customInstances.splice(i, 1);
            break;
          }
        }

        if (originalDestroy) {
          originalDestroy.apply(this, arguments);
        }
      };

      // save module to list
      this.modules[proto.name] = Module;
    },
    getInstance: function (element) {
      return $(element).data(commonOptions.dataKey);
    },
    replace: function (elements, moduleName, customOptions) {
      var self = this,
        instance;

      if (!commonOptions.styleSheetCreated) {
        createStyleSheet();
      }

      $(elements).each(function () {
        var moduleOptions,
          element = $(this);

        instance = element.data(commonOptions.dataKey);
        if (instance) {
          instance.refresh();
        } else {
          if (!moduleName) {
            $.each(self.modules, function (currentModuleName, module) {
              if (
                module.prototype.matchElement.call(module.prototype, element)
              ) {
                moduleName = currentModuleName;
                return false;
              }
            });
          }
          if (moduleName) {
            moduleOptions = $.extend({ element: element }, customOptions);
            instance = new self.modules[moduleName](moduleOptions);
          }
        }
      });
      return instance;
    },
    refresh: function (elements) {
      $(elements).each(function () {
        var instance = $(this).data(commonOptions.dataKey);
        if (instance) {
          instance.refresh();
        }
      });
    },
    destroy: function (elements) {
      $(elements).each(function () {
        var instance = $(this).data(commonOptions.dataKey);
        if (instance) {
          instance.destroy();
        }
      });
    },
    replaceAll: function (context) {
      var self = this;
      $.each(this.modules, function (moduleName, module) {
        $(module.prototype.selector, context).each(function () {
          if (this.className.indexOf('jcf-ignore') < 0) {
            self.replace(this, moduleName);
          }
        });
      });
    },
    refreshAll: function (context) {
      if (context) {
        $.each(this.modules, function (moduleName, module) {
          $(module.prototype.selector, context).each(function () {
            var instance = $(this).data(commonOptions.dataKey);
            if (instance) {
              instance.refresh();
            }
          });
        });
      } else {
        for (var i = customInstances.length - 1; i >= 0; i--) {
          customInstances[i].refresh();
        }
      }
    },
    destroyAll: function (context) {
      if (context) {
        $.each(this.modules, function (moduleName, module) {
          $(module.prototype.selector, context).each(function (index, element) {
            var instance = $(element).data(commonOptions.dataKey);
            if (instance) {
              instance.destroy();
            }
          });
        });
      } else {
        while (customInstances.length) {
          customInstances[0].destroy();
        }
      }
    },
  };

  // always export API to the global window object
  window.jcf = api;

  return api;
});

/*!
 * JavaScript Custom Forms
 *
 * Copyright 2014-2015 PSD2HTML - http://psd2html.com/jcf
 * Released under the MIT license (LICENSE.txt)
 *
 * Version: 1.1.3
 */
(function (root, factory) {
  'use strict';
  if (typeof define === 'function' && define.amd) {
    define(['jquery'], factory);
  } else if (typeof exports === 'object') {
    module.exports = factory(require('jquery'));
  } else {
    root.jcf = factory(jQuery);
  }
})(this, function ($) {
  'use strict';

  // define version
  var version = '1.1.3';

  // private variables
  var customInstances = [];

  // default global options
  var commonOptions = {
    optionsKey: 'jcf',
    dataKey: 'jcf-instance',
    rtlClass: 'jcf-rtl',
    focusClass: 'jcf-focus',
    pressedClass: 'jcf-pressed',
    disabledClass: 'jcf-disabled',
    hiddenClass: 'jcf-hidden',
    resetAppearanceClass: 'jcf-reset-appearance',
    unselectableClass: 'jcf-unselectable',
  };

  // detect device type
  var isTouchDevice =
      'ontouchstart' in window ||
      (window.DocumentTouch && document instanceof window.DocumentTouch),
    isWinPhoneDevice = /Windows Phone/.test(navigator.userAgent);
  commonOptions.isMobileDevice = !!(isTouchDevice || isWinPhoneDevice);

  var isIOS = /(iPad|iPhone).*OS ([0-9_]*) .*/.exec(navigator.userAgent);
  if (isIOS) isIOS = parseFloat(isIOS[2].replace(/_/g, '.'));
  commonOptions.ios = isIOS;

  // create global stylesheet if custom forms are used
  var createStyleSheet = function () {
    var styleTag = $('<style>').appendTo('head'),
      styleSheet = styleTag.prop('sheet') || styleTag.prop('styleSheet');

    // crossbrowser style handling
    var addCSSRule = function (selector, rules, index) {
      if (styleSheet.insertRule) {
        styleSheet.insertRule(selector + '{' + rules + '}', index);
      } else {
        styleSheet.addRule(selector, rules, index);
      }
    };

    // add special rules
    addCSSRule(
      '.' + commonOptions.hiddenClass,
      'position:absolute !important;left:-9999px !important;height:1px !important;width:1px !important;margin:0 !important;border-width:0 !important;-webkit-appearance:none;-moz-appearance:none;appearance:none'
    );
    addCSSRule(
      '.' + commonOptions.rtlClass + ' .' + commonOptions.hiddenClass,
      'right:-9999px !important; left: auto !important'
    );
    addCSSRule(
      '.' + commonOptions.unselectableClass,
      '-webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; -webkit-tap-highlight-color: rgba(0,0,0,0);'
    );
    addCSSRule(
      '.' + commonOptions.resetAppearanceClass,
      'background: none; border: none; -webkit-appearance: none; appearance: none; opacity: 0; filter: alpha(opacity=0);'
    );

    // detect rtl pages
    var html = $('html'),
      body = $('body');
    if (html.css('direction') === 'rtl' || body.css('direction') === 'rtl') {
      html.addClass(commonOptions.rtlClass);
    }

    // handle form reset event
    html.on('reset', function () {
      setTimeout(function () {
        api.refreshAll();
      }, 0);
    });

    // mark stylesheet as created
    commonOptions.styleSheetCreated = true;
  };

  // simplified pointer events handler
  (function () {
    var pointerEventsSupported =
        navigator.pointerEnabled || navigator.msPointerEnabled,
      touchEventsSupported =
        'ontouchstart' in window ||
        (window.DocumentTouch && document instanceof window.DocumentTouch),
      eventList,
      eventMap = {},
      eventPrefix = 'jcf-';

    // detect events to attach
    if (pointerEventsSupported) {
      eventList = {
        pointerover: navigator.pointerEnabled ? 'pointerover' : 'MSPointerOver',
        pointerdown: navigator.pointerEnabled ? 'pointerdown' : 'MSPointerDown',
        pointermove: navigator.pointerEnabled ? 'pointermove' : 'MSPointerMove',
        pointerup: navigator.pointerEnabled ? 'pointerup' : 'MSPointerUp',
      };
    } else {
      eventList = {
        pointerover: 'mouseover',
        pointerdown: 'mousedown' + (touchEventsSupported ? ' touchstart' : ''),
        pointermove: 'mousemove' + (touchEventsSupported ? ' touchmove' : ''),
        pointerup: 'mouseup' + (touchEventsSupported ? ' touchend' : ''),
      };
    }

    // create event map
    $.each(eventList, function (targetEventName, fakeEventList) {
      $.each(fakeEventList.split(' '), function (index, fakeEventName) {
        eventMap[fakeEventName] = targetEventName;
      });
    });

    // jQuery event hooks
    $.each(eventList, function (eventName, eventHandlers) {
      eventHandlers = eventHandlers.split(' ');
      $.event.special[eventPrefix + eventName] = {
        setup: function () {
          var self = this;
          $.each(eventHandlers, function (index, fallbackEvent) {
            if (self.addEventListener)
              self.addEventListener(
                fallbackEvent,
                fixEvent,
                commonOptions.isMobileDevice ? { passive: false } : false
              );
            else self['on' + fallbackEvent] = fixEvent;
          });
        },
        teardown: function () {
          var self = this;
          $.each(eventHandlers, function (index, fallbackEvent) {
            if (self.addEventListener)
              self.removeEventListener(
                fallbackEvent,
                fixEvent,
                commonOptions.isMobileDevice ? { passive: false } : false
              );
            else self['on' + fallbackEvent] = null;
          });
        },
      };
    });

    // check that mouse event are not simulated by mobile browsers
    var lastTouch = null;
    var mouseEventSimulated = function (e) {
      var dx = Math.abs(e.pageX - lastTouch.x),
        dy = Math.abs(e.pageY - lastTouch.y),
        rangeDistance = 25;

      if (dx <= rangeDistance && dy <= rangeDistance) {
        return true;
      }
    };

    // normalize event
    var fixEvent = function (e) {
      var origEvent = e || window.event,
        touchEventData = null,
        targetEventName = eventMap[origEvent.type];

      e = $.event.fix(origEvent);
      e.type = eventPrefix + targetEventName;

      if (origEvent.pointerType) {
        switch (origEvent.pointerType) {
          case 2:
            e.pointerType = 'touch';
            break;
          case 3:
            e.pointerType = 'pen';
            break;
          case 4:
            e.pointerType = 'mouse';
            break;
          default:
            e.pointerType = origEvent.pointerType;
        }
      } else {
        e.pointerType = origEvent.type.substr(0, 5); // "mouse" or "touch" word length
      }

      if (!e.pageX && !e.pageY) {
        touchEventData = origEvent.changedTouches
          ? origEvent.changedTouches[0]
          : origEvent;
        e.pageX = touchEventData.pageX;
        e.pageY = touchEventData.pageY;
      }

      if (origEvent.type === 'touchend') {
        lastTouch = { x: e.pageX, y: e.pageY };
      }
      if (e.pointerType === 'mouse' && lastTouch && mouseEventSimulated(e)) {

      } else {
        return ($.event.dispatch || $.event.handle).call(this, e);
      }
    };
  })();

  // custom mousewheel/trackpad handler
  (function () {
    var wheelEvents = (
        'onwheel' in document || document.documentMode >= 9
          ? 'wheel'
          : 'mousewheel DOMMouseScroll'
      ).split(' '),
      shimEventName = 'jcf-mousewheel';

    $.event.special[shimEventName] = {
      setup: function () {
        var self = this;
        $.each(wheelEvents, function (index, fallbackEvent) {
          if (self.addEventListener)
            self.addEventListener(fallbackEvent, fixEvent, false);
          else self['on' + fallbackEvent] = fixEvent;
        });
      },
      teardown: function () {
        var self = this;
        $.each(wheelEvents, function (index, fallbackEvent) {
          if (self.addEventListener)
            self.removeEventListener(fallbackEvent, fixEvent, false);
          else self['on' + fallbackEvent] = null;
        });
      },
    };

    var fixEvent = function (e) {
      var origEvent = e || window.event;
      e = $.event.fix(origEvent);
      e.type = shimEventName;

      // old wheel events handler
      if ('detail' in origEvent) {
        e.deltaY = -origEvent.detail;
      }
      if ('wheelDelta' in origEvent) {
        e.deltaY = -origEvent.wheelDelta;
      }
      if ('wheelDeltaY' in origEvent) {
        e.deltaY = -origEvent.wheelDeltaY;
      }
      if ('wheelDeltaX' in origEvent) {
        e.deltaX = -origEvent.wheelDeltaX;
      }

      // modern wheel event handler
      if ('deltaY' in origEvent) {
        e.deltaY = origEvent.deltaY;
      }
      if ('deltaX' in origEvent) {
        e.deltaX = origEvent.deltaX;
      }

      // handle deltaMode for mouse wheel
      e.delta = e.deltaY || e.deltaX;
      if (origEvent.deltaMode === 1) {
        var lineHeight = 16;
        e.delta *= lineHeight;
        e.deltaY *= lineHeight;
        e.deltaX *= lineHeight;
      }

      return ($.event.dispatch || $.event.handle).call(this, e);
    };
  })();

  // extra module methods
  var moduleMixin = {
    // provide function for firing native events
    fireNativeEvent: function (elements, eventName) {
      $(elements).each(function () {
        var element = this,
          eventObject;
        if (element.dispatchEvent) {
          eventObject = document.createEvent('HTMLEvents');
          eventObject.initEvent(eventName, true, true);
          element.dispatchEvent(eventObject);
        } else if (document.createEventObject) {
          eventObject = document.createEventObject();
          eventObject.target = element;
          element.fireEvent('on' + eventName, eventObject);
        }
      });
    },
    // bind event handlers for module instance (functions beggining with "on")
    bindHandlers: function () {
      var self = this;
      $.each(self, function (propName, propValue) {
        if (propName.indexOf('on') === 0 && $.isFunction(propValue)) {
          // dont use $.proxy here because it doesn't create unique handler
          self[propName] = function () {
            return propValue.apply(self, arguments);
          };
        }
      });
    },
  };

  // public API
  var api = {
    version: version,
    modules: {},
    getOptions: function () {
      return $.extend({}, commonOptions);
    },
    setOptions: function (moduleName, moduleOptions) {
      if (arguments.length > 1) {
        // set module options
        if (this.modules[moduleName]) {
          $.extend(this.modules[moduleName].prototype.options, moduleOptions);
        }
      } else {
        // set common options
        $.extend(commonOptions, moduleName);
      }
    },
    addModule: function (proto) {
      // add module to list
      var Module = function (options) {
        // save instance to collection
        if (!options.element.data(commonOptions.dataKey)) {
          options.element.data(commonOptions.dataKey, this);
        }
        customInstances.push(this);

        // save options
        this.options = $.extend(
          {},
          commonOptions,
          this.options,
          getInlineOptions(options.element),
          options
        );

        // bind event handlers to instance
        this.bindHandlers();

        // call constructor
        this.init.apply(this, arguments);
      };

      // parse options from HTML attribute
      var getInlineOptions = function (element) {
        var dataOptions = element.data(commonOptions.optionsKey),
          attrOptions = element.attr(commonOptions.optionsKey);

        if (dataOptions) {
          return dataOptions;
        } else if (attrOptions) {
          try {
            return $.parseJSON(attrOptions);
          } catch (e) {
            // ignore invalid attributes
          }
        }
      };

      // set proto as prototype for new module
      Module.prototype = proto;

      // add mixin methods to module proto
      $.extend(proto, moduleMixin);
      if (proto.plugins) {
        $.each(proto.plugins, function (pluginName, plugin) {
          $.extend(plugin.prototype, moduleMixin);
        });
      }

      // override destroy method
      var originalDestroy = Module.prototype.destroy;
      Module.prototype.destroy = function () {
        this.options.element.removeData(this.options.dataKey);

        for (var i = customInstances.length - 1; i >= 0; i--) {
          if (customInstances[i] === this) {
            customInstances.splice(i, 1);
            break;
          }
        }

        if (originalDestroy) {
          originalDestroy.apply(this, arguments);
        }
      };

      // save module to list
      this.modules[proto.name] = Module;
    },
    getInstance: function (element) {
      return $(element).data(commonOptions.dataKey);
    },
    replace: function (elements, moduleName, customOptions) {
      var self = this,
        instance;

      if (!commonOptions.styleSheetCreated) {
        createStyleSheet();
      }

      $(elements).each(function () {
        var moduleOptions,
          element = $(this);

        instance = element.data(commonOptions.dataKey);
        if (instance) {
          instance.refresh();
        } else {
          if (!moduleName) {
            $.each(self.modules, function (currentModuleName, module) {
              if (
                module.prototype.matchElement.call(module.prototype, element)
              ) {
                moduleName = currentModuleName;
                return false;
              }
            });
          }
          if (moduleName) {
            moduleOptions = $.extend({ element: element }, customOptions);
            instance = new self.modules[moduleName](moduleOptions);
          }
        }
      });
      return instance;
    },
    refresh: function (elements) {
      $(elements).each(function () {
        var instance = $(this).data(commonOptions.dataKey);
        if (instance) {
          instance.refresh();
        }
      });
    },
    destroy: function (elements) {
      $(elements).each(function () {
        var instance = $(this).data(commonOptions.dataKey);
        if (instance) {
          instance.destroy();
        }
      });
    },
    replaceAll: function (context) {
      var self = this;
      $.each(this.modules, function (moduleName, module) {
        $(module.prototype.selector, context).each(function () {
          if (this.className.indexOf('jcf-ignore') < 0) {
            self.replace(this, moduleName);
          }
        });
      });
    },
    refreshAll: function (context) {
      if (context) {
        $.each(this.modules, function (moduleName, module) {
          $(module.prototype.selector, context).each(function () {
            var instance = $(this).data(commonOptions.dataKey);
            if (instance) {
              instance.refresh();
            }
          });
        });
      } else {
        for (var i = customInstances.length - 1; i >= 0; i--) {
          customInstances[i].refresh();
        }
      }
    },
    destroyAll: function (context) {
      if (context) {
        $.each(this.modules, function (moduleName, module) {
          $(module.prototype.selector, context).each(function (index, element) {
            var instance = $(element).data(commonOptions.dataKey);
            if (instance) {
              instance.destroy();
            }
          });
        });
      } else {
        while (customInstances.length) {
          customInstances[0].destroy();
        }
      }
    },
  };

  // always export API to the global window object
  window.jcf = api;

  return api;
});

/*!
 * JavaScript Custom Forms : Select Module
 *
 * Copyright 2014-2015 PSD2HTML - http://psd2html.com/jcf
 * Released under the MIT license (LICENSE.txt)
 *
 * Version: 1.1.3
 */
(function ($, window) {
  'use strict';

  jcf.addModule({
    name: 'Select',
    selector: 'select',
    options: {
      element: null,
      multipleCompactStyle: false,
    },
    plugins: {
      ListBox: ListBox,
      ComboBox: ComboBox,
      SelectList: SelectList,
    },
    matchElement: function (element) {
      return element.is('select');
    },
    init: function () {
      this.element = $(this.options.element);
      this.createInstance();
    },
    isListBox: function () {
      return this.element.is('[size]:not([jcf-size]), [multiple]');
    },
    createInstance: function () {
      if (this.instance) {
        this.instance.destroy();
      }
      if (this.isListBox() && !this.options.multipleCompactStyle) {
        this.instance = new ListBox(this.options);
      } else {
        this.instance = new ComboBox(this.options);
      }
    },
    refresh: function () {
      var typeMismatch =
        (this.isListBox() && this.instance instanceof ComboBox) ||
        (!this.isListBox() && this.instance instanceof ListBox);

      if (typeMismatch) {
        this.createInstance();
      } else {
        this.instance.refresh();
      }
    },
    destroy: function () {
      this.instance.destroy();
    },
  });

  // combobox module
  function ComboBox(options) {
    this.options = $.extend(
      {
        wrapNative: true,
        wrapNativeOnMobile: true,
        fakeDropInBody: true,
        useCustomScroll: true,
        flipDropToFit: true,
        maxVisibleItems: 10,
        fakeAreaStructure:
          '<span class="jcf-select"><span class="jcf-select-text"></span><span class="jcf-select-opener"></span></span>',
        fakeDropStructure:
          '<div class="jcf-select-drop"><div class="jcf-select-drop-content"></div></div>',
        optionClassPrefix: 'jcf-option-',
        selectClassPrefix: 'jcf-select-',
        dropContentSelector: '.jcf-select-drop-content',
        selectTextSelector: '.jcf-select-text',
        dropActiveClass: 'jcf-drop-active',
        flipDropClass: 'jcf-drop-flipped',
      },
      options
    );
    this.init();
  }

  $.extend(ComboBox.prototype, {
    init: function () {
      this.initStructure();
      this.bindHandlers();
      this.attachEvents();
      this.refresh();
    },
    initStructure: function () {
      // prepare structure
      this.win = $(window);
      this.doc = $(document);
      this.realElement = $(this.options.element);
      this.fakeElement = $(this.options.fakeAreaStructure).insertAfter(
        this.realElement
      );
      this.selectTextContainer = this.fakeElement.find(
        this.options.selectTextSelector
      );
      this.selectText = $('<span></span>').appendTo(this.selectTextContainer);
      makeUnselectable(this.fakeElement);

      // copy classes from original select
      this.fakeElement.addClass(
        getPrefixedClasses(
          this.realElement.prop('className'),
          this.options.selectClassPrefix
        )
      );

      // handle compact multiple style
      if (this.realElement.prop('multiple')) {
        this.fakeElement.addClass('jcf-compact-multiple');
      }

      // detect device type and dropdown behavior
      if (
        this.options.isMobileDevice &&
        this.options.wrapNativeOnMobile &&
        !this.options.wrapNative
      ) {
        this.options.wrapNative = true;
      }

      if (this.options.wrapNative) {
        // wrap native select inside fake block
        this.realElement
          .prependTo(this.fakeElement)
          .css({
            position: 'absolute',
            height: '100%',
            width: '100%',
          })
          .addClass(this.options.resetAppearanceClass);
      } else {
        // just hide native select
        this.realElement.addClass(this.options.hiddenClass);
        this.fakeElement.attr('title', this.realElement.attr('title'));
        this.fakeDropTarget = this.options.fakeDropInBody
          ? $('body')
          : this.fakeElement;
      }
    },
    attachEvents: function () {
      // delayed refresh handler
      var self = this;
      this.delayedRefresh = function () {
        setTimeout(function () {
          self.refresh();
          if (self.list) {
            self.list.refresh();
            self.list.scrollToActiveOption();
          }
        }, 1);
      };

      // native dropdown event handlers
      if (this.options.wrapNative) {
        this.realElement.on({
          focus: this.onFocus,
          change: this.onChange,
          click: this.onChange,
          keydown: this.onChange,
        });
      } else {
        // custom dropdown event handlers
        this.realElement.on({
          focus: this.onFocus,
          change: this.onChange,
          keydown: this.onKeyDown,
        });
        this.fakeElement.on({
          'jcf-pointerdown': this.onSelectAreaPress,
        });
      }
    },
    onKeyDown: function (e) {
      if (e.which === 13) {
        this.toggleDropdown();
      } else if (this.dropActive) {
        this.delayedRefresh();
      }
    },
    onChange: function () {
      this.refresh();
    },
    onFocus: function () {
      if (!this.pressedFlag || !this.focusedFlag) {
        this.fakeElement.addClass(this.options.focusClass);
        this.realElement.on('blur', this.onBlur);
        this.toggleListMode(true);
        this.focusedFlag = true;
      }
    },
    onBlur: function () {
      if (!this.pressedFlag) {
        this.fakeElement.removeClass(this.options.focusClass);
        this.realElement.off('blur', this.onBlur);
        this.toggleListMode(false);
        this.focusedFlag = false;
      }
    },
    onResize: function () {
      if (this.dropActive) {
        this.hideDropdown();
      }
    },
    onSelectDropPress: function () {
      this.pressedFlag = true;
    },
    onSelectDropRelease: function (e, pointerEvent) {
      this.pressedFlag = false;
      if (pointerEvent.pointerType === 'mouse') {
        this.realElement.focus();
      }
    },
    onSelectAreaPress: function (e) {
      // skip click if drop inside fake element or real select is disabled
      var dropClickedInsideFakeElement =
        !this.options.fakeDropInBody &&
        $(e.target).closest(this.dropdown).length;
      if (
        dropClickedInsideFakeElement ||
        e.button > 1 ||
        this.realElement.is(':disabled')
      ) {
        return;
      }

      // toggle dropdown visibility
      this.selectOpenedByEvent = e.pointerType;
      this.toggleDropdown();

      // misc handlers
      if (!this.focusedFlag) {
        if (e.pointerType === 'mouse') {
          this.realElement.focus();
        } else {
          this.onFocus(e);
        }
      }
      this.pressedFlag = true;
      this.fakeElement.addClass(this.options.pressedClass);
      this.doc.on('jcf-pointerup', this.onSelectAreaRelease);
    },
    onSelectAreaRelease: function (e) {
      if (this.focusedFlag && e.pointerType === 'mouse') {
        this.realElement.focus();
      }
      this.pressedFlag = false;
      this.fakeElement.removeClass(this.options.pressedClass);
      this.doc.off('jcf-pointerup', this.onSelectAreaRelease);
    },
    onOutsideClick: function (e) {
      var target = $(e.target),
        clickedInsideSelect =
          target.closest(this.fakeElement).length ||
          target.closest(this.dropdown).length;

      if (!clickedInsideSelect) {
        this.hideDropdown();
      }
    },
    onSelect: function () {
      this.refresh();

      if (this.realElement.prop('multiple')) {
        this.repositionDropdown();
      } else {
        this.hideDropdown();
      }

      this.fireNativeEvent(this.realElement, 'change');
    },
    toggleListMode: function (state) {
      if (!this.options.wrapNative) {
        if (state) {
          // temporary change select to list to avoid appearing of native dropdown
          this.realElement.attr({
            size: 4,
            'jcf-size': '',
          });
        } else {
          // restore select from list mode to dropdown select
          if (!this.options.wrapNative) {
            this.realElement.removeAttr('size jcf-size');
          }
        }
      }
    },
    createDropdown: function () {
      // destroy previous dropdown if needed
      if (this.dropdown) {
        this.list.destroy();
        this.dropdown.remove();
      }

      // create new drop container
      this.dropdown = $(this.options.fakeDropStructure).appendTo(
        this.fakeDropTarget
      );
      this.dropdown.addClass(
        getPrefixedClasses(
          this.realElement.prop('className'),
          this.options.selectClassPrefix
        )
      );
      makeUnselectable(this.dropdown);

      // handle compact multiple style
      if (this.realElement.prop('multiple')) {
        this.dropdown.addClass('jcf-compact-multiple');
      }

      // set initial styles for dropdown in body
      if (this.options.fakeDropInBody) {
        this.dropdown.css({
          position: 'absolute',
          top: -9999,
        });
      }

      // create new select list instance
      this.list = new SelectList({
        useHoverClass: true,
        handleResize: false,
        alwaysPreventMouseWheel: true,
        maxVisibleItems: this.options.maxVisibleItems,
        useCustomScroll: this.options.useCustomScroll,
        holder: this.dropdown.find(this.options.dropContentSelector),
        multipleSelectWithoutKey: this.realElement.prop('multiple'),
        element: this.realElement,
      });
      $(this.list).on({
        select: this.onSelect,
        press: this.onSelectDropPress,
        release: this.onSelectDropRelease,
      });
    },
    repositionDropdown: function () {
      var selectOffset = this.fakeElement.offset(),
        selectWidth = this.fakeElement.outerWidth(),
        selectHeight = this.fakeElement.outerHeight(),
        dropHeight = this.dropdown.css('width', selectWidth).outerHeight(),
        winScrollTop = this.win.scrollTop(),
        winHeight = this.win.height(),
        calcTop,
        calcLeft,
        bodyOffset,
        needFlipDrop = false;

      // check flip drop position
      if (
        selectOffset.top + selectHeight + dropHeight >
          winScrollTop + winHeight &&
        selectOffset.top - dropHeight > winScrollTop
      ) {
        needFlipDrop = true;
      }

      if (this.options.fakeDropInBody) {
        bodyOffset =
          this.fakeDropTarget.css('position') !== 'static'
            ? this.fakeDropTarget.offset().top
            : 0;
        if (this.options.flipDropToFit && needFlipDrop) {
          // calculate flipped dropdown position
          calcLeft = selectOffset.left;
          calcTop = selectOffset.top - dropHeight - bodyOffset;
        } else {
          // calculate default drop position
          calcLeft = selectOffset.left;
          calcTop = selectOffset.top + selectHeight - bodyOffset;
        }

        // update drop styles
        this.dropdown.css({
          width: selectWidth,
          left: calcLeft,
          top: calcTop,
        });
      }

      // refresh flipped class
      this.dropdown
        .add(this.fakeElement)
        .toggleClass(
          this.options.flipDropClass,
          this.options.flipDropToFit && needFlipDrop
        );
    },
    showDropdown: function () {
      // do not show empty custom dropdown
      if (!this.realElement.prop('options').length) {
        return;
      }

      // create options list if not created
      if (!this.dropdown) {
        this.createDropdown();
      }

      // show dropdown
      this.dropActive = true;
      this.dropdown.appendTo(this.fakeDropTarget);
      this.fakeElement.addClass(this.options.dropActiveClass);
      this.refreshSelectedText();
      this.repositionDropdown();
      this.list.setScrollTop(this.savedScrollTop);
      this.list.refresh();

      // add temporary event handlers
      this.win.on('resize', this.onResize);
      this.doc.on('jcf-pointerdown', this.onOutsideClick);
    },
    hideDropdown: function () {
      if (this.dropdown) {
        this.savedScrollTop = this.list.getScrollTop();
        this.fakeElement.removeClass(
          this.options.dropActiveClass + ' ' + this.options.flipDropClass
        );
        this.dropdown.removeClass(this.options.flipDropClass).detach();
        this.doc.off('jcf-pointerdown', this.onOutsideClick);
        this.win.off('resize', this.onResize);
        this.dropActive = false;
        if (this.selectOpenedByEvent === 'touch') {
          this.onBlur();
        }
      }
    },
    toggleDropdown: function () {
      if (this.dropActive) {
        this.hideDropdown();
      } else {
        this.showDropdown();
      }
    },
    refreshSelectedText: function () {
      // redraw selected area
      var selectedIndex = this.realElement.prop('selectedIndex'),
        selectedOption = this.realElement.prop('options')[selectedIndex],
        selectedOptionImage = selectedOption
          ? selectedOption.getAttribute('data-image')
          : null,
        selectedOptionText = '',
        selectedOptionClasses,
        self = this;

      if (this.realElement.prop('multiple')) {
        $.each(this.realElement.prop('options'), function (index, option) {
          if (option.selected) {
            selectedOptionText +=
              (selectedOptionText ? ', ' : '') + option.innerHTML;
          }
        });
        if (!selectedOptionText) {
          selectedOptionText = self.realElement.attr('placeholder') || '';
        }
        this.selectText.removeAttr('class').html(selectedOptionText);
      } else if (!selectedOption) {
        if (this.selectImage) {
          this.selectImage.hide();
        }
        this.selectText.removeAttr('class').empty();
      } else if (
        this.currentSelectedText !== selectedOption.innerHTML ||
        this.currentSelectedImage !== selectedOptionImage
      ) {
        selectedOptionClasses = getPrefixedClasses(
          selectedOption.className,
          this.options.optionClassPrefix
        );
        this.selectText
          .attr('class', selectedOptionClasses)
          .html(selectedOption.innerHTML);

        if (selectedOptionImage) {
          if (!this.selectImage) {
            this.selectImage = $('<img>')
              .prependTo(this.selectTextContainer)
              .hide();
          }
          this.selectImage.attr('src', selectedOptionImage).show();
        } else if (this.selectImage) {
          this.selectImage.hide();
        }

        this.currentSelectedText = selectedOption.innerHTML;
        this.currentSelectedImage = selectedOptionImage;
      }
    },
    refresh: function () {
      // refresh fake select visibility
      if (this.realElement.prop('style').display === 'none') {
        this.fakeElement.hide();
      } else {
        this.fakeElement.show();
      }

      // refresh selected text
      this.refreshSelectedText();

      // handle disabled state
      this.fakeElement.toggleClass(
        this.options.disabledClass,
        this.realElement.is(':disabled')
      );
    },
    destroy: function () {
      // restore structure
      if (this.options.wrapNative) {
        this.realElement
          .insertBefore(this.fakeElement)
          .css({
            position: '',
            height: '',
            width: '',
          })
          .removeClass(this.options.resetAppearanceClass);
      } else {
        this.realElement.removeClass(this.options.hiddenClass);
        if (this.realElement.is('[jcf-size]')) {
          this.realElement.removeAttr('size jcf-size');
        }
      }

      // removing element will also remove its event handlers
      this.fakeElement.remove();

      // remove other event handlers
      this.doc.off('jcf-pointerup', this.onSelectAreaRelease);
      this.realElement.off({
        focus: this.onFocus,
      });
    },
  });

  // listbox module
  function ListBox(options) {
    this.options = $.extend(
      {
        wrapNative: true,
        useCustomScroll: true,
        fakeStructure:
          '<span class="jcf-list-box"><span class="jcf-list-wrapper"></span></span>',
        selectClassPrefix: 'jcf-select-',
        listHolder: '.jcf-list-wrapper',
      },
      options
    );
    this.init();
  }

  $.extend(ListBox.prototype, {
    init: function () {
      this.bindHandlers();
      this.initStructure();
      this.attachEvents();
    },
    initStructure: function () {
      this.realElement = $(this.options.element);
      this.fakeElement = $(this.options.fakeStructure).insertAfter(
        this.realElement
      );
      this.listHolder = this.fakeElement.find(this.options.listHolder);
      makeUnselectable(this.fakeElement);

      // copy classes from original select
      this.fakeElement.addClass(
        getPrefixedClasses(
          this.realElement.prop('className'),
          this.options.selectClassPrefix
        )
      );
      this.realElement.addClass(this.options.hiddenClass);

      this.list = new SelectList({
        useCustomScroll: this.options.useCustomScroll,
        holder: this.listHolder,
        selectOnClick: false,
        element: this.realElement,
      });
    },
    attachEvents: function () {
      // delayed refresh handler
      var self = this;
      this.delayedRefresh = function (e) {
        if (e && e.which === 16) {
          // ignore SHIFT key

        } else {
          clearTimeout(self.refreshTimer);
          self.refreshTimer = setTimeout(function () {
            self.refresh();
            self.list.scrollToActiveOption();
          }, 1);
        }
      };

      // other event handlers
      this.realElement.on({
        focus: this.onFocus,
        click: this.delayedRefresh,
        keydown: this.delayedRefresh,
      });

      // select list event handlers
      $(this.list).on({
        select: this.onSelect,
        press: this.onFakeOptionsPress,
        release: this.onFakeOptionsRelease,
      });
    },
    onFakeOptionsPress: function (e, pointerEvent) {
      this.pressedFlag = true;
      if (pointerEvent.pointerType === 'mouse') {
        this.realElement.focus();
      }
    },
    onFakeOptionsRelease: function (e, pointerEvent) {
      this.pressedFlag = false;
      if (pointerEvent.pointerType === 'mouse') {
        this.realElement.focus();
      }
    },
    onSelect: function () {
      this.fireNativeEvent(this.realElement, 'change');
      this.fireNativeEvent(this.realElement, 'click');
    },
    onFocus: function () {
      if (!this.pressedFlag || !this.focusedFlag) {
        this.fakeElement.addClass(this.options.focusClass);
        this.realElement.on('blur', this.onBlur);
        this.focusedFlag = true;
      }
    },
    onBlur: function () {
      if (!this.pressedFlag) {
        this.fakeElement.removeClass(this.options.focusClass);
        this.realElement.off('blur', this.onBlur);
        this.focusedFlag = false;
      }
    },
    refresh: function () {
      this.fakeElement.toggleClass(
        this.options.disabledClass,
        this.realElement.is(':disabled')
      );
      this.list.refresh();
    },
    destroy: function () {
      this.list.destroy();
      this.realElement
        .insertBefore(this.fakeElement)
        .removeClass(this.options.hiddenClass);
      this.fakeElement.remove();
    },
  });

  // options list module
  function SelectList(options) {
    this.options = $.extend(
      {
        holder: null,
        maxVisibleItems: 10,
        selectOnClick: true,
        useHoverClass: false,
        useCustomScroll: false,
        handleResize: true,
        multipleSelectWithoutKey: false,
        alwaysPreventMouseWheel: false,
        indexAttribute: 'data-index',
        cloneClassPrefix: 'jcf-option-',
        containerStructure:
          '<span class="jcf-list"><span class="jcf-list-content"></span></span>',
        containerSelector: '.jcf-list-content',
        captionClass: 'jcf-optgroup-caption',
        disabledClass: 'jcf-disabled',
        optionClass: 'jcf-option',
        groupClass: 'jcf-optgroup',
        hoverClass: 'jcf-hover',
        selectedClass: 'jcf-selected',
        scrollClass: 'jcf-scroll-active',
      },
      options
    );
    this.init();
  }

  $.extend(SelectList.prototype, {
    init: function () {
      this.initStructure();
      this.refreshSelectedClass();
      this.attachEvents();
    },
    initStructure: function () {
      this.element = $(this.options.element);
      this.indexSelector = '[' + this.options.indexAttribute + ']';
      this.container = $(this.options.containerStructure).appendTo(
        this.options.holder
      );
      this.listHolder = this.container.find(this.options.containerSelector);
      this.lastClickedIndex = this.element.prop('selectedIndex');
      this.rebuildList();
    },
    attachEvents: function () {
      this.bindHandlers();
      this.listHolder.on(
        'jcf-pointerdown',
        this.indexSelector,
        this.onItemPress
      );
      this.listHolder.on('jcf-pointerdown', this.onPress);

      if (this.options.useHoverClass) {
        this.listHolder.on(
          'jcf-pointerover',
          this.indexSelector,
          this.onHoverItem
        );
      }
    },
    onPress: function (e) {
      $(this).trigger('press', e);
      this.listHolder.on('jcf-pointerup', this.onRelease);
    },
    onRelease: function (e) {
      $(this).trigger('release', e);
      this.listHolder.off('jcf-pointerup', this.onRelease);
    },
    onHoverItem: function (e) {
      var hoverIndex = parseFloat(
        e.currentTarget.getAttribute(this.options.indexAttribute)
      );
      this.fakeOptions
        .removeClass(this.options.hoverClass)
        .eq(hoverIndex)
        .addClass(this.options.hoverClass);
    },
    onItemPress: function (e) {
      if (e.pointerType === 'touch' || this.options.selectOnClick) {
        // select option after "click"
        this.tmpListOffsetTop = this.list.offset().top;
        this.listHolder.on(
          'jcf-pointerup',
          this.indexSelector,
          this.onItemRelease
        );
      } else {
        // select option immediately
        this.onSelectItem(e);
      }
    },
    onItemRelease: function (e) {
      // remove event handlers and temporary data
      this.listHolder.off(
        'jcf-pointerup',
        this.indexSelector,
        this.onItemRelease
      );

      // simulate item selection
      if (this.tmpListOffsetTop === this.list.offset().top) {
        this.listHolder.on(
          'click',
          this.indexSelector,
          { savedPointerType: e.pointerType },
          this.onSelectItem
        );
      }
      delete this.tmpListOffsetTop;
    },
    onSelectItem: function (e) {
      var clickedIndex = parseFloat(
          e.currentTarget.getAttribute(this.options.indexAttribute)
        ),
        pointerType =
          (e.data && e.data.savedPointerType) || e.pointerType || 'mouse',
        range;

      // remove click event handler
      this.listHolder.off('click', this.indexSelector, this.onSelectItem);

      // ignore clicks on disabled options
      if (e.button > 1 || this.realOptions[clickedIndex].disabled) {
        return;
      }

      if (this.element.prop('multiple')) {
        if (
          e.metaKey ||
          e.ctrlKey ||
          pointerType === 'touch' ||
          this.options.multipleSelectWithoutKey
        ) {
          // if CTRL/CMD pressed or touch devices - toggle selected option
          this.realOptions[clickedIndex].selected =
            !this.realOptions[clickedIndex].selected;
        } else if (e.shiftKey) {
          // if SHIFT pressed - update selection
          range = [this.lastClickedIndex, clickedIndex].sort(function (a, b) {
            return a - b;
          });
          this.realOptions.each(function (index, option) {
            option.selected = index >= range[0] && index <= range[1];
          });
        } else {
          // set single selected index
          this.element.prop('selectedIndex', clickedIndex);
        }
      } else {
        this.element.prop('selectedIndex', clickedIndex);
      }

      // save last clicked option
      if (!e.shiftKey) {
        this.lastClickedIndex = clickedIndex;
      }

      // refresh classes
      this.refreshSelectedClass();

      // scroll to active item in desktop browsers
      if (pointerType === 'mouse') {
        this.scrollToActiveOption();
      }

      // make callback when item selected
      $(this).trigger('select');
    },
    rebuildList: function () {
      // rebuild options
      var self = this,
        rootElement = this.element[0];

      // recursively create fake options
      this.storedSelectHTML = rootElement.innerHTML;
      this.optionIndex = 0;
      this.list = $(this.createOptionsList(rootElement));
      this.listHolder.empty().append(this.list);
      this.realOptions = this.element.find('option');
      this.fakeOptions = this.list.find(this.indexSelector);
      this.fakeListItems = this.list.find(
        '.' + this.options.captionClass + ',' + this.indexSelector
      );
      delete this.optionIndex;

      // detect max visible items
      var maxCount = this.options.maxVisibleItems,
        sizeValue = this.element.prop('size');
      if (sizeValue > 1 && !this.element.is('[jcf-size]')) {
        maxCount = sizeValue;
      }

      // handle scrollbar
      var needScrollBar = this.fakeOptions.length > maxCount;
      this.container.toggleClass(this.options.scrollClass, needScrollBar);
      if (needScrollBar) {
        // change max-height
        this.listHolder.css({
          maxHeight: this.getOverflowHeight(maxCount),
          overflow: 'auto',
        });

        if (this.options.useCustomScroll && jcf.modules.Scrollable) {
          // add custom scrollbar if specified in options
          jcf.replace(this.listHolder, 'Scrollable', {
            handleResize: this.options.handleResize,
            alwaysPreventMouseWheel: this.options.alwaysPreventMouseWheel,
          });
          return;
        }
      }

      // disable edge wheel scrolling
      if (this.options.alwaysPreventMouseWheel) {
        this.preventWheelHandler = function (e) {
          var currentScrollTop = self.listHolder.scrollTop(),
            maxScrollTop =
              self.listHolder.prop('scrollHeight') -
              self.listHolder.innerHeight();

          // check edge cases
          if (
            (currentScrollTop <= 0 && e.deltaY < 0) ||
            (currentScrollTop >= maxScrollTop && e.deltaY > 0)
          ) {
            e.preventDefault();
          }
        };
        this.listHolder.on('jcf-mousewheel', this.preventWheelHandler);
      }
    },
    refreshSelectedClass: function () {
      var self = this,
        selectedItem,
        isMultiple = this.element.prop('multiple'),
        selectedIndex = this.element.prop('selectedIndex');

      if (isMultiple) {
        this.realOptions.each(function (index, option) {
          self.fakeOptions
            .eq(index)
            .toggleClass(self.options.selectedClass, !!option.selected);
        });
      } else {
        this.fakeOptions.removeClass(
          this.options.selectedClass + ' ' + this.options.hoverClass
        );
        selectedItem = this.fakeOptions
          .eq(selectedIndex)
          .addClass(this.options.selectedClass);
        if (this.options.useHoverClass) {
          selectedItem.addClass(this.options.hoverClass);
        }
      }
    },
    scrollToActiveOption: function () {
      // scroll to target option
      var targetOffset = this.getActiveOptionOffset();
      if (typeof targetOffset === 'number') {
        this.listHolder.prop('scrollTop', targetOffset);
      }
    },
    getSelectedIndexRange: function () {
      var firstSelected = -1,
        lastSelected = -1;
      this.realOptions.each(function (index, option) {
        if (option.selected) {
          if (firstSelected < 0) {
            firstSelected = index;
          }
          lastSelected = index;
        }
      });
      return [firstSelected, lastSelected];
    },
    getChangedSelectedIndex: function () {
      var selectedIndex = this.element.prop('selectedIndex'),
        targetIndex;

      if (this.element.prop('multiple')) {
        // multiple selects handling
        if (!this.previousRange) {
          this.previousRange = [selectedIndex, selectedIndex];
        }
        this.currentRange = this.getSelectedIndexRange();
        targetIndex =
          this.currentRange[
            this.currentRange[0] !== this.previousRange[0] ? 0 : 1
          ];
        this.previousRange = this.currentRange;
        return targetIndex;
      } else {
        // single choice selects handling
        return selectedIndex;
      }
    },
    getActiveOptionOffset: function () {
      // calc values
      var dropHeight = this.listHolder.height(),
        dropScrollTop = this.listHolder.prop('scrollTop'),
        currentIndex = this.getChangedSelectedIndex(),
        fakeOption = this.fakeOptions.eq(currentIndex),
        fakeOptionOffset = fakeOption.offset().top - this.list.offset().top,
        fakeOptionHeight = fakeOption.innerHeight();

      // scroll list
      if (fakeOptionOffset + fakeOptionHeight >= dropScrollTop + dropHeight) {
        // scroll down (always scroll to option)
        return fakeOptionOffset - dropHeight + fakeOptionHeight;
      } else if (fakeOptionOffset < dropScrollTop) {
        // scroll up to option
        return fakeOptionOffset;
      }
    },
    getOverflowHeight: function (sizeValue) {
      var item = this.fakeListItems.eq(sizeValue - 1),
        listOffset = this.list.offset().top,
        itemOffset = item.offset().top,
        itemHeight = item.innerHeight();

      return itemOffset + itemHeight - listOffset;
    },
    getScrollTop: function () {
      return this.listHolder.scrollTop();
    },
    setScrollTop: function (value) {
      this.listHolder.scrollTop(value);
    },
    createOption: function (option) {
      var newOption = document.createElement('span');
      newOption.className = this.options.optionClass;
      newOption.innerHTML = option.innerHTML;
      newOption.setAttribute(this.options.indexAttribute, this.optionIndex++);

      var optionImage,
        optionImageSrc = option.getAttribute('data-image');
      if (optionImageSrc) {
        optionImage = document.createElement('img');
        optionImage.src = optionImageSrc;
        newOption.insertBefore(optionImage, newOption.childNodes[0]);
      }
      if (option.disabled) {
        newOption.className += ' ' + this.options.disabledClass;
      }
      if (option.className) {
        newOption.className +=
          ' ' +
          getPrefixedClasses(option.className, this.options.cloneClassPrefix);
      }
      return newOption;
    },
    createOptGroup: function (optgroup) {
      var optGroupContainer = document.createElement('span'),
        optGroupName = optgroup.getAttribute('label'),
        optGroupCaption,
        optGroupList;

      // create caption
      optGroupCaption = document.createElement('span');
      optGroupCaption.className = this.options.captionClass;
      optGroupCaption.innerHTML = optGroupName;
      optGroupContainer.appendChild(optGroupCaption);

      // create list of options
      if (optgroup.children.length) {
        optGroupList = this.createOptionsList(optgroup);
        optGroupContainer.appendChild(optGroupList);
      }

      optGroupContainer.className = this.options.groupClass;
      return optGroupContainer;
    },
    createOptionContainer: function () {
      var optionContainer = document.createElement('li');
      return optionContainer;
    },
    createOptionsList: function (container) {
      var self = this,
        list = document.createElement('ul');

      $.each(container.children, function (index, currentNode) {
        var item = self.createOptionContainer(currentNode),
          newNode;

        switch (currentNode.tagName.toLowerCase()) {
          case 'option':
            newNode = self.createOption(currentNode);
            break;
          case 'optgroup':
            newNode = self.createOptGroup(currentNode);
            break;
        }
        list.appendChild(item).appendChild(newNode);
      });
      return list;
    },
    refresh: function () {
      // check for select innerHTML changes
      if (this.storedSelectHTML !== this.element.prop('innerHTML')) {
        this.rebuildList();
      }

      // refresh custom scrollbar
      var scrollInstance = jcf.getInstance(this.listHolder);
      if (scrollInstance) {
        scrollInstance.refresh();
      }

      // refresh selectes classes
      this.refreshSelectedClass();
    },
    destroy: function () {
      this.listHolder.off('jcf-mousewheel', this.preventWheelHandler);
      this.listHolder.off(
        'jcf-pointerdown',
        this.indexSelector,
        this.onSelectItem
      );
      this.listHolder.off(
        'jcf-pointerover',
        this.indexSelector,
        this.onHoverItem
      );
      this.listHolder.off('jcf-pointerdown', this.onPress);
    },
  });

  // helper functions
  var getPrefixedClasses = function (className, prefixToAdd) {
    return className
      ? className.replace(/[\s]*([\S]+)+[\s]*/gi, prefixToAdd + '$1 ')
      : '';
  };
  var makeUnselectable = (function () {
    var unselectableClass = jcf.getOptions().unselectableClass;

    function preventHandler(e) {
      e.preventDefault();
    }

    return function (node) {
      node.addClass(unselectableClass).on('selectstart', preventHandler);
    };
  })();
})(jQuery, this);

/*!
 * JavaScript Custom Forms : Radio Module
 *
 * Copyright 2014-2015 PSD2HTML - http://psd2html.com/jcf
 * Released under the MIT license (LICENSE.txt)
 *
 * Version: 1.1.3
 */
(function ($) {
  'use strict';

  jcf.addModule({
    name: 'Radio',
    selector: 'input[type="radio"]',
    options: {
      wrapNative: true,
      checkedClass: 'jcf-checked',
      uncheckedClass: 'jcf-unchecked',
      labelActiveClass: 'jcf-label-active',
      fakeStructure: '<span class="jcf-radio"><span></span></span>',
    },
    matchElement: function (element) {
      return element.is(':radio');
    },
    init: function () {
      this.initStructure();
      this.attachEvents();
      this.refresh();
    },
    initStructure: function () {
      // prepare structure
      this.doc = $(document);
      this.realElement = $(this.options.element);
      this.fakeElement = $(this.options.fakeStructure).insertAfter(
        this.realElement
      );
      this.labelElement = this.getLabelFor();

      if (this.options.wrapNative) {
        // wrap native radio inside fake block
        this.realElement.prependTo(this.fakeElement).css({
          position: 'absolute',
          opacity: 0,
        });
      } else {
        // just hide native radio
        this.realElement.addClass(this.options.hiddenClass);
      }
    },
    attachEvents: function () {
      // add event handlers
      this.realElement.on({
        focus: this.onFocus,
        click: this.onRealClick,
      });
      this.fakeElement.on('click', this.onFakeClick);
      this.fakeElement.on('jcf-pointerdown', this.onPress);
    },
    onRealClick: function (e) {
      // redraw current radio and its group (setTimeout handles click that might be prevented)
      var self = this;
      this.savedEventObject = e;
      setTimeout(function () {
        self.refreshRadioGroup();
      }, 0);
    },
    onFakeClick: function (e) {
      // skip event if clicked on real element inside wrapper
      if (this.options.wrapNative && this.realElement.is(e.target)) {
        return;
      }

      // toggle checked class
      if (!this.realElement.is(':disabled')) {
        delete this.savedEventObject;
        this.currentActiveRadio = this.getCurrentActiveRadio();
        this.stateChecked = this.realElement.prop('checked');
        this.realElement.prop('checked', true);
        this.fireNativeEvent(this.realElement, 'click');
        if (
          this.savedEventObject &&
          this.savedEventObject.isDefaultPrevented()
        ) {
          this.realElement.prop('checked', this.stateChecked);
          this.currentActiveRadio.prop('checked', true);
        } else {
          this.fireNativeEvent(this.realElement, 'change');
        }
        delete this.savedEventObject;
      }
    },
    onFocus: function () {
      if (!this.pressedFlag || !this.focusedFlag) {
        this.focusedFlag = true;
        this.fakeElement.addClass(this.options.focusClass);
        this.realElement.on('blur', this.onBlur);
      }
    },
    onBlur: function () {
      if (!this.pressedFlag) {
        this.focusedFlag = false;
        this.fakeElement.removeClass(this.options.focusClass);
        this.realElement.off('blur', this.onBlur);
      }
    },
    onPress: function (e) {
      if (!this.focusedFlag && e.pointerType === 'mouse') {
        this.realElement.focus();
      }
      this.pressedFlag = true;
      this.fakeElement.addClass(this.options.pressedClass);
      this.doc.on('jcf-pointerup', this.onRelease);
    },
    onRelease: function (e) {
      if (this.focusedFlag && e.pointerType === 'mouse') {
        this.realElement.focus();
      }
      this.pressedFlag = false;
      this.fakeElement.removeClass(this.options.pressedClass);
      this.doc.off('jcf-pointerup', this.onRelease);
    },
    getCurrentActiveRadio: function () {
      return this.getRadioGroup(this.realElement).filter(':checked');
    },
    getRadioGroup: function (radio) {
      // find radio group for specified radio button
      var name = radio.attr('name'),
        parentForm = radio.parents('form');

      if (name) {
        if (parentForm.length) {
          return parentForm.find('input[name="' + name + '"]');
        } else {
          return $('input[name="' + name + '"]:not(form input)');
        }
      } else {
        return radio;
      }
    },
    getLabelFor: function () {
      var parentLabel = this.realElement.closest('label'),
        elementId = this.realElement.prop('id');

      if (!parentLabel.length && elementId) {
        parentLabel = $('label[for="' + elementId + '"]');
      }
      return parentLabel.length ? parentLabel : null;
    },
    refreshRadioGroup: function () {
      // redraw current radio and its group
      this.getRadioGroup(this.realElement).each(function () {
        jcf.refresh(this);
      });
    },
    refresh: function () {
      // redraw current radio button
      var isChecked = this.realElement.is(':checked'),
        isDisabled = this.realElement.is(':disabled');

      this.fakeElement
        .toggleClass(this.options.checkedClass, isChecked)
        .toggleClass(this.options.uncheckedClass, !isChecked)
        .toggleClass(this.options.disabledClass, isDisabled);

      if (this.labelElement) {
        this.labelElement.toggleClass(this.options.labelActiveClass, isChecked);
      }
    },
    destroy: function () {
      // restore structure
      if (this.options.wrapNative) {
        this.realElement.insertBefore(this.fakeElement).css({
          position: '',
          width: '',
          height: '',
          opacity: '',
          margin: '',
        });
      } else {
        this.realElement.removeClass(this.options.hiddenClass);
      }

      // removing element will also remove its event handlers
      this.fakeElement.off('jcf-pointerdown', this.onPress);
      this.fakeElement.remove();

      // remove other event handlers
      this.doc.off('jcf-pointerup', this.onRelease);
      this.realElement.off({
        blur: this.onBlur,
        focus: this.onFocus,
        click: this.onRealClick,
      });
    },
  });
})(jQuery);

/*!
 * JavaScript Custom Forms : Checkbox Module
 *
 * Copyright 2014-2015 PSD2HTML - http://psd2html.com/jcf
 * Released under the MIT license (LICENSE.txt)
 *
 * Version: 1.1.3
 */
(function ($) {
  'use strict';

  jcf.addModule({
    name: 'Checkbox',
    selector: 'input[type="checkbox"]',
    options: {
      wrapNative: true,
      checkedClass: 'jcf-checked',
      uncheckedClass: 'jcf-unchecked',
      labelActiveClass: 'jcf-label-active',
      fakeStructure: '<span class="jcf-checkbox"><span></span></span>',
    },
    matchElement: function (element) {
      return element.is(':checkbox');
    },
    init: function () {
      this.initStructure();
      this.attachEvents();
      this.refresh();
    },
    initStructure: function () {
      // prepare structure
      this.doc = $(document);
      this.realElement = $(this.options.element);
      this.fakeElement = $(this.options.fakeStructure).insertAfter(
        this.realElement
      );
      this.labelElement = this.getLabelFor();

      if (this.options.wrapNative) {
        // wrap native checkbox inside fake block
        this.realElement.appendTo(this.fakeElement).css({
          position: 'absolute',
          height: '100%',
          width: '100%',
          opacity: 0,
          margin: 0,
        });
      } else {
        // just hide native checkbox
        this.realElement.addClass(this.options.hiddenClass);
      }
    },
    attachEvents: function () {
      // add event handlers
      this.realElement.on({
        focus: this.onFocus,
        click: this.onRealClick,
      });
      this.fakeElement.on('click', this.onFakeClick);
      this.fakeElement.on('jcf-pointerdown', this.onPress);
    },
    onRealClick: function (e) {
      // just redraw fake element (setTimeout handles click that might be prevented)
      var self = this;
      this.savedEventObject = e;
      setTimeout(function () {
        self.refresh();
      }, 0);
    },
    onFakeClick: function (e) {
      // skip event if clicked on real element inside wrapper
      if (this.options.wrapNative && this.realElement.is(e.target)) {
        return;
      }

      // toggle checked class
      if (!this.realElement.is(':disabled')) {
        delete this.savedEventObject;
        this.stateChecked = this.realElement.prop('checked');
        this.realElement.prop('checked', !this.stateChecked);
        this.fireNativeEvent(this.realElement, 'click');
        if (
          this.savedEventObject &&
          this.savedEventObject.isDefaultPrevented()
        ) {
          this.realElement.prop('checked', this.stateChecked);
        } else {
          this.fireNativeEvent(this.realElement, 'change');
        }
        delete this.savedEventObject;
      }
    },
    onFocus: function () {
      if (!this.pressedFlag || !this.focusedFlag) {
        this.focusedFlag = true;
        this.fakeElement.addClass(this.options.focusClass);
        this.realElement.on('blur', this.onBlur);
      }
    },
    onBlur: function () {
      if (!this.pressedFlag) {
        this.focusedFlag = false;
        this.fakeElement.removeClass(this.options.focusClass);
        this.realElement.off('blur', this.onBlur);
      }
    },
    onPress: function (e) {
      if (!this.focusedFlag && e.pointerType === 'mouse') {
        this.realElement.focus();
      }
      this.pressedFlag = true;
      this.fakeElement.addClass(this.options.pressedClass);
      this.doc.on('jcf-pointerup', this.onRelease);
    },
    onRelease: function (e) {
      if (this.focusedFlag && e.pointerType === 'mouse') {
        this.realElement.focus();
      }
      this.pressedFlag = false;
      this.fakeElement.removeClass(this.options.pressedClass);
      this.doc.off('jcf-pointerup', this.onRelease);
    },
    getLabelFor: function () {
      var parentLabel = this.realElement.closest('label'),
        elementId = this.realElement.prop('id');

      if (!parentLabel.length && elementId) {
        parentLabel = $('label[for="' + elementId + '"]');
      }
      return parentLabel.length ? parentLabel : null;
    },
    refresh: function () {
      // redraw custom checkbox
      var isChecked = this.realElement.is(':checked'),
        isDisabled = this.realElement.is(':disabled');

      this.fakeElement
        .toggleClass(this.options.checkedClass, isChecked)
        .toggleClass(this.options.uncheckedClass, !isChecked)
        .toggleClass(this.options.disabledClass, isDisabled);

      if (this.labelElement) {
        this.labelElement.toggleClass(this.options.labelActiveClass, isChecked);
      }
    },
    destroy: function () {
      // restore structure
      if (this.options.wrapNative) {
        this.realElement.insertBefore(this.fakeElement).css({
          position: '',
          width: '',
          height: '',
          opacity: '',
          margin: '',
        });
      } else {
        this.realElement.removeClass(this.options.hiddenClass);
      }

      // removing element will also remove its event handlers
      this.fakeElement.off('jcf-pointerdown', this.onPress);
      this.fakeElement.remove();

      // remove other event handlers
      this.doc.off('jcf-pointerup', this.onRelease);
      this.realElement.off({
        focus: this.onFocus,
        click: this.onRealClick,
      });
    },
  });
})(jQuery);

/*
 * Responsive Layout helper
 */
ResponsiveHelper = (function ($) {
  // init variables
  var handlers = [],
    prevWinWidth,
    win = $(window),
    nativeMatchMedia = false;

  // detect match media support
  if (window.matchMedia) {
    if (window.Window && window.matchMedia === Window.prototype.matchMedia) {
      nativeMatchMedia = true;
    } else if (window.matchMedia.toString().indexOf('native') > -1) {
      nativeMatchMedia = true;
    }
  }

  // prepare resize handler
  function resizeHandler() {
    var winWidth = win.width();
    if (winWidth !== prevWinWidth) {
      prevWinWidth = winWidth;

      // loop through range groups
      $.each(handlers, function (index, rangeObject) {
        // disable current active area if needed
        $.each(rangeObject.data, function (property, item) {
          if (item.currentActive && !matchRange(item.range[0], item.range[1])) {
            item.currentActive = false;
            if (typeof item.disableCallback === 'function') {
              item.disableCallback();
            }
          }
        });

        // enable areas that match current width
        $.each(rangeObject.data, function (property, item) {
          if (!item.currentActive && matchRange(item.range[0], item.range[1])) {
            // make callback
            item.currentActive = true;
            if (typeof item.enableCallback === 'function') {
              item.enableCallback();
            }
          }
        });
      });
    }
  }

  win.bind('load resize orientationchange', resizeHandler);

  // test range
  function matchRange(r1, r2) {
    var mediaQueryString = '';
    if (r1 > 0) {
      mediaQueryString += '(min-width: ' + r1 + 'px)';
    }
    if (r2 < Infinity) {
      mediaQueryString +=
        (mediaQueryString ? ' and ' : '') + '(max-width: ' + r2 + 'px)';
    }
    return matchQuery(mediaQueryString, r1, r2);
  }

  // media query function
  function matchQuery(query, r1, r2) {
    if (window.matchMedia && nativeMatchMedia) {
      return matchMedia(query).matches;
    } else if (window.styleMedia) {
      return styleMedia.matchMedium(query);
    } else if (window.media) {
      return media.matchMedium(query);
    } else {
      return prevWinWidth >= r1 && prevWinWidth <= r2;
    }
  }

  // range parser
  function parseRange(rangeStr) {
    var rangeData = rangeStr.split('..');
    var x1 = parseInt(rangeData[0], 10) || -Infinity;
    var x2 = parseInt(rangeData[1], 10) || Infinity;
    return [x1, x2].sort(function (a, b) {
      return a - b;
    });
  }

  // export public functions
  return {
    addRange: function (ranges) {
      // parse data and add items to collection
      var result = { data: {} };
      $.each(ranges, function (property, data) {
        result.data[property] = {
          range: parseRange(property),
          enableCallback: data.on,
          disableCallback: data.off,
        };
      });
      handlers.push(result);

      // call resizeHandler to recalculate all events
      prevWinWidth = null;
      resizeHandler();
    },
  };
})(jQuery);

/*! Picturefill - v2.3.1 - 2015-04-09
 * http://scottjehl.github.io/picturefill
 * Copyright (c) 2015 https://github.com/scottjehl/picturefill/blob/master/Authors.txt; Licensed MIT */
document.createElement('picture');
window.matchMedia ||
  (window.matchMedia = (function () {
    'use strict';
    var a = window.styleMedia || window.media;
    if (!a) {
      var b = document.createElement('style'),
        c = document.getElementsByTagName('script')[0],
        d = null;
      (b.type = 'text/css'),
        (b.id = 'matchmediajs-test'),
        c.parentNode.insertBefore(b, c),
        (d =
          ('getComputedStyle' in window && window.getComputedStyle(b, null)) ||
          b.currentStyle),
        (a = {
          matchMedium: function (a) {
            var c = '@media ' + a + '{ #matchmediajs-test { width: 1px; } }';
            return (
              b.styleSheet ? (b.styleSheet.cssText = c) : (b.textContent = c),
              '1px' === d.width
            );
          },
        });
    }
    return function (b) {
      return { matches: a.matchMedium(b || 'all'), media: b || 'all' };
    };
  })()),
  (function (a, b, c) {
    'use strict';

    function d(b) {
      'object' == typeof module && 'object' == typeof module.exports
        ? (module.exports = b)
        : 'function' == typeof define &&
          define.amd &&
          define('picturefill', function () {
            return b;
          }),
        'object' == typeof a && (a.picturefill = b);
    }

    function e(a) {
      var b,
        c,
        d,
        e,
        f,
        i = a || {};
      b = i.elements || g.getAllElements();
      for (var j = 0, k = b.length; k > j; j++)
        if (
          ((c = b[j]),
          (d = c.parentNode),
          (e = void 0),
          (f = void 0),
          'IMG' === c.nodeName.toUpperCase() &&
            (c[g.ns] || (c[g.ns] = {}), i.reevaluate || !c[g.ns].evaluated))
        ) {
          if (d && 'PICTURE' === d.nodeName.toUpperCase()) {
            if ((g.removeVideoShim(d), (e = g.getMatch(c, d)), e === !1))
              continue;
          } else e = void 0;
          ((d && 'PICTURE' === d.nodeName.toUpperCase()) ||
            (!g.sizesSupported && c.srcset && h.test(c.srcset))) &&
            g.dodgeSrcset(c),
            e
              ? ((f = g.processSourceSet(e)), g.applyBestCandidate(f, c))
              : ((f = g.processSourceSet(c)),
                (void 0 === c.srcset || c[g.ns].srcset) &&
                  g.applyBestCandidate(f, c)),
            (c[g.ns].evaluated = !0);
        }
    }

    function f() {
      function c() {
        clearTimeout(d), (d = setTimeout(h, 60));
      }

      g.initTypeDetects(), e();
      var d,
        f = setInterval(function () {
          return (
            e(),
            /^loaded|^i|^c/.test(b.readyState) ? void clearInterval(f) : void 0
          );
        }, 250),
        h = function () {
          e({ reevaluate: !0 });
        };
      a.addEventListener
        ? a.addEventListener('resize', c, !1)
        : a.attachEvent && a.attachEvent('onresize', c);
    }

    if (a.HTMLPictureElement) return void d(function () {});
    b.createElement('picture');
    var g = a.picturefill || {},
      h = /\s+\+?\d+(e\d+)?w/;
    (g.ns = 'picturefill'),
      (function () {
        (g.srcsetSupported = 'srcset' in c),
          (g.sizesSupported = 'sizes' in c),
          (g.curSrcSupported = 'currentSrc' in c);
      })(),
      (g.trim = function (a) {
        return a.trim ? a.trim() : a.replace(/^\s+|\s+$/g, '');
      }),
      (g.makeUrl = (function () {
        var a = b.createElement('a');
        return function (b) {
          return (a.href = b), a.href;
        };
      })()),
      (g.restrictsMixedContent = function () {
        return 'https:' === a.location.protocol;
      }),
      (g.matchesMedia = function (b) {
        return a.matchMedia && a.matchMedia(b).matches;
      }),
      (g.getDpr = function () {
        return a.devicePixelRatio || 1;
      }),
      (g.getWidthFromLength = function (a) {
        var c;
        if (
          !a ||
          a.indexOf('%') > -1 != !1 ||
          !(parseFloat(a) > 0 || a.indexOf('calc(') > -1)
        )
          return !1;
        (a = a.replace('vw', '%')),
          g.lengthEl ||
            ((g.lengthEl = b.createElement('div')),
            (g.lengthEl.style.cssText =
              'border:0;display:block;font-size:1em;left:0;margin:0;padding:0;position:absolute;visibility:hidden'),
            (g.lengthEl.className = 'helper-from-picturefill-js')),
          (g.lengthEl.style.width = '0px');
        try {
          g.lengthEl.style.width = a;
        } catch (d) {}
        return (
          b.body.appendChild(g.lengthEl),
          (c = g.lengthEl.offsetWidth),
          0 >= c && (c = !1),
          b.body.removeChild(g.lengthEl),
          c
        );
      }),
      (g.detectTypeSupport = function (b, c) {
        var d = new a.Image();
        return (
          (d.onerror = function () {
            (g.types[b] = !1), e();
          }),
          (d.onload = function () {
            (g.types[b] = 1 === d.width), e();
          }),
          (d.src = c),
          'pending'
        );
      }),
      (g.types = g.types || {}),
      (g.initTypeDetects = function () {
        (g.types['image/jpeg'] = !0),
          (g.types['image/gif'] = !0),
          (g.types['image/png'] = !0),
          (g.types['image/svg+xml'] = b.implementation.hasFeature(
            'http://www.w3.org/TR/SVG11/feature#Image',
            '1.1'
          )),
          (g.types['image/webp'] = g.detectTypeSupport(
            'image/webp',
            'data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAAAAAAfQ//73v/+BiOh/AAA='
          ));
      }),
      (g.verifyTypeSupport = function (a) {
        var b = a.getAttribute('type');
        if (null === b || '' === b) return !0;
        var c = g.types[b];
        return 'string' == typeof c && 'pending' !== c
          ? ((g.types[b] = g.detectTypeSupport(b, c)), 'pending')
          : 'function' == typeof c
          ? (c(), 'pending')
          : c;
      }),
      (g.parseSize = function (a) {
        var b = /(\([^)]+\))?\s*(.+)/g.exec(a);
        return { media: b && b[1], length: b && b[2] };
      }),
      (g.findWidthFromSourceSize = function (c) {
        for (
          var d, e = g.trim(c).split(/\s*,\s*/), f = 0, h = e.length;
          h > f;
          f++
        ) {
          var i = e[f],
            j = g.parseSize(i),
            k = j.length,
            l = j.media;
          if (k && (!l || g.matchesMedia(l)) && (d = g.getWidthFromLength(k)))
            break;
        }
        return d || Math.max(a.innerWidth || 0, b.documentElement.clientWidth);
      }),
      (g.parseSrcset = function (a) {
        for (var b = []; '' !== a; ) {
          a = a.replace(/^\s+/g, '');
          var c,
            d = a.search(/\s/g),
            e = null;
          if (-1 !== d) {
            c = a.slice(0, d);
            var f = c.slice(-1);
            if (
              ((',' === f || '' === c) &&
                ((c = c.replace(/,+$/, '')), (e = '')),
              (a = a.slice(d + 1)),
              null === e)
            ) {
              var g = a.indexOf(',');
              -1 !== g
                ? ((e = a.slice(0, g)), (a = a.slice(g + 1)))
                : ((e = a), (a = ''));
            }
          } else (c = a), (a = '');
          (c || e) && b.push({ url: c, descriptor: e });
        }
        return b;
      }),
      (g.parseDescriptor = function (a, b) {
        var c,
          d = b || '100vw',
          e = a && a.replace(/(^\s+|\s+$)/g, ''),
          f = g.findWidthFromSourceSize(d);
        if (e)
          for (var h = e.split(' '), i = h.length - 1; i >= 0; i--) {
            var j = h[i],
              k = j && j.slice(j.length - 1);
            if (('h' !== k && 'w' !== k) || g.sizesSupported) {
              if ('x' === k) {
                var l = j && parseFloat(j, 10);
                c = l && !isNaN(l) ? l : 1;
              }
            } else c = parseFloat(parseInt(j, 10) / f);
          }
        return c || 1;
      }),
      (g.getCandidatesFromSourceSet = function (a, b) {
        for (
          var c = g.parseSrcset(a), d = [], e = 0, f = c.length;
          f > e;
          e++
        ) {
          var h = c[e];
          d.push({
            url: h.url,
            resolution: g.parseDescriptor(h.descriptor, b),
          });
        }
        return d;
      }),
      (g.dodgeSrcset = function (a) {
        a.srcset &&
          ((a[g.ns].srcset = a.srcset),
          (a.srcset = ''),
          a.setAttribute('data-pfsrcset', a[g.ns].srcset));
      }),
      (g.processSourceSet = function (a) {
        var b = a.getAttribute('srcset'),
          c = a.getAttribute('sizes'),
          d = [];
        return (
          'IMG' === a.nodeName.toUpperCase() &&
            a[g.ns] &&
            a[g.ns].srcset &&
            (b = a[g.ns].srcset),
          b && (d = g.getCandidatesFromSourceSet(b, c)),
          d
        );
      }),
      (g.backfaceVisibilityFix = function (a) {
        var b = a.style || {},
          c = 'webkitBackfaceVisibility' in b,
          d = b.zoom;
        c && ((b.zoom = '.999'), (c = a.offsetWidth), (b.zoom = d));
      }),
      (g.setIntrinsicSize = (function () {
        var c = {},
          d = function (a, b, c) {
            b && a.setAttribute('width', parseInt(b / c, 10));
          };
        return function (e, f) {
          var h;
          e[g.ns] &&
            !a.pfStopIntrinsicSize &&
            (void 0 === e[g.ns].dims &&
              (e[g.ns].dims =
                e.getAttribute('width') || e.getAttribute('height')),
            e[g.ns].dims ||
              (f.url in c
                ? d(e, c[f.url], f.resolution)
                : ((h = b.createElement('img')),
                  (h.onload = function () {
                    if (((c[f.url] = h.width), !c[f.url]))
                      try {
                        b.body.appendChild(h),
                          (c[f.url] = h.width || h.offsetWidth),
                          b.body.removeChild(h);
                      } catch (a) {}
                    e.src === f.url && d(e, c[f.url], f.resolution),
                      (e = null),
                      (h.onload = null),
                      (h = null);
                  }),
                  (h.src = f.url))));
        };
      })()),
      (g.applyBestCandidate = function (a, b) {
        var c, d, e;
        a.sort(g.ascendingSort), (d = a.length), (e = a[d - 1]);
        for (var f = 0; d > f; f++)
          if (((c = a[f]), c.resolution >= g.getDpr())) {
            e = c;
            break;
          }
        e &&
          ((e.url = g.makeUrl(e.url)),
          b.src !== e.url &&
            (g.restrictsMixedContent() &&
            'http:' === e.url.substr(0, 'http:'.length).toLowerCase()
              ? void 0 !== window.console &&
                console.warn('Blocked mixed content image ' + e.url)
              : ((b.src = e.url),
                g.curSrcSupported || (b.currentSrc = b.src),
                g.backfaceVisibilityFix(b))),
          g.setIntrinsicSize(b, e));
      }),
      (g.ascendingSort = function (a, b) {
        return a.resolution - b.resolution;
      }),
      (g.removeVideoShim = function (a) {
        var b = a.getElementsByTagName('video');
        if (b.length) {
          for (var c = b[0], d = c.getElementsByTagName('source'); d.length; )
            a.insertBefore(d[0], c);
          c.parentNode.removeChild(c);
        }
      }),
      (g.getAllElements = function () {
        for (
          var a = [], c = b.getElementsByTagName('img'), d = 0, e = c.length;
          e > d;
          d++
        ) {
          var f = c[d];
          ('PICTURE' === f.parentNode.nodeName.toUpperCase() ||
            null !== f.getAttribute('srcset') ||
            (f[g.ns] && null !== f[g.ns].srcset)) &&
            a.push(f);
        }
        return a;
      }),
      (g.getMatch = function (a, b) {
        for (var c, d = b.childNodes, e = 0, f = d.length; f > e; e++) {
          var h = d[e];
          if (1 === h.nodeType) {
            if (h === a) return c;
            if ('SOURCE' === h.nodeName.toUpperCase()) {
              null !== h.getAttribute('src') &&
                void 0 !== typeof console &&
                console.warn(
                  'The `src` attribute is invalid on `picture` `source` element; instead, use `srcset`.'
                );
              var i = h.getAttribute('media');
              if (h.getAttribute('srcset') && (!i || g.matchesMedia(i))) {
                var j = g.verifyTypeSupport(h);
                if (j === !0) {
                  c = h;
                  break;
                }
                if ('pending' === j) return !1;
              }
            }
          }
        }
        return c;
      }),
      f(),
      (e._ = g),
      d(e);
  })(window, window.document, new window.Image());
!function(e){"use strict";var t={i18n:{ru:{months:["Январь","Февраль","Март","Апрель","Май","Июнь","Июль","Август","Сентябрь","Октябрь","Ноябрь","Декабрь"],dayOfWeek:["Вск","Пн","Вт","Ср","Чт","Пт","Сб"]},en:{months:["January","February","March","April","May","June","July","August","September","October","November","December"],dayOfWeek:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]},de:{months:["Januar","Februar","März","April","Mai","Juni","Juli","August","September","Oktober","November","Dezember"],dayOfWeek:["So","Mo","Di","Mi","Do","Fr","Sa"]},nl:{months:["januari","februari","maart","april","mei","juni","juli","augustus","september","oktober","november","december"],dayOfWeek:["zo","ma","di","wo","do","vr","za"]},tr:{months:["Ocak","Şubat","Mart","Nisan","Mayıs","Haziran","Temmuz","Ağustos","Eylül","Ekim","Kasım","Aralık"],dayOfWeek:["Paz","Pts","Sal","Çar","Per","Cum","Cts"]},fr:{months:["Janvier","Février","Mars","Avril","Mai","Juin","Juillet","Août","Septembre","Octobre","Novembre","Décembre"],dayOfWeek:["Dim","Lun","Mar","Mer","Jeu","Ven","Sam"]},es:{months:["Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"],dayOfWeek:["Dom","Lun","Mar","Mié","Jue","Vie","Sáb"]},th:{months:["มกราคม","กุมภาพันธ์","มีนาคม","เมษายน","พฤษภาคม","มิถุนายน","กรกฎาคม","สิงหาคม","กันยายน","ตุลาคม","พฤศจิกายน","ธันวาคม"],dayOfWeek:["อา.","จ.","อ.","พ.","พฤ.","ศ.","ส."]},pl:{months:["styczeń","luty","marzec","kwiecień","maj","czerwiec","lipiec","sierpień","wrzesień","październik","listopad","grudzień"],dayOfWeek:["nd","pn","wt","śr","cz","pt","sb"]},pt:{months:["Janeiro","Fevereiro","Março","Abril","Maio","Junho","Julho","Agosto","Setembro","Outubro","Novembro","Dezembro"],dayOfWeek:["Dom","Seg","Ter","Qua","Qui","Sex","Sab"]},ch:{months:["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],dayOfWeek:["日","一","二","三","四","五","六"]},se:{months:["Januari","Februari","Mars","April","Maj","Juni","Juli","Augusti","September","Oktober","November","December"],dayOfWeek:["Sön","Mån","Tis","Ons","Tor","Fre","Lör"]},kr:{months:["1월","2월","3월","4월","5월","6월","7월","8월","9월","10월","11월","12월"],dayOfWeek:["일","월","화","수","목","금","토"]},it:{months:["Gennaio","Febbraio","Marzo","Aprile","Maggio","Giugno","Luglio","Agosto","Settembre","Ottobre","Novembre","Dicembre"],dayOfWeek:["Dom","Lun","Mar","Mer","Gio","Ven","Sab"]},da:{months:["January","Februar","Marts","April","Maj","Juni","July","August","September","Oktober","November","December"],dayOfWeek:["Søn","Man","Tir","ons","Tor","Fre","lør"]},ja:{months:["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],dayOfWeek:["日","月","火","水","木","金","土"]},vi:{months:["Tháng 1","Tháng 2","Tháng 3","Tháng 4","Tháng 5","Tháng 6","Tháng 7","Tháng 8","Tháng 9","Tháng 10","Tháng 11","Tháng 12"],dayOfWeek:["CN","T2","T3","T4","T5","T6","T7"]}},value:"",lang:"en",format:"Y/m/d H:i",formatTime:"H:i",formatDate:"Y/m/d",startDate:!1,step:60,closeOnDateSelect:!1,closeOnWithoutClick:!0,timepicker:!0,datepicker:!0,minDate:!1,maxDate:!1,minTime:!1,maxTime:!1,allowTimes:[],opened:!1,initTime:!0,inline:!1,onSelectDate:function(){},onSelectTime:function(){},onChangeMonth:function(){},onChangeDateTime:function(){},onShow:function(){},onClose:function(){},onGenerate:function(){},withoutCopyright:!0,inverseButton:!1,hours12:!1,next:"xdsoft_next",prev:"xdsoft_prev",dayOfWeekStart:0,timeHeightInTimePicker:25,timepickerScrollbar:!0,todayButton:!0,defaultSelect:!0,scrollMonth:!0,scrollTime:!0,scrollInput:!0,lazyInit:!1,mask:!1,validateOnBlur:!0,allowBlank:!0,yearStart:1950,yearEnd:2050,style:"",id:"",roundTime:"round",className:"",weekends:[],yearOffset:0};Array.prototype.indexOf||(Array.prototype.indexOf=function(e,t){for(var n=t||0,a=this.length;n<a;n++)if(this[n]===e)return n;return-1}),e.fn.xdsoftScroller=function(t){return this.each(function(){var n=e(this);if(!e(this).hasClass("xdsoft_scroller_box")){var a=function(e){var t={x:0,y:0};if("touchstart"==e.type||"touchmove"==e.type||"touchend"==e.type||"touchcancel"==e.type){var n=e.originalEvent.touches[0]||e.originalEvent.changedTouches[0];t.x=n.pageX,t.y=n.pageY}else"mousedown"!=e.type&&"mouseup"!=e.type&&"mousemove"!=e.type&&"mouseover"!=e.type&&"mouseout"!=e.type&&"mouseenter"!=e.type&&"mouseleave"!=e.type||(t.x=e.pageX,t.y=e.pageY);return t},r=0,o=n.children().eq(0),s=n[0].clientHeight,i=o[0].offsetHeight,d=e('<div class="xdsoft_scrollbar"></div>'),u=e('<div class="xdsoft_scroller"></div>'),c=100,l=!1;d.append(u),n.addClass("xdsoft_scroller_box").append(d),u.on("mousedown.xdsoft_scroller",function(a){s||n.trigger("resize_scroll.xdsoft_scroller",[t]);var o=a.pageY,i=parseInt(u.css("margin-top")),l=d[0].offsetHeight;e(document.body).addClass("xdsoft_noselect"),e([document.body,window]).on("mouseup.xdsoft_scroller",function f(){e([document.body,window]).off("mouseup.xdsoft_scroller",f).off("mousemove.xdsoft_scroller",r).removeClass("xdsoft_noselect")}),e(document.body).on("mousemove.xdsoft_scroller",r=function(e){var t=e.pageY-o+i;t<0&&(t=0),t+u[0].offsetHeight>l&&(t=l-u[0].offsetHeight),n.trigger("scroll_element.xdsoft_scroller",[c?t/c:0])})}),n.on("scroll_element.xdsoft_scroller",function(e,t){s||n.trigger("resize_scroll.xdsoft_scroller",[t,!0]),t=t>1?1:t<0||isNaN(t)?0:t,u.css("margin-top",c*t),o.css("marginTop",-parseInt((i-s)*t))}).on("resize_scroll.xdsoft_scroller",function(e,t,a){s=n[0].clientHeight,i=o[0].offsetHeight;var r=s/i,l=r*d[0].offsetHeight;r>1?u.hide():(u.show(),u.css("height",parseInt(l>10?l:10)),c=d[0].offsetHeight-u[0].offsetHeight,a!==!0&&n.trigger("scroll_element.xdsoft_scroller",[t?t:Math.abs(parseInt(o.css("marginTop")))/(i-s)]))}),n.mousewheel&&n.mousewheel(function(e,t,a,r){var d=Math.abs(parseInt(o.css("marginTop")));return n.trigger("scroll_element.xdsoft_scroller",[(d-20*t)/(i-s)]),e.stopPropagation(),!1}),n.on("touchstart",function(e){l=a(e)}),n.on("touchmove",function(e){if(l){var t=a(e),r=Math.abs(parseInt(o.css("marginTop")));n.trigger("scroll_element.xdsoft_scroller",[(r-(t.y-l.y))/(i-s)]),e.stopPropagation(),e.preventDefault()}}),n.on("touchend touchcancel",function(e){l=!1})}n.trigger("resize_scroll.xdsoft_scroller",[t])})},e.fn.datetimepicker=function(n){var a=48,r=57,o=96,s=105,i=17,d=46,u=13,c=27,l=8,f=37,m=38,h=39,g=40,p=9,x=116,v=65,y=67,D=86,T=90,w=89,b=!1,_=e.isPlainObject(n)||!n?e.extend(!0,{},t,n):e.extend({},t),M=0,k=function(e){e.on("open.xdsoft focusin.xdsoft mousedown.xdsoft",function t(n){e.is(":disabled")||e.is(":hidden")||!e.is(":visible")||e.data("xdsoft_datetimepicker")||(clearTimeout(M),M=setTimeout(function(){e.data("xdsoft_datetimepicker")||S(e),e.off("open.xdsoft focusin.xdsoft mousedown.xdsoft",t).trigger("open.xdsoft")},100))})},S=function(t){function n(){var e=_.value?_.value:t&&t.val&&t.val()?t.val():"";return e&&W.isValidDate(e=Date.parseDate(e,_.format))?M.data("changed",!0):e="",e||_.startDate===!1||(e=W.strToDateTime(_.startDate)),e?e:0}var M=e("<div "+(_.id?'id="'+_.id+'"':"")+" "+(_.style?'style="'+_.style+'"':"")+' class="xdsoft_datetimepicker xdsoft_noselect '+_.className+'"></div>'),k=e('<div class="xdsoft_copyright"><a target="_blank" href="http://xdsoft.net/jqplugins/datetimepicker/">xdsoft.net</a></div>'),S=e('<div class="xdsoft_datepicker active"></div>'),O=e('<div class="xdsoft_mounthpicker"><button type="button" class="xdsoft_prev"></button><button type="button" class="xdsoft_today_button"></button><div class="xdsoft_label xdsoft_month"><span></span></div><div class="xdsoft_label xdsoft_year"><span></span></div><button type="button" class="xdsoft_next"></button></div>'),F=e('<div class="xdsoft_calendar"></div>'),I=e('<div class="xdsoft_timepicker active"><button type="button" class="xdsoft_prev"></button><div class="xdsoft_time_box"></div><button type="button" class="xdsoft_next"></button></div>'),C=I.find(".xdsoft_time_box").eq(0),H=e('<div class="xdsoft_time_variant"></div>'),Y=e('<div class="xdsoft_scrollbar"></div>'),P=(e('<div class="xdsoft_scroller"></div>'),e('<div class="xdsoft_select xdsoft_monthselect"><div></div></div>')),A=e('<div class="xdsoft_select xdsoft_yearselect"><div></div></div>');O.find(".xdsoft_month span").after(P),O.find(".xdsoft_year span").after(A),O.find(".xdsoft_month,.xdsoft_year").on("mousedown.xdsoft",function(t){O.find(".xdsoft_select").hide();var n=e(this).find(".xdsoft_select").eq(0),a=0,r=0;W.currentTime&&(a=W.currentTime[e(this).hasClass("xdsoft_month")?"getMonth":"getFullYear"]()),n.show();for(var o=n.find("div.xdsoft_option"),s=0;s<o.length&&o.eq(s).data("value")!=a;s++)r+=o[0].offsetHeight;return n.xdsoftScroller(r/(n.children()[0].offsetHeight-n[0].clientHeight)),t.stopPropagation(),!1}),O.find(".xdsoft_select").xdsoftScroller().on("mousedown.xdsoft",function(e){e.stopPropagation(),e.preventDefault()}).on("mousedown.xdsoft",".xdsoft_option",function(t){W&&W.currentTime&&W.currentTime[e(this).parent().parent().hasClass("xdsoft_monthselect")?"setMonth":"setFullYear"](e(this).data("value")),e(this).parent().parent().hide(),M.trigger("xchange.xdsoft"),_.onChangeMonth&&_.onChangeMonth.call&&_.onChangeMonth.call(M,W.currentTime,M.data("input"))}),M.setOptions=function(n){if(_=e.extend(!0,{},_,n),n.allowTimes&&e.isArray(n.allowTimes)&&n.allowTimes.length&&(_.allowTimes=e.extend(!0,[],n.allowTimes)),n.weekends&&e.isArray(n.weekends)&&n.weekends.length&&(_.weekends=e.extend(!0,[],n.weekends)),!_.open&&!_.opened||_.inline||t.trigger("open.xdsoft"),_.inline&&(M.addClass("xdsoft_inline"),t.after(M).hide(),M.trigger("afterOpen.xdsoft")),_.inverseButton&&(_.next="xdsoft_prev",_.prev="xdsoft_next"),_.datepicker?S.addClass("active"):S.removeClass("active"),_.timepicker?I.addClass("active"):I.removeClass("active"),_.value&&(t&&t.val&&t.val(_.value),W.setCurrentTime(_.value)),isNaN(_.dayOfWeekStart)||parseInt(_.dayOfWeekStart)<0||parseInt(_.dayOfWeekStart)>6?_.dayOfWeekStart=0:_.dayOfWeekStart=parseInt(_.dayOfWeekStart),_.timepickerScrollbar||Y.hide(),_.minDate&&/^-(.*)$/.test(_.minDate)&&(_.minDate=W.strToDateTime(_.minDate).dateFormat(_.formatDate)),_.maxDate&&/^\+(.*)$/.test(_.maxDate)&&(_.maxDate=W.strToDateTime(_.maxDate).dateFormat(_.formatDate)),O.find(".xdsoft_today_button").css("visibility",_.todayButton?"visible":"hidden"),_.mask){var k=function(e){try{if(document.selection&&document.selection.createRange){var t=document.selection.createRange();return t.getBookmark().charCodeAt(2)-2}if(e.setSelectionRange)return e.selectionStart}catch(n){return 0}},F=function(e,t){var e="string"==typeof e||e instanceof String?document.getElementById(e):e;if(!e)return!1;if(e.createTextRange){var n=e.createTextRange();return n.collapse(!0),n.moveEnd(t),n.moveStart(t),n.select(),!0}return!!e.setSelectionRange&&(e.setSelectionRange(t,t),!0)},C=function(e,t){var n=e.replace(/([\[\]\/\{\}\(\)\-\.\+]{1})/g,"\\$1").replace(/_/g,"{digit+}").replace(/([0-9]{1})/g,"{digit$1}").replace(/\{digit([0-9]{1})\}/g,"[0-$1_]{1}").replace(/\{digit[\+]\}/g,"[0-9_]{1}");return RegExp(n).test(t)};switch(t.off("keydown.xdsoft"),!0){case _.mask===!0:_.mask=_.format.replace(/Y/g,"9999").replace(/F/g,"9999").replace(/m/g,"19").replace(/d/g,"39").replace(/H/g,"29").replace(/i/g,"59").replace(/s/g,"59");case"string"==e.type(_.mask):C(_.mask,t.val())||t.val(_.mask.replace(/[0-9]/g,"_")),t.on("keydown.xdsoft",function(n){var M=this.value,S=n.which;switch(!0){case S>=a&&S<=r||S>=o&&S<=s||S==l||S==d:var O=k(this),I=S!=l&&S!=d?String.fromCharCode(o<=S&&S<=s?S-a:S):"_";for(S!=l&&S!=d||!O||(O--,I="_");/[^0-9_]/.test(_.mask.substr(O,1))&&O<_.mask.length&&O>0;)O+=S==l||S==d?-1:1;if(M=M.substr(0,O)+I+M.substr(O+1),""==e.trim(M))M=_.mask.replace(/[0-9]/g,"_");else if(O==_.mask.length)break;for(O+=S==l||S==d?0:1;/[^0-9_]/.test(_.mask.substr(O,1))&&O<_.mask.length&&O>0;)O+=S==l||S==d?-1:1;C(_.mask,M)?(this.value=M,F(this,O)):""==e.trim(M)?this.value=_.mask.replace(/[0-9]/g,"_"):t.trigger("error_input.xdsoft");break;case!!~[v,y,D,T,w].indexOf(S)&&b:case!!~[c,m,g,f,h,x,i,p,u].indexOf(S):return!0}return n.preventDefault(),!1})}}_.validateOnBlur&&t.off("blur.xdsoft").on("blur.xdsoft",function(){_.allowBlank&&!e.trim(e(this).val()).length?(e(this).val(null),M.data("xdsoft_datetime").empty()):Date.parseDate(e(this).val(),_.format)?M.data("xdsoft_datetime").setCurrentTime(e(this).val()):(e(this).val(W.now().dateFormat(_.format)),M.data("xdsoft_datetime").setCurrentTime(e(this).val())),M.trigger("changedatetime.xdsoft")}),_.dayOfWeekStartPrev=0==_.dayOfWeekStart?6:_.dayOfWeekStart-1,M.trigger("xchange.xdsoft")},M.data("options",_).on("mousedown.xdsoft",function(e){return e.stopPropagation(),e.preventDefault(),A.hide(),P.hide(),!1});var N=I.find(".xdsoft_time_box");N.append(H),N.xdsoftScroller(),M.on("afterOpen.xdsoft",function(){N.xdsoftScroller()}),M.append(S).append(I),_.withoutCopyright!==!0&&M.append(k),S.append(O).append(F),e("body").append(M);var W=new function(){var e=this;e.now=function(){var e=new Date;return _.yearOffset&&e.setFullYear(e.getFullYear()+_.yearOffset),e},e.currentTime=this.now(),e.isValidDate=function(e){return"[object Date]"===Object.prototype.toString.call(e)&&!isNaN(e.getTime())},e.setCurrentTime=function(t){e.currentTime="string"==typeof t?e.strToDateTime(t):e.isValidDate(t)?t:e.now(),M.trigger("xchange.xdsoft")},e.empty=function(){e.currentTime=null},e.getCurrentTime=function(t){return e.currentTime},e.nextMonth=function(){var t=e.currentTime.getMonth()+1;return 12==t&&(e.currentTime.setFullYear(e.currentTime.getFullYear()+1),t=0),e.currentTime.setDate(Math.min(Date.daysInMonth[t],e.currentTime.getDate())),e.currentTime.setMonth(t),_.onChangeMonth&&_.onChangeMonth.call&&_.onChangeMonth.call(M,W.currentTime,M.data("input")),M.trigger("xchange.xdsoft"),t},e.prevMonth=function(){var t=e.currentTime.getMonth()-1;return t==-1&&(e.currentTime.setFullYear(e.currentTime.getFullYear()-1),t=11),e.currentTime.setDate(Math.min(Date.daysInMonth[t],e.currentTime.getDate())),e.currentTime.setMonth(t),_.onChangeMonth&&_.onChangeMonth.call&&_.onChangeMonth.call(M,W.currentTime,M.data("input")),M.trigger("xchange.xdsoft"),t},e.strToDateTime=function(t){var n,a,r=[];return(r=/^(\+|\-)(.*)$/.exec(t))&&(r[2]=Date.parseDate(r[2],_.formatDate))?(n=r[2].getTime()-1*r[2].getTimezoneOffset()*6e4,a=new Date(W.now().getTime()+parseInt(r[1]+"1")*n)):a=t?Date.parseDate(t,_.format):e.now(),e.isValidDate(a)||(a=e.now()),a},e.strtodate=function(t){var n=t?Date.parseDate(t,_.formatDate):e.now();return e.isValidDate(n)||(n=e.now()),n},e.strtotime=function(t){var n=t?Date.parseDate(t,_.formatTime):e.now();return e.isValidDate(n)||(n=e.now()),n},e.str=function(){return e.currentTime.dateFormat(_.format)}};O.find(".xdsoft_today_button").on("mousedown.xdsoft",function(){M.data("changed",!0),W.setCurrentTime(0),M.trigger("afterOpen.xdsoft")}).on("dblclick.xdsoft",function(){t.val(W.str()),M.trigger("close.xdsoft")}),O.find(".xdsoft_prev,.xdsoft_next").on("mousedown.xdsoft",function(){var t=e(this),n=0,a=!1;!function r(e){W.currentTime.getMonth();t.hasClass(_.next)?W.nextMonth():t.hasClass(_.prev)&&W.prevMonth(),!a&&(n=setTimeout(r,e?e:100))}(500),e([document.body,window]).on("mouseup.xdsoft",function o(){clearTimeout(n),a=!0,e([document.body,window]).off("mouseup.xdsoft",o)})}),I.find(".xdsoft_prev,.xdsoft_next").on("mousedown.xdsoft",function(){var t=e(this),n=0,a=!1,r=110;!function o(e){var s=C[0].clientHeight,i=H[0].offsetHeight,d=Math.abs(parseInt(H.css("marginTop")));t.hasClass(_.next)&&i-s-_.timeHeightInTimePicker>=d?H.css("marginTop","-"+(d+_.timeHeightInTimePicker)+"px"):t.hasClass(_.prev)&&d-_.timeHeightInTimePicker>=0&&H.css("marginTop","-"+(d-_.timeHeightInTimePicker)+"px"),C.trigger("scroll_element.xdsoft_scroller",[Math.abs(parseInt(H.css("marginTop"))/(i-s))]),r=r>10?10:r-10,!a&&(n=setTimeout(o,e?e:r))}(500),e([document.body,window]).on("mouseup.xdsoft",function s(){clearTimeout(n),a=!0,e([document.body,window]).off("mouseup.xdsoft",s)})});var z=0;M.on("xchange.xdsoft",function(t){clearTimeout(z),z=setTimeout(function(){for(var t="",n=new Date(W.currentTime.getFullYear(),W.currentTime.getMonth(),1,12,0,0),a=0,r=W.now();n.getDay()!=_.dayOfWeekStart;)n.setDate(n.getDate()-1);t+="<table><thead><tr>";for(var o=0;o<7;o++)t+="<th>"+_.i18n[_.lang].dayOfWeek[o+_.dayOfWeekStart>6?0:o+_.dayOfWeekStart]+"</th>";t+="</tr></thead>",t+="<tbody><tr>";var s=!1,i=!1;_.maxDate!==!1&&(s=W.strtodate(_.maxDate),s=new Date(s.getFullYear(),s.getMonth(),s.getDate(),23,59,59,999)),_.minDate!==!1&&(i=W.strtodate(_.minDate),i=new Date(i.getFullYear(),i.getMonth(),i.getDate()));for(var d,u,c,l=[];a<W.currentTime.getDaysInMonth()||n.getDay()!=_.dayOfWeekStart||W.currentTime.getMonth()==n.getMonth();)l=[],a++,d=n.getDate(),u=n.getFullYear(),c=n.getMonth(),l.push("xdsoft_date"),(s!==!1&&n>s||i!==!1&&n<i)&&l.push("xdsoft_disabled"),W.currentTime.getMonth()!=c&&l.push("xdsoft_other_month"),(_.defaultSelect||M.data("changed"))&&W.currentTime.dateFormat("d.m.Y")==n.dateFormat("d.m.Y")&&l.push("xdsoft_current"),r.dateFormat("d.m.Y")==n.dateFormat("d.m.Y")&&l.push("xdsoft_today"),(0==n.getDay()||6==n.getDay()||~_.weekends.indexOf(n.dateFormat("d.m.Y")))&&l.push("xdsoft_weekend"),_.beforeShowDay&&"function"==typeof _.beforeShowDay&&l.push(_.beforeShowDay(n)),t+='<td data-date="'+d+'" data-month="'+c+'" data-year="'+u+'" class="xdsoft_date xdsoft_day_of_week'+n.getDay()+" "+l.join(" ")+'"><div>'+d+"</div></td>",n.getDay()==_.dayOfWeekStartPrev&&(t+="</tr>"),n.setDate(d+1);t+="</tbody></table>",F.html(t),O.find(".xdsoft_label span").eq(0).text(_.i18n[_.lang].months[W.currentTime.getMonth()]),O.find(".xdsoft_label span").eq(1).text(W.currentTime.getFullYear());var f="",m="",c="",h=function(e,t){var n=W.now();n.setHours(e),e=parseInt(n.getHours()),n.setMinutes(t),t=parseInt(n.getMinutes()),l=[],(_.maxTime!==!1&&W.strtotime(_.maxTime).getTime()<n.getTime()||_.minTime!==!1&&W.strtotime(_.minTime).getTime()>n.getTime())&&l.push("xdsoft_disabled"),(_.initTime||_.defaultSelect||M.data("changed"))&&parseInt(W.currentTime.getHours())==parseInt(e)&&(_.step>59||Math[_.roundTime](W.currentTime.getMinutes()/_.step)*_.step==parseInt(t))&&(_.defaultSelect||M.data("changed")?l.push("xdsoft_current"):_.initTime&&l.push("xdsoft_init_time")),parseInt(r.getHours())==parseInt(e)&&parseInt(r.getMinutes())==parseInt(t)&&l.push("xdsoft_today"),f+='<div class="xdsoft_time '+l.join(" ")+'" data-hour="'+e+'" data-minute="'+t+'">'+n.dateFormat(_.formatTime)+"</div>"};if(_.allowTimes&&e.isArray(_.allowTimes)&&_.allowTimes.length)for(var a=0;a<_.allowTimes.length;a++)m=W.strtotime(_.allowTimes[a]).getHours(),c=W.strtotime(_.allowTimes[a]).getMinutes(),h(m,c);else for(var a=0,o=0;a<(_.hours12?12:24);a++)for(o=0;o<60;o+=_.step)m=(a<10?"0":"")+a,c=(o<10?"0":"")+o,h(m,c);H.html(f);var g="",a=0;for(a=parseInt(_.yearStart,10)+_.yearOffset;a<=parseInt(_.yearEnd,10)+_.yearOffset;a++)g+='<div class="xdsoft_option '+(W.currentTime.getFullYear()==a?"xdsoft_current":"")+'" data-value="'+a+'">'+a+"</div>";for(A.children().eq(0).html(g),a=0,g="";a<=11;a++)g+='<div class="xdsoft_option '+(W.currentTime.getMonth()==a?"xdsoft_current":"")+'" data-value="'+a+'">'+_.i18n[_.lang].months[a]+"</div>";P.children().eq(0).html(g),e(this).trigger("generate.xdsoft")},10),t.stopPropagation()}).on("afterOpen.xdsoft",function(){if(_.timepicker){var e;if(H.find(".xdsoft_current").length?e=".xdsoft_current":H.find(".xdsoft_init_time").length&&(e=".xdsoft_init_time"),e){var t=C[0].clientHeight,n=H[0].offsetHeight,a=H.find(e).index()*_.timeHeightInTimePicker+1;n-t<a&&(a=n-t),H.css("marginTop","-"+parseInt(a)+"px"),C.trigger("scroll_element.xdsoft_scroller",[parseInt(a)/(n-t)])}}});var J=0;F.on("click.xdsoft","td",function(n){n.stopPropagation(),J++;var a=e(this),r=W.currentTime;return!a.hasClass("xdsoft_disabled")&&(r.setDate(a.data("date")),r.setMonth(a.data("month")),r.setFullYear(a.data("year")),M.trigger("select.xdsoft",[r]),t.val(W.str()),(J>1||_.closeOnDateSelect===!0||0===_.closeOnDateSelect&&!_.timepicker)&&!_.inline&&M.trigger("close.xdsoft"),_.onSelectDate&&_.onSelectDate.call&&_.onSelectDate.call(M,W.currentTime,M.data("input")),M.data("changed",!0),M.trigger("xchange.xdsoft"),M.trigger("changedatetime.xdsoft"),void setTimeout(function(){J=0},200))}),H.on("click.xdsoft","div",function(t){t.stopPropagation();var n=e(this),a=W.currentTime;return!n.hasClass("xdsoft_disabled")&&(a.setHours(n.data("hour")),a.setMinutes(n.data("minute")),M.trigger("select.xdsoft",[a]),M.data("input").val(W.str()),!_.inline&&M.trigger("close.xdsoft"),_.onSelectTime&&_.onSelectTime.call&&_.onSelectTime.call(M,W.currentTime,M.data("input")),M.data("changed",!0),M.trigger("xchange.xdsoft"),void M.trigger("changedatetime.xdsoft"))}),M.mousewheel&&S.mousewheel(function(e,t,n,a){return!_.scrollMonth||(t<0?W.nextMonth():W.prevMonth(),!1)}),M.mousewheel&&C.unmousewheel().mousewheel(function(e,t,n,a){if(!_.scrollTime)return!0;var r=C[0].clientHeight,o=H[0].offsetHeight,s=Math.abs(parseInt(H.css("marginTop"))),i=!0;return t<0&&o-r-_.timeHeightInTimePicker>=s?(H.css("marginTop","-"+(s+_.timeHeightInTimePicker)+"px"),i=!1):t>0&&s-_.timeHeightInTimePicker>=0&&(H.css("marginTop","-"+(s-_.timeHeightInTimePicker)+"px"),i=!1),C.trigger("scroll_element.xdsoft_scroller",[Math.abs(parseInt(H.css("marginTop"))/(o-r))]),e.stopPropagation(),i}),M.on("changedatetime.xdsoft",function(){if(_.onChangeDateTime&&_.onChangeDateTime.call){var e=M.data("input");_.onChangeDateTime.call(M,W.currentTime,e),e.trigger("change")}}).on("generate.xdsoft",function(){_.onGenerate&&_.onGenerate.call&&_.onGenerate.call(M,W.currentTime,M.data("input"))});var j=0;t.mousewheel&&t.mousewheel(function(e,n,a,r){return!_.scrollInput||(!_.datepicker&&_.timepicker?(j=H.find(".xdsoft_current").length?H.find(".xdsoft_current").eq(0).index():0,j+n>=0&&j+n<H.children().length&&(j+=n),H.children().eq(j).length&&H.children().eq(j).trigger("mousedown"),!1):_.datepicker&&!_.timepicker?(S.trigger(e,[n,a,r]),t.val&&t.val(W.str()),M.trigger("changedatetime.xdsoft"),!1):void 0)});var L=function(){var t=M.data("input").offset(),n=t.top+M.data("input")[0].offsetHeight-1,a=t.left;n+M[0].offsetHeight>e(window).height()+e(window).scrollTop()&&(n=t.top-M[0].offsetHeight+1),n<0&&(n=0),a+M[0].offsetWidth>e(window).width()&&(a=t.left-M[0].offsetWidth+M.data("input")[0].offsetWidth),M.css({left:a,top:n})};M.on("open.xdsoft",function(){var t=!0;_.onShow&&_.onShow.call&&(t=_.onShow.call(M,W.currentTime,M.data("input"))),t!==!1&&(M.show(),M.trigger("afterOpen.xdsoft"),L(),e(window).off("resize.xdsoft",L).on("resize.xdsoft",L),_.closeOnWithoutClick&&e([document.body,window]).on("mousedown.xdsoft",function n(){M.trigger("close.xdsoft"),e([document.body,window]).off("mousedown.xdsoft",n)}))}).on("close.xdsoft",function(e){var t=!0;_.onClose&&_.onClose.call&&(t=_.onClose.call(M,W.currentTime,M.data("input"))),t===!1||_.opened||_.inline||M.hide(),e.stopPropagation()}).data("input",t);var E=0;M.data("xdsoft_datetime",W),M.setOptions(_),W.setCurrentTime(n()),M.trigger("afterOpen.xdsoft"),t.data("xdsoft_datetimepicker",M).on("open.xdsoft focusin.xdsoft mousedown.xdsoft",function(e){t.is(":disabled")||t.is(":hidden")||!t.is(":visible")||(clearTimeout(E),E=setTimeout(function(){t.is(":disabled")||t.is(":hidden")||!t.is(":visible")||(W.setCurrentTime(n()),M.trigger("open.xdsoft"))},100))}).on("keydown.xdsoft",function(t){var n=(this.value,t.which);switch(!0){case!!~[u].indexOf(n):var a=e("input:visible,textarea:visible");return M.trigger("close.xdsoft"),a.eq(a.index(this)+1).focus(),!1;case!!~[p].indexOf(n):return M.trigger("close.xdsoft"),!0}})},O=function(t){var n=t.data("xdsoft_datetimepicker");n&&(n.data("xdsoft_datetime",null),n.remove(),t.data("xdsoft_datetimepicker",null).off("open.xdsoft focusin.xdsoft focusout.xdsoft mousedown.xdsoft blur.xdsoft keydown.xdsoft"),e(window).off("resize.xdsoft"),e([window,document.body]).off("mousedown.xdsoft"),t.unmousewheel&&t.unmousewheel())};return e(document).off("keydown.xdsoftctrl keyup.xdsoftctrl").on("keydown.xdsoftctrl",function(e){e.keyCode==i&&(b=!0)}).on("keyup.xdsoftctrl",function(e){e.keyCode==i&&(b=!1)}),this.each(function(){var t;if(t=e(this).data("xdsoft_datetimepicker")){if("string"===e.type(n))switch(n){case"show":e(this).select().focus(),t.trigger("open.xdsoft");break;case"hide":t.trigger("close.xdsoft");break;case"destroy":O(e(this));break;case"reset":this.value=this.defaultValue,this.value&&t.data("xdsoft_datetime").isValidDate(Date.parseDate(this.value,_.format))||t.data("changed",!1),t.data("xdsoft_datetime").setCurrentTime(this.value)}else t.setOptions(n);return 0}"string"!==e.type(n)&&(!_.lazyInit||_.open||_.inline?S(e(this)):k(e(this)))})}}(jQuery),Date.parseFunctions={count:0},Date.parseRegexes=[],Date.formatFunctions={count:0},Date.prototype.dateFormat=function(e){if("unixtime"==e)return parseInt(this.getTime()/1e3);null==Date.formatFunctions[e]&&Date.createNewFormat(e);var t=Date.formatFunctions[e];return this[t]()},Date.createNewFormat=function(format){var funcName="format"+Date.formatFunctions.count++;Date.formatFunctions[format]=funcName;for(var code="Date.prototype."+funcName+" = function() {return ",special=!1,ch="",i=0;i<format.length;++i)ch=format.charAt(i),special||"\\"!=ch?special?(special=!1,code+="'"+String.escape(ch)+"' + "):code+=Date.getFormatCode(ch):special=!0;eval(code.substring(0,code.length-3)+";}")},Date.getFormatCode=function(e){switch(e){case"d":return"String.leftPad(this.getDate(), 2, '0') + ";case"D":return"Date.dayNames[this.getDay()].substring(0, 3) + ";case"j":return"this.getDate() + ";case"l":return"Date.dayNames[this.getDay()] + ";case"S":return"this.getSuffix() + ";case"w":return"this.getDay() + ";case"z":return"this.getDayOfYear() + ";case"W":return"this.getWeekOfYear() + ";case"F":return"Date.monthNames[this.getMonth()] + ";case"m":return"String.leftPad(this.getMonth() + 1, 2, '0') + ";case"M":return"Date.monthNames[this.getMonth()].substring(0, 3) + ";case"n":return"(this.getMonth() + 1) + ";case"t":return"this.getDaysInMonth() + ";case"L":return"(this.isLeapYear() ? 1 : 0) + ";case"Y":return"this.getFullYear() + ";case"y":return"('' + this.getFullYear()).substring(2, 4) + ";case"a":return"(this.getHours() < 12 ? 'am' : 'pm') + ";case"A":return"(this.getHours() < 12 ? 'AM' : 'PM') + ";case"g":return"((this.getHours() %12) ? this.getHours() % 12 : 12) + ";case"G":return"this.getHours() + ";case"h":return"String.leftPad((this.getHours() %12) ? this.getHours() % 12 : 12, 2, '0') + ";case"H":return"String.leftPad(this.getHours(), 2, '0') + ";case"i":return"String.leftPad(this.getMinutes(), 2, '0') + ";case"s":return"String.leftPad(this.getSeconds(), 2, '0') + ";case"O":return"this.getGMTOffset() + ";case"T":return"this.getTimezone() + ";case"Z":return"(this.getTimezoneOffset() * -60) + ";default:return"'"+String.escape(e)+"' + "}},Date.parseDate=function(e,t){if("unixtime"==t)return new Date(isNaN(parseInt(e))?0:1e3*parseInt(e));null==Date.parseFunctions[t]&&Date.createParser(t);var n=Date.parseFunctions[t];return Date[n](e)},Date.createParser=function(format){var funcName="parse"+Date.parseFunctions.count++,regexNum=Date.parseRegexes.length,currentGroup=1;Date.parseFunctions[format]=funcName;for(var code="Date."+funcName+" = function(input) {\nvar y = -1, m = -1, d = -1, h = -1, i = -1, s = -1, z = -1;\nvar d = new Date();\ny = d.getFullYear();\nm = d.getMonth();\nd = d.getDate();\nvar results = input.match(Date.parseRegexes["+regexNum+"]);\nif (results && results.length > 0) {",regex="",special=!1,ch="",i=0;i<format.length;++i)ch=format.charAt(i),special||"\\"!=ch?special?(special=!1,regex+=String.escape(ch)):(obj=Date.formatCodeToRegex(ch,currentGroup),currentGroup+=obj.g,regex+=obj.s,obj.g&&obj.c&&(code+=obj.c)):special=!0;code+="if (y > 0 && z > 0){\nvar doyDate = new Date(y,0);\ndoyDate.setDate(z);\nm = doyDate.getMonth();\nd = doyDate.getDate();\n}",code+="if (y > 0 && m >= 0 && d > 0 && h >= 0 && i >= 0 && s >= 0)\n{return new Date(y, m, d, h, i, s);}\nelse if (y > 0 && m >= 0 && d > 0 && h >= 0 && i >= 0)\n{return new Date(y, m, d, h, i);}\nelse if (y > 0 && m >= 0 && d > 0 && h >= 0)\n{return new Date(y, m, d, h);}\nelse if (y > 0 && m >= 0 && d > 0)\n{return new Date(y, m, d);}\nelse if (y > 0 && m >= 0)\n{return new Date(y, m);}\nelse if (y > 0)\n{return new Date(y);}\n}return null;}",Date.parseRegexes[regexNum]=new RegExp("^"+regex+"$"),eval(code)},Date.formatCodeToRegex=function(e,t){switch(e){case"D":return{g:0,c:null,s:"(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)"};case"j":case"d":return{g:1,c:"d = parseInt(results["+t+"], 10);\n",s:"(\\d{1,2})"};case"l":return{g:0,c:null,s:"(?:"+Date.dayNames.join("|")+")"};case"S":return{g:0,c:null,s:"(?:st|nd|rd|th)"};case"w":return{g:0,c:null,s:"\\d"};case"z":return{g:1,c:"z = parseInt(results["+t+"], 10);\n",s:"(\\d{1,3})"};case"W":return{g:0,c:null,s:"(?:\\d{2})"};case"F":return{g:1,c:"m = parseInt(Date.monthNumbers[results["+t+"].substring(0, 3)], 10);\n",s:"("+Date.monthNames.join("|")+")"};case"M":return{g:1,c:"m = parseInt(Date.monthNumbers[results["+t+"]], 10);\n",s:"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)"};case"n":case"m":return{g:1,c:"m = parseInt(results["+t+"], 10) - 1;\n",s:"(\\d{1,2})"};case"t":return{g:0,c:null,s:"\\d{1,2}"};case"L":return{g:0,c:null,s:"(?:1|0)"};case"Y":return{g:1,c:"y = parseInt(results["+t+"], 10);\n",s:"(\\d{4})"};case"y":return{g:1,c:"var ty = parseInt(results["+t+"], 10);\ny = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n",s:"(\\d{1,2})"};case"a":return{g:1,c:"if (results["+t+"] == 'am') {\nif (h == 12) { h = 0; }\n} else { if (h < 12) { h += 12; }}",s:"(am|pm)"};case"A":return{g:1,c:"if (results["+t+"] == 'AM') {\nif (h == 12) { h = 0; }\n} else { if (h < 12) { h += 12; }}",s:"(AM|PM)"};case"g":case"G":case"h":case"H":return{g:1,c:"h = parseInt(results["+t+"], 10);\n",s:"(\\d{1,2})"};case"i":return{g:1,c:"i = parseInt(results["+t+"], 10);\n",s:"(\\d{2})"};case"s":return{g:1,c:"s = parseInt(results["+t+"], 10);\n",s:"(\\d{2})"};case"O":return{g:0,c:null,s:"[+-]\\d{4}"};case"T":return{g:0,c:null,s:"[A-Z]{3}"};case"Z":return{g:0,c:null,s:"[+-]\\d{1,5}"};default:return{g:0,c:null,s:String.escape(e)}}},Date.prototype.getTimezone=function(){return this.toString().replace(/^.*? ([A-Z]{3}) [0-9]{4}.*$/,"$1").replace(/^.*?\(([A-Z])[a-z]+ ([A-Z])[a-z]+ ([A-Z])[a-z]+\)$/,"$1$2$3")},Date.prototype.getGMTOffset=function(){return(this.getTimezoneOffset()>0?"-":"+")+String.leftPad(Math.floor(Math.abs(this.getTimezoneOffset())/60),2,"0")+String.leftPad(Math.abs(this.getTimezoneOffset())%60,2,"0")},Date.prototype.getDayOfYear=function(){var e=0;Date.daysInMonth[1]=this.isLeapYear()?29:28;for(var t=0;t<this.getMonth();++t)e+=Date.daysInMonth[t];return e+this.getDate()},Date.prototype.getWeekOfYear=function(){var e=this.getDayOfYear()+(4-this.getDay()),t=new Date(this.getFullYear(),0,1),n=7-t.getDay()+4;return String.leftPad(Math.ceil((e-n)/7)+1,2,"0")},Date.prototype.isLeapYear=function(){var e=this.getFullYear();return 0==(3&e)&&(e%100||e%400==0&&e)},Date.prototype.getFirstDayOfMonth=function(){var e=(this.getDay()-(this.getDate()-1))%7;return e<0?e+7:e},Date.prototype.getLastDayOfMonth=function(){var e=(this.getDay()+(Date.daysInMonth[this.getMonth()]-this.getDate()))%7;return e<0?e+7:e},Date.prototype.getDaysInMonth=function(){return Date.daysInMonth[1]=this.isLeapYear()?29:28,Date.daysInMonth[this.getMonth()]},Date.prototype.getSuffix=function(){switch(this.getDate()){case 1:case 21:case 31:return"st";case 2:case 22:return"nd";case 3:case 23:return"rd";default:return"th"}},String.escape=function(e){return e.replace(/('|\\)/g,"\\$1")},String.leftPad=function(e,t,n){var a=new String(e);for(null==n&&(n=" ");a.length<t;)a=n+a;return a},Date.daysInMonth=[31,28,31,30,31,30,31,31,30,31,30,31],Date.monthNames=["January","February","March","April","May","June","July","August","September","October","November","December"],Date.dayNames=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],Date.y2kYear=50,Date.monthNumbers={Jan:0,Feb:1,Mar:2,
Apr:3,May:4,Jun:5,Jul:6,Aug:7,Sep:8,Oct:9,Nov:10,Dec:11},Date.patterns={ISO8601LongPattern:"Y-m-d H:i:s",ISO8601ShortPattern:"Y-m-d",ShortDatePattern:"n/j/Y",LongDatePattern:"l, F d, Y",FullDateTimePattern:"l, F d, Y g:i:s A",MonthDayPattern:"F d",ShortTimePattern:"g:i A",LongTimePattern:"g:i:s A",SortableDateTimePattern:"Y-m-d\\TH:i:s",UniversalSortableDateTimePattern:"Y-m-d H:i:sO",YearMonthPattern:"F, Y"},function(e){"function"==typeof define&&define.amd?define(["jquery.flot.min"],e):"object"==typeof exports?module.exports=e:e(jQuery)}(function(e){function t(t){var r,o=t||window.event,s=[].slice.call(arguments,1),i=0,d=0,u=0,c=0,l=0;return t=e.event.fix(o),t.type="mousewheel",o.wheelDelta&&(i=o.wheelDelta),o.detail&&(i=o.detail*-1),o.deltaY&&(u=o.deltaY*-1,i=u),o.deltaX&&(d=o.deltaX,i=d*-1),void 0!==o.wheelDeltaY&&(u=o.wheelDeltaY),void 0!==o.wheelDeltaX&&(d=o.wheelDeltaX*-1),c=Math.abs(i),(!n||c<n)&&(n=c),l=Math.max(Math.abs(u),Math.abs(d)),(!a||l<a)&&(a=l),r=i>0?"floor":"ceil",i=Math[r](i/n),d=Math[r](d/a),u=Math[r](u/a),s.unshift(t,i,d,u),(e.event.dispatch||e.event.handle).apply(this,s)}var n,a,r=["wheel","mousewheel","DOMMouseScroll","MozMousePixelScroll"],o="onwheel"in document||document.documentMode>=9?["wheel"]:["mousewheel","DomMouseScroll","MozMousePixelScroll"];if(e.event.fixHooks)for(var s=r.length;s;)e.event.fixHooks[r[--s]]=e.event.mouseHooks;e.event.special.mousewheel={setup:function(){if(this.addEventListener)for(var e=o.length;e;)this.addEventListener(o[--e],t,!1);else this.onmousewheel=t},teardown:function(){if(this.removeEventListener)for(var e=o.length;e;)this.removeEventListener(o[--e],t,!1);else this.onmousewheel=null}},e.fn.extend({mousewheel:function(e){return e?this.bind("mousewheel",e):this.trigger("mousewheel")},unmousewheel:function(e){return this.unbind("mousewheel",e)}})});
function _toConsumableArray(e){if(Array.isArray(e)){for(var t=0,i=Array(e.length);t<e.length;t++)i[t]=e[t];return i}return Array.from(e)}var _slice=Array.prototype.slice,_slicedToArray=function(){function e(e,t){var i=[],n=!0,r=!1,s=void 0;try{for(var a,o=e[Symbol.iterator]();!(n=(a=o.next()).done)&&(i.push(a.value),!t||i.length!==t);n=!0);}catch(l){r=!0,s=l}finally{try{!n&&o["return"]&&o["return"]()}finally{if(r)throw s}}return i}return function(t,i){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,i);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),_extends=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&(e[n]=i[n])}return e};!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t(require("jquery")):"function"==typeof define&&define.amd?define(["jquery"],t):e.parsley=t(e.jQuery)}(this,function(e){"use strict";function t(e,t){return e.parsleyAdaptedCallback||(e.parsleyAdaptedCallback=function(){var i=Array.prototype.slice.call(arguments,0);i.unshift(this),e.apply(t||T,i)}),e.parsleyAdaptedCallback}function i(e){return 0===e.lastIndexOf(D,0)?e.substr(D.length):e}function n(){var t=this,i=window||global;_extends(this,{isNativeEvent:function(e){return e.originalEvent&&e.originalEvent.isTrusted!==!1},fakeInputEvent:function(i){t.isNativeEvent(i)&&e(i.target).trigger("input")},misbehaves:function(i){t.isNativeEvent(i)&&(t.behavesOk(i),e(document).on("change.inputevent",i.data.selector,t.fakeInputEvent),t.fakeInputEvent(i))},behavesOk:function(i){t.isNativeEvent(i)&&e(document).off("input.inputevent",i.data.selector,t.behavesOk).off("change.inputevent",i.data.selector,t.misbehaves)},install:function(){if(!i.inputEventPatched){i.inputEventPatched="0.0.3";for(var n=["select",'input[type="checkbox"]','input[type="radio"]','input[type="file"]'],r=0;r<n.length;r++){var s=n[r];e(document).on("input.inputevent",s,{selector:s},t.behavesOk).on("change.inputevent",s,{selector:s},t.misbehaves)}}},uninstall:function(){delete i.inputEventPatched,e(document).off(".inputevent")}})}var r=1,s={},a={attr:function(e,t,i){var n,r,s,a=new RegExp("^"+t,"i");if("undefined"==typeof i)i={};else for(n in i)i.hasOwnProperty(n)&&delete i[n];if(!e)return i;for(s=e.attributes,n=s.length;n--;)r=s[n],r&&r.specified&&a.test(r.name)&&(i[this.camelize(r.name.slice(t.length))]=this.deserializeValue(r.value));return i},checkAttr:function(e,t,i){return e.hasAttribute(t+i)},setAttr:function(e,t,i,n){e.setAttribute(this.dasherize(t+i),String(n))},generateID:function(){return""+r++},deserializeValue:function(t){var i;try{return t?"true"==t||"false"!=t&&("null"==t?null:isNaN(i=Number(t))?/^[\[\{]/.test(t)?e.parseJSON(t):t:i):t}catch(n){return t}},camelize:function(e){return e.replace(/-+(.)?/g,function(e,t){return t?t.toUpperCase():""})},dasherize:function(e){return e.replace(/::/g,"/").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/_/g,"-").toLowerCase()},warn:function(){var e;window.console&&"function"==typeof window.console.warn&&(e=window.console).warn.apply(e,arguments)},warnOnce:function(e){s[e]||(s[e]=!0,this.warn.apply(this,arguments))},_resetWarnings:function(){s={}},trimString:function(e){return e.replace(/^\s+|\s+$/g,"")},parse:{date:function S(e){var t=e.match(/^(\d{4,})-(\d\d)-(\d\d)$/);if(!t)return null;var i=t.map(function(e){return parseInt(e,10)}),n=_slicedToArray(i,4),r=(n[0],n[1]),s=n[2],a=n[3],S=new Date(r,s-1,a);return S.getFullYear()!==r||S.getMonth()+1!==s||S.getDate()!==a?null:S},string:function(e){return e},integer:function(e){return isNaN(e)?null:parseInt(e,10)},number:function(e){if(isNaN(e))throw null;return parseFloat(e)},"boolean":function(e){return!/^\s*false\s*$/i.test(e)},object:function(e){return a.deserializeValue(e)},regexp:function(e){var t="";return/^\/.*\/(?:[gimy]*)$/.test(e)?(t=e.replace(/.*\/([gimy]*)$/,"$1"),e=e.replace(new RegExp("^/(.*?)/"+t+"$"),"$1")):e="^"+e+"$",new RegExp(e,t)}},parseRequirement:function(e,t){var i=this.parse[e||"string"];if(!i)throw'Unknown requirement specification: "'+e+'"';var n=i(t);if(null===n)throw"Requirement is not a "+e+': "'+t+'"';return n},namespaceEvents:function(t,i){return t=this.trimString(t||"").split(/\s+/),t[0]?e.map(t,function(e){return e+"."+i}).join(" "):""},difference:function(t,i){var n=[];return e.each(t,function(e,t){i.indexOf(t)==-1&&n.push(t)}),n},all:function(t){return e.when.apply(e,_toConsumableArray(t).concat([42,42]))},objectCreate:Object.create||function(){var e=function(){};return function(t){if(arguments.length>1)throw Error("Second argument not supported");if("object"!=typeof t)throw TypeError("Argument must be an object");e.prototype=t;var i=new e;return e.prototype=null,i}}(),_SubmitSelector:'input[type="submit"], button:submit'},o={namespace:"data-parsley-",inputs:"input, textarea, select",excluded:"input[type=button], input[type=submit], input[type=reset], input[type=hidden]",priorityEnabled:!0,multiple:null,group:null,uiEnabled:!0,validationThreshold:3,focus:"first",trigger:!1,triggerAfterFailure:"input",errorClass:"parsley-error",successClass:"parsley-success",classHandler:function(e){},errorsContainer:function(e){},errorsWrapper:'<ul class="parsley-errors-list"></ul>',errorTemplate:"<li></li>"},l=function(){this.__id__=a.generateID()};l.prototype={asyncSupport:!0,_pipeAccordingToValidationResult:function(){var t=this,i=function(){var i=e.Deferred();return!0!==t.validationResult&&i.reject(),i.resolve().promise()};return[i,i]},actualizeOptions:function(){return a.attr(this.element,this.options.namespace,this.domOptions),this.parent&&this.parent.actualizeOptions&&this.parent.actualizeOptions(),this},_resetOptions:function(e){this.domOptions=a.objectCreate(this.parent.options),this.options=a.objectCreate(this.domOptions);for(var t in e)e.hasOwnProperty(t)&&(this.options[t]=e[t]);this.actualizeOptions()},_listeners:null,on:function(e,t){this._listeners=this._listeners||{};var i=this._listeners[e]=this._listeners[e]||[];return i.push(t),this},subscribe:function(t,i){e.listenTo(this,t.toLowerCase(),i)},off:function(e,t){var i=this._listeners&&this._listeners[e];if(i)if(t)for(var n=i.length;n--;)i[n]===t&&i.splice(n,1);else delete this._listeners[e];return this},unsubscribe:function(t,i){e.unsubscribeTo(this,t.toLowerCase())},trigger:function(e,t,i){t=t||this;var n,r=this._listeners&&this._listeners[e];if(r)for(var s=r.length;s--;)if(n=r[s].call(t,t,i),n===!1)return n;return!this.parent||this.parent.trigger(e,t,i)},asyncIsValid:function(e,t){return a.warnOnce("asyncIsValid is deprecated; please use whenValid instead"),this.whenValid({group:e,force:t})},_findRelated:function(){return this.options.multiple?e(this.parent.element.querySelectorAll("["+this.options.namespace+'multiple="'+this.options.multiple+'"]')):this.$element}};var u=function(e,t){var i=e.match(/^\s*\[(.*)\]\s*$/);if(!i)throw'Requirement is not an array: "'+e+'"';var n=i[1].split(",").map(a.trimString);if(n.length!==t)throw"Requirement has "+n.length+" values when "+t+" are needed";return n},d=function(e,t,i){var n=null,r={};for(var s in e)if(s){var o=i(s);"string"==typeof o&&(o=a.parseRequirement(e[s],o)),r[s]=o}else n=a.parseRequirement(e[s],t);return[n,r]},h=function(t){e.extend(!0,this,t)};h.prototype={validate:function(e,t){if(this.fn)return arguments.length>3&&(t=[].slice.call(arguments,1,-1)),this.fn(e,t);if(Array.isArray(e)){if(!this.validateMultiple)throw"Validator `"+this.name+"` does not handle multiple values";return this.validateMultiple.apply(this,arguments)}var i=arguments[arguments.length-1];if(this.validateDate&&i._isDateInput())return arguments[0]=a.parse.date(arguments[0]),null!==arguments[0]&&this.validateDate.apply(this,arguments);if(this.validateNumber)return!isNaN(e)&&(arguments[0]=parseFloat(arguments[0]),this.validateNumber.apply(this,arguments));if(this.validateString)return this.validateString.apply(this,arguments);throw"Validator `"+this.name+"` only handles multiple values"},parseRequirements:function(t,i){if("string"!=typeof t)return Array.isArray(t)?t:[t];var n=this.requirementType;if(Array.isArray(n)){for(var r=u(t,n.length),s=0;s<r.length;s++)r[s]=a.parseRequirement(n[s],r[s]);return r}return e.isPlainObject(n)?d(n,t,i):[a.parseRequirement(n,t)]},requirementType:"string",priority:2};var p=function(e,t){this.__class__="ValidatorRegistry",this.locale="en",this.init(e||{},t||{})},c={email:/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i,number:/^-?(\d*\.)?\d+(e[-+]?\d+)?$/i,integer:/^-?\d+$/,digits:/^\d+$/,alphanum:/^\w+$/i,date:{test:function(e){return null!==a.parse.date(e)}},url:new RegExp("^(?:(?:https?|ftp)://)?(?:\\S+(?::\\S*)?@)?(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))(?::\\d{2,5})?(?:/\\S*)?$","i")};c.range=c.number;var f=function(e){var t=(""+e).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);return t?Math.max(0,(t[1]?t[1].length:0)-(t[2]?+t[2]:0)):0},m=function(e,t){return t.map(a.parse[e])},g=function(e,t){return function(i){for(var n=arguments.length,r=Array(n>1?n-1:0),s=1;s<n;s++)r[s-1]=arguments[s];return r.pop(),t.apply(void 0,[i].concat(_toConsumableArray(m(e,r))))}},v=function(e){return{validateDate:g("date",e),validateNumber:g("number",e),requirementType:e.length<=2?"string":["string","string"],priority:30}};p.prototype={init:function(e,t){this.catalog=t,this.validators=_extends({},this.validators);for(var i in e)this.addValidator(i,e[i].fn,e[i].priority);window.Parsley.trigger("parsley:validator:init")},setLocale:function(e){if("undefined"==typeof this.catalog[e])throw new Error(e+" is not available in the catalog");return this.locale=e,this},addCatalog:function(e,t,i){return"object"==typeof t&&(this.catalog[e]=t),!0===i?this.setLocale(e):this},addMessage:function(e,t,i){return"undefined"==typeof this.catalog[e]&&(this.catalog[e]={}),this.catalog[e][t]=i,this},addMessages:function(e,t){for(var i in t)this.addMessage(e,i,t[i]);return this},addValidator:function(e,t,i){if(this.validators[e])a.warn('Validator "'+e+'" is already defined.');else if(o.hasOwnProperty(e))return void a.warn('"'+e+'" is a restricted keyword and is not a valid validator name.');return this._setValidator.apply(this,arguments)},updateValidator:function(e,t,i){return this.validators[e]?this._setValidator.apply(this,arguments):(a.warn('Validator "'+e+'" is not already defined.'),this.addValidator.apply(this,arguments))},removeValidator:function(e){return this.validators[e]||a.warn('Validator "'+e+'" is not defined.'),delete this.validators[e],this},_setValidator:function(e,t,i){"object"!=typeof t&&(t={fn:t,priority:i}),t.validate||(t=new h(t)),this.validators[e]=t;for(var n in t.messages||{})this.addMessage(n,e,t.messages[n]);return this},getErrorMessage:function(e){var t;if("type"===e.name){var i=this.catalog[this.locale][e.name]||{};t=i[e.requirements]}else t=this.formatMessage(this.catalog[this.locale][e.name],e.requirements);return t||this.catalog[this.locale].defaultMessage||this.catalog.en.defaultMessage},formatMessage:function(e,t){if("object"==typeof t){for(var i in t)e=this.formatMessage(e,t[i]);return e}return"string"==typeof e?e.replace(/%s/i,t):""},validators:{notblank:{validateString:function(e){return/\S/.test(e)},priority:2},required:{validateMultiple:function(e){return e.length>0},validateString:function(e){return/\S/.test(e)},priority:512},type:{validateString:function(e,t){var i=arguments.length<=2||void 0===arguments[2]?{}:arguments[2],n=i.step,r=void 0===n?"any":n,s=i.base,a=void 0===s?0:s,o=c[t];if(!o)throw new Error("validator type `"+t+"` is not supported");if(!o.test(e))return!1;if("number"===t&&!/^any$/i.test(r||"")){var l=Number(e),u=Math.max(f(r),f(a));if(f(l)>u)return!1;var d=function(e){return Math.round(e*Math.pow(10,u))};if((d(l)-d(a))%d(r)!=0)return!1}return!0},requirementType:{"":"string",step:"string",base:"number"},priority:256},pattern:{validateString:function(e,t){return t.test(e)},requirementType:"regexp",priority:64},minlength:{validateString:function(e,t){return e.length>=t},requirementType:"integer",priority:30},maxlength:{validateString:function(e,t){return e.length<=t},requirementType:"integer",priority:30},length:{validateString:function(e,t,i){return e.length>=t&&e.length<=i},requirementType:["integer","integer"],priority:30},mincheck:{validateMultiple:function(e,t){return e.length>=t},requirementType:"integer",priority:30},maxcheck:{validateMultiple:function(e,t){return e.length<=t},requirementType:"integer",priority:30},check:{validateMultiple:function(e,t,i){return e.length>=t&&e.length<=i},requirementType:["integer","integer"],priority:30},min:v(function(e,t){return e>=t}),max:v(function(e,t){return e<=t}),range:v(function(e,t,i){return e>=t&&e<=i}),equalto:{validateString:function(t,i){var n=e(i);return n.length?t===n.val():t===i},priority:256}}};var y={},_=function k(e,t,i){for(var n=[],r=[],s=0;s<e.length;s++){for(var a=!1,o=0;o<t.length;o++)if(e[s].assert.name===t[o].assert.name){a=!0;break}a?r.push(e[s]):n.push(e[s])}return{kept:r,added:n,removed:i?[]:k(t,e,!0).added}};y.Form={_actualizeTriggers:function(){var e=this;this.$element.on("submit.Parsley",function(t){e.onSubmitValidate(t)}),this.$element.on("click.Parsley",a._SubmitSelector,function(t){e.onSubmitButton(t)}),!1!==this.options.uiEnabled&&this.element.setAttribute("novalidate","")},focus:function(){if(this._focusedField=null,!0===this.validationResult||"none"===this.options.focus)return null;for(var e=0;e<this.fields.length;e++){var t=this.fields[e];if(!0!==t.validationResult&&t.validationResult.length>0&&"undefined"==typeof t.options.noFocus&&(this._focusedField=t.$element,"first"===this.options.focus))break}return null===this._focusedField?null:this._focusedField.focus()},_destroyUI:function(){this.$element.off(".Parsley")}},y.Field={_reflowUI:function(){if(this._buildUI(),this._ui){var e=_(this.validationResult,this._ui.lastValidationResult);this._ui.lastValidationResult=this.validationResult,this._manageStatusClass(),this._manageErrorsMessages(e),this._actualizeTriggers(),!e.kept.length&&!e.added.length||this._failedOnce||(this._failedOnce=!0,this._actualizeTriggers())}},getErrorsMessages:function(){if(!0===this.validationResult)return[];for(var e=[],t=0;t<this.validationResult.length;t++)e.push(this.validationResult[t].errorMessage||this._getErrorMessage(this.validationResult[t].assert));return e},addError:function(e){var t=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],i=t.message,n=t.assert,r=t.updateClass,s=void 0===r||r;this._buildUI(),this._addError(e,{message:i,assert:n}),s&&this._errorClass()},updateError:function(e){var t=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],i=t.message,n=t.assert,r=t.updateClass,s=void 0===r||r;this._buildUI(),this._updateError(e,{message:i,assert:n}),s&&this._errorClass()},removeError:function(e){var t=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],i=t.updateClass,n=void 0===i||i;this._buildUI(),this._removeError(e),n&&this._manageStatusClass()},_manageStatusClass:function(){this.hasConstraints()&&this.needsValidation()&&!0===this.validationResult?this._successClass():this.validationResult.length>0?this._errorClass():this._resetClass()},_manageErrorsMessages:function(t){if("undefined"==typeof this.options.errorsMessagesDisabled){if("undefined"!=typeof this.options.errorMessage)return t.added.length||t.kept.length?(this._insertErrorWrapper(),0===this._ui.$errorsWrapper.find(".parsley-custom-error-message").length&&this._ui.$errorsWrapper.append(e(this.options.errorTemplate).addClass("parsley-custom-error-message")),this._ui.$errorsWrapper.addClass("filled").find(".parsley-custom-error-message").html(this.options.errorMessage)):this._ui.$errorsWrapper.removeClass("filled").find(".parsley-custom-error-message").remove();for(var i=0;i<t.removed.length;i++)this._removeError(t.removed[i].assert.name);for(i=0;i<t.added.length;i++)this._addError(t.added[i].assert.name,{message:t.added[i].errorMessage,assert:t.added[i].assert});for(i=0;i<t.kept.length;i++)this._updateError(t.kept[i].assert.name,{message:t.kept[i].errorMessage,assert:t.kept[i].assert})}},_addError:function(t,i){var n=i.message,r=i.assert;this._insertErrorWrapper(),this._ui.$errorsWrapper.addClass("filled").append(e(this.options.errorTemplate).addClass("parsley-"+t).html(n||this._getErrorMessage(r)))},_updateError:function(e,t){var i=t.message,n=t.assert;this._ui.$errorsWrapper.addClass("filled").find(".parsley-"+e).html(i||this._getErrorMessage(n))},_removeError:function(e){this._ui.$errorsWrapper.removeClass("filled").find(".parsley-"+e).remove()},_getErrorMessage:function(e){var t=e.name+"Message";return"undefined"!=typeof this.options[t]?window.Parsley.formatMessage(this.options[t],e.requirements):window.Parsley.getErrorMessage(e)},_buildUI:function(){if(!this._ui&&!1!==this.options.uiEnabled){var t={};this.element.setAttribute(this.options.namespace+"id",this.__id__),t.$errorClassHandler=this._manageClassHandler(),t.errorsWrapperId="parsley-id-"+(this.options.multiple?"multiple-"+this.options.multiple:this.__id__),t.$errorsWrapper=e(this.options.errorsWrapper).attr("id",t.errorsWrapperId),t.lastValidationResult=[],t.validationInformationVisible=!1,this._ui=t}},_manageClassHandler:function(){if("string"==typeof this.options.classHandler)return 0===e(this.options.classHandler).length&&ParsleyUtils.warn("No elements found that match the selector `"+this.options.classHandler+"` set in options.classHandler or data-parsley-class-handler"),e(this.options.classHandler);if("function"==typeof this.options.classHandler)var t=this.options.classHandler.call(this,this);return"undefined"!=typeof t&&t.length?t:this._inputHolder()},_inputHolder:function(){return this.options.multiple&&"SELECT"!==this.element.nodeName?this.$element.parent():this.$element},_insertErrorWrapper:function(){var t;if(0!==this._ui.$errorsWrapper.parent().length)return this._ui.$errorsWrapper.parent();if("string"==typeof this.options.errorsContainer){if(e(this.options.errorsContainer).length)return e(this.options.errorsContainer).append(this._ui.$errorsWrapper);a.warn("The errors container `"+this.options.errorsContainer+"` does not exist in DOM")}else"function"==typeof this.options.errorsContainer&&(t=this.options.errorsContainer.call(this,this));return"undefined"!=typeof t&&t.length?t.append(this._ui.$errorsWrapper):this._inputHolder().after(this._ui.$errorsWrapper)},_actualizeTriggers:function(){var e,t=this,i=this._findRelated();i.off(".Parsley"),this._failedOnce?i.on(a.namespaceEvents(this.options.triggerAfterFailure,"Parsley"),function(){t._validateIfNeeded()}):(e=a.namespaceEvents(this.options.trigger,"Parsley"))&&i.on(e,function(e){t._validateIfNeeded(e)})},_validateIfNeeded:function(e){var t=this;e&&/key|input/.test(e.type)&&(!this._ui||!this._ui.validationInformationVisible)&&this.getValue().length<=this.options.validationThreshold||(this.options.debounce?(window.clearTimeout(this._debounced),this._debounced=window.setTimeout(function(){return t.validate()},this.options.debounce)):this.validate())},_resetUI:function(){this._failedOnce=!1,this._actualizeTriggers(),"undefined"!=typeof this._ui&&(this._ui.$errorsWrapper.removeClass("filled").children().remove(),this._resetClass(),this._ui.lastValidationResult=[],this._ui.validationInformationVisible=!1)},_destroyUI:function(){this._resetUI(),"undefined"!=typeof this._ui&&this._ui.$errorsWrapper.remove(),delete this._ui},_successClass:function(){this._ui.validationInformationVisible=!0,this._ui.$errorClassHandler.removeClass(this.options.errorClass).addClass(this.options.successClass)},_errorClass:function(){this._ui.validationInformationVisible=!0,this._ui.$errorClassHandler.removeClass(this.options.successClass).addClass(this.options.errorClass)},_resetClass:function(){this._ui.$errorClassHandler.removeClass(this.options.successClass).removeClass(this.options.errorClass)}};var w=function(t,i,n){this.__class__="Form",this.element=t,this.$element=e(t),this.domOptions=i,this.options=n,this.parent=window.Parsley,this.fields=[],this.validationResult=null},b={pending:null,resolved:!0,rejected:!1};w.prototype={onSubmitValidate:function(e){var t=this;if(!0!==e.parsley){var i=this._submitSource||this.$element.find(a._SubmitSelector)[0];if(this._submitSource=null,this.$element.find(".parsley-synthetic-submit-button").prop("disabled",!0),!i||null===i.getAttribute("formnovalidate")){window.Parsley._remoteCache={};var n=this.whenValidate({event:e});"resolved"===n.state()&&!1!==this._trigger("submit")||(e.stopImmediatePropagation(),e.preventDefault(),"pending"===n.state()&&n.done(function(){t._submit(i)}))}}},onSubmitButton:function(e){this._submitSource=e.currentTarget},_submit:function(t){if(!1!==this._trigger("submit")){if(t){var i=this.$element.find(".parsley-synthetic-submit-button").prop("disabled",!1);0===i.length&&(i=e('<input class="parsley-synthetic-submit-button" type="hidden">').appendTo(this.$element)),i.attr({name:t.getAttribute("name"),value:t.getAttribute("value")})}this.$element.trigger(_extends(e.Event("submit"),{parsley:!0}))}},validate:function(t){if(arguments.length>=1&&!e.isPlainObject(t)){a.warnOnce("Calling validate on a parsley form without passing arguments as an object is deprecated.");var i=_slice.call(arguments),n=i[0],r=i[1],s=i[2];t={group:n,force:r,event:s}}return b[this.whenValidate(t).state()]},whenValidate:function(){var t,i=this,n=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],r=n.group,s=n.force,o=n.event;this.submitEvent=o,o&&(this.submitEvent=_extends({},o,{preventDefault:function(){a.warnOnce("Using `this.submitEvent.preventDefault()` is deprecated; instead, call `this.validationResult = false`"),i.validationResult=!1}})),this.validationResult=!0,this._trigger("validate"),this._refreshFields();var l=this._withoutReactualizingFormOptions(function(){return e.map(i.fields,function(e){return e.whenValidate({force:s,group:r})})});return(t=a.all(l).done(function(){i._trigger("success")}).fail(function(){i.validationResult=!1,i.focus(),i._trigger("error")}).always(function(){i._trigger("validated")})).pipe.apply(t,_toConsumableArray(this._pipeAccordingToValidationResult()))},isValid:function(t){if(arguments.length>=1&&!e.isPlainObject(t)){a.warnOnce("Calling isValid on a parsley form without passing arguments as an object is deprecated.");var i=_slice.call(arguments),n=i[0],r=i[1];t={group:n,force:r}}return b[this.whenValid(t).state()]},whenValid:function(){var t=this,i=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],n=i.group,r=i.force;this._refreshFields();var s=this._withoutReactualizingFormOptions(function(){return e.map(t.fields,function(e){return e.whenValid({group:n,force:r})})});return a.all(s)},reset:function(){for(var e=0;e<this.fields.length;e++)this.fields[e].reset();this._trigger("reset")},destroy:function(){this._destroyUI();for(var e=0;e<this.fields.length;e++)this.fields[e].destroy();this.$element.removeData("Parsley"),this._trigger("destroy")},_refreshFields:function(){return this.actualizeOptions()._bindFields()},_bindFields:function(){var t=this,i=this.fields;return this.fields=[],this.fieldsMappedById={},this._withoutReactualizingFormOptions(function(){t.$element.find(t.options.inputs).not(t.options.excluded).each(function(e,i){var n=new window.Parsley.Factory(i,{},t);if(("Field"===n.__class__||"FieldMultiple"===n.__class__)&&!0!==n.options.excluded){var r=n.__class__+"-"+n.__id__;"undefined"==typeof t.fieldsMappedById[r]&&(t.fieldsMappedById[r]=n,t.fields.push(n))}}),e.each(a.difference(i,t.fields),function(e,t){t.reset()})}),this},_withoutReactualizingFormOptions:function(e){var t=this.actualizeOptions;this.actualizeOptions=function(){return this};var i=e();return this.actualizeOptions=t,i},_trigger:function(e){return this.trigger("form:"+e)}};var F=function(e,t,i,n,r){var s=window.Parsley._validatorRegistry.validators[t],a=new h(s);n=n||e.options[t+"Priority"]||a.priority,r=!0===r,_extends(this,{validator:a,name:t,requirements:i,priority:n,isDomConstraint:r}),this._parseRequirements(e.options)},C=function(e){var t=e[0].toUpperCase();return t+e.slice(1)};F.prototype={validate:function(e,t){var i;return(i=this.validator).validate.apply(i,[e].concat(_toConsumableArray(this.requirementList),[t]))},_parseRequirements:function(e){var t=this;this.requirementList=this.validator.parseRequirements(this.requirements,function(i){return e[t.name+C(i)]})}};var E=function(t,i,n,r){this.__class__="Field",this.element=t,this.$element=e(t),"undefined"!=typeof r&&(this.parent=r),this.options=n,this.domOptions=i,this.constraints=[],this.constraintsByName={},this.validationResult=!0,this._bindConstraints()},A={pending:null,resolved:!0,rejected:!1};E.prototype={validate:function(t){arguments.length>=1&&!e.isPlainObject(t)&&(a.warnOnce("Calling validate on a parsley field without passing arguments as an object is deprecated."),t={options:t});var i=this.whenValidate(t);if(!i)return!0;switch(i.state()){case"pending":return null;case"resolved":return!0;case"rejected":return this.validationResult}},whenValidate:function(){var e,t=this,i=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],n=i.force,r=i.group;if(this.refreshConstraints(),!r||this._isInGroup(r))return this.value=this.getValue(),this._trigger("validate"),(e=this.whenValid({force:n,value:this.value,_refreshed:!0}).always(function(){t._reflowUI()}).done(function(){t._trigger("success")}).fail(function(){t._trigger("error")}).always(function(){t._trigger("validated")})).pipe.apply(e,_toConsumableArray(this._pipeAccordingToValidationResult()))},hasConstraints:function(){return 0!==this.constraints.length},needsValidation:function(e){return"undefined"==typeof e&&(e=this.getValue()),!(!e.length&&!this._isRequired()&&"undefined"==typeof this.options.validateIfEmpty)},_isInGroup:function(t){return Array.isArray(this.options.group)?-1!==e.inArray(t,this.options.group):this.options.group===t},isValid:function(t){if(arguments.length>=1&&!e.isPlainObject(t)){a.warnOnce("Calling isValid on a parsley field without passing arguments as an object is deprecated.");var i=_slice.call(arguments),n=i[0],r=i[1];t={force:n,value:r}}var s=this.whenValid(t);return!s||A[s.state()]},whenValid:function(){var t=this,i=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],n=i.force,r=void 0!==n&&n,s=i.value,o=i.group,l=i._refreshed;if(l||this.refreshConstraints(),!o||this._isInGroup(o)){if(this.validationResult=!0,!this.hasConstraints())return e.when();if("undefined"!=typeof s&&null!==s||(s=this.getValue()),!this.needsValidation(s)&&!0!==r)return e.when();var u=this._getGroupedConstraints(),d=[];return e.each(u,function(i,n){var r=a.all(e.map(n,function(e){return t._validateConstraint(s,e)}));if(d.push(r),"rejected"===r.state())return!1}),a.all(d)}},_validateConstraint:function(t,i){var n=this,r=i.validate(t,this);return!1===r&&(r=e.Deferred().reject()),a.all([r]).fail(function(e){n.validationResult instanceof Array||(n.validationResult=[]),n.validationResult.push({assert:i,errorMessage:"string"==typeof e&&e})})},getValue:function(){var e;return e="function"==typeof this.options.value?this.options.value(this):"undefined"!=typeof this.options.value?this.options.value:this.$element.val(),"undefined"==typeof e||null===e?"":this._handleWhitespace(e)},reset:function(){return this._resetUI(),this._trigger("reset")},destroy:function(){this._destroyUI(),this.$element.removeData("Parsley"),this.$element.removeData("FieldMultiple"),this._trigger("destroy")},refreshConstraints:function(){return this.actualizeOptions()._bindConstraints()},addConstraint:function(e,t,i,n){if(window.Parsley._validatorRegistry.validators[e]){var r=new F(this,e,t,i,n);"undefined"!==this.constraintsByName[r.name]&&this.removeConstraint(r.name),this.constraints.push(r),this.constraintsByName[r.name]=r}return this},removeConstraint:function(e){for(var t=0;t<this.constraints.length;t++)if(e===this.constraints[t].name){this.constraints.splice(t,1);break}return delete this.constraintsByName[e],this},updateConstraint:function(e,t,i){return this.removeConstraint(e).addConstraint(e,t,i)},_bindConstraints:function(){for(var e=[],t={},i=0;i<this.constraints.length;i++)!1===this.constraints[i].isDomConstraint&&(e.push(this.constraints[i]),t[this.constraints[i].name]=this.constraints[i]);this.constraints=e,this.constraintsByName=t;for(var n in this.options)this.addConstraint(n,this.options[n],void 0,!0);return this._bindHtml5Constraints()},_bindHtml5Constraints:function(){null!==this.element.getAttribute("required")&&this.addConstraint("required",!0,void 0,!0),null!==this.element.getAttribute("pattern")&&this.addConstraint("pattern",this.element.getAttribute("pattern"),void 0,!0);var e=this.element.getAttribute("min"),t=this.element.getAttribute("max");null!==e&&null!==t?this.addConstraint("range",[e,t],void 0,!0):null!==e?this.addConstraint("min",e,void 0,!0):null!==t&&this.addConstraint("max",t,void 0,!0),null!==this.element.getAttribute("minlength")&&null!==this.element.getAttribute("maxlength")?this.addConstraint("length",[this.element.getAttribute("minlength"),this.element.getAttribute("maxlength")],void 0,!0):null!==this.element.getAttribute("minlength")?this.addConstraint("minlength",this.element.getAttribute("minlength"),void 0,!0):null!==this.element.getAttribute("maxlength")&&this.addConstraint("maxlength",this.element.getAttribute("maxlength"),void 0,!0);var i=this.element.type;return"number"===i?this.addConstraint("type",["number",{step:this.element.getAttribute("step")||"1",base:e||this.element.getAttribute("value")}],void 0,!0):/^(email|url|range|date)$/i.test(i)?this.addConstraint("type",i,void 0,!0):this},_isRequired:function(){return"undefined"!=typeof this.constraintsByName.required&&!1!==this.constraintsByName.required.requirements},_trigger:function(e){return this.trigger("field:"+e)},_handleWhitespace:function(e){return!0===this.options.trimValue&&a.warnOnce('data-parsley-trim-value="true" is deprecated, please use data-parsley-whitespace="trim"'),"squish"===this.options.whitespace&&(e=e.replace(/\s{2,}/g," ")),"trim"!==this.options.whitespace&&"squish"!==this.options.whitespace&&!0!==this.options.trimValue||(e=a.trimString(e)),e},_isDateInput:function(){var e=this.constraintsByName.type;return e&&"date"===e.requirements},_getGroupedConstraints:function(){if(!1===this.options.priorityEnabled)return[this.constraints];for(var e=[],t={},i=0;i<this.constraints.length;i++){var n=this.constraints[i].priority;t[n]||e.push(t[n]=[]),t[n].push(this.constraints[i])}return e.sort(function(e,t){return t[0].priority-e[0].priority}),e}};var x=E,$=function(){this.__class__="FieldMultiple"};$.prototype={addElement:function(e){return this.$elements.push(e),this},refreshConstraints:function(){var t;if(this.constraints=[],"SELECT"===this.element.nodeName)return this.actualizeOptions()._bindConstraints(),
this;for(var i=0;i<this.$elements.length;i++)if(e("html").has(this.$elements[i]).length){t=this.$elements[i].data("FieldMultiple").refreshConstraints().constraints;for(var n=0;n<t.length;n++)this.addConstraint(t[n].name,t[n].requirements,t[n].priority,t[n].isDomConstraint)}else this.$elements.splice(i,1);return this},getValue:function(){if("function"==typeof this.options.value)return this.options.value(this);if("undefined"!=typeof this.options.value)return this.options.value;if("INPUT"===this.element.nodeName){if("radio"===this.element.type)return this._findRelated().filter(":checked").val()||"";if("checkbox"===this.element.type){var t=[];return this._findRelated().filter(":checked").each(function(){t.push(e(this).val())}),t}}return"SELECT"===this.element.nodeName&&null===this.$element.val()?[]:this.$element.val()},_init:function(){return this.$elements=[this.$element],this}};var P=function(t,i,n){this.element=t,this.$element=e(t);var r=this.$element.data("Parsley");if(r)return"undefined"!=typeof n&&r.parent===window.Parsley&&(r.parent=n,r._resetOptions(r.options)),"object"==typeof i&&_extends(r.options,i),r;if(!this.$element.length)throw new Error("You must bind Parsley on an existing element.");if("undefined"!=typeof n&&"Form"!==n.__class__)throw new Error("Parent instance must be a Form instance");return this.parent=n||window.Parsley,this.init(i)};P.prototype={init:function(e){return this.__class__="Parsley",this.__version__="2.7.2",this.__id__=a.generateID(),this._resetOptions(e),"FORM"===this.element.nodeName||a.checkAttr(this.element,this.options.namespace,"validate")&&!this.$element.is(this.options.inputs)?this.bind("parsleyForm"):this.isMultiple()?this.handleMultiple():this.bind("parsleyField")},isMultiple:function(){return"radio"===this.element.type||"checkbox"===this.element.type||"SELECT"===this.element.nodeName&&null!==this.element.getAttribute("multiple")},handleMultiple:function(){var t,i,n=this;if(this.options.multiple=this.options.multiple||(t=this.element.getAttribute("name"))||this.element.getAttribute("id"),"SELECT"===this.element.nodeName&&null!==this.element.getAttribute("multiple"))return this.options.multiple=this.options.multiple||this.__id__,this.bind("parsleyFieldMultiple");if(!this.options.multiple)return a.warn("To be bound by Parsley, a radio, a checkbox and a multiple select input must have either a name or a multiple option.",this.$element),this;this.options.multiple=this.options.multiple.replace(/(:|\.|\[|\]|\{|\}|\$)/g,""),t&&e('input[name="'+t+'"]').each(function(e,t){"radio"!==t.type&&"checkbox"!==t.type||t.setAttribute(n.options.namespace+"multiple",n.options.multiple)});for(var r=this._findRelated(),s=0;s<r.length;s++)if(i=e(r.get(s)).data("Parsley"),"undefined"!=typeof i){this.$element.data("FieldMultiple")||i.addElement(this.$element);break}return this.bind("parsleyField",!0),i||this.bind("parsleyFieldMultiple")},bind:function(t,i){var n;switch(t){case"parsleyForm":n=e.extend(new w(this.element,this.domOptions,this.options),new l,window.ParsleyExtend)._bindFields();break;case"parsleyField":n=e.extend(new x(this.element,this.domOptions,this.options,this.parent),new l,window.ParsleyExtend);break;case"parsleyFieldMultiple":n=e.extend(new x(this.element,this.domOptions,this.options,this.parent),new $,new l,window.ParsleyExtend)._init();break;default:throw new Error(t+"is not a supported Parsley type")}return this.options.multiple&&a.setAttr(this.element,this.options.namespace,"multiple",this.options.multiple),"undefined"!=typeof i?(this.$element.data("FieldMultiple",n),n):(this.$element.data("Parsley",n),n._actualizeTriggers(),n._trigger("init"),n)}};var V=e.fn.jquery.split(".");if(parseInt(V[0])<=1&&parseInt(V[1])<8)throw"The loaded version of jQuery is too old. Please upgrade to 1.8.x or better.";V.forEach||a.warn("Parsley requires ES5 to run properly. Please include https://github.com/es-shims/es5-shim");var O=_extends(new l,{element:document,$element:e(document),actualizeOptions:null,_resetOptions:null,Factory:P,version:"2.7.2"});_extends(x.prototype,y.Field,l.prototype),_extends(w.prototype,y.Form,l.prototype),_extends(P.prototype,l.prototype),e.fn.parsley=e.fn.psly=function(t){if(this.length>1){var i=[];return this.each(function(){i.push(e(this).parsley(t))}),i}return e(this).length?new P(this[0],t):void a.warn("You must bind Parsley on an existing element.")},"undefined"==typeof window.ParsleyExtend&&(window.ParsleyExtend={}),O.options=_extends(a.objectCreate(o),window.ParsleyConfig),window.ParsleyConfig=O.options,window.Parsley=window.psly=O,O.Utils=a,window.ParsleyUtils={},e.each(a,function(e,t){"function"==typeof t&&(window.ParsleyUtils[e]=function(){return a.warnOnce("Accessing `window.ParsleyUtils` is deprecated. Use `window.Parsley.Utils` instead."),a[e].apply(a,arguments)})});var M=window.Parsley._validatorRegistry=new p(window.ParsleyConfig.validators,window.ParsleyConfig.i18n);window.ParsleyValidator={},e.each("setLocale addCatalog addMessage addMessages getErrorMessage formatMessage addValidator updateValidator removeValidator".split(" "),function(e,t){window.Parsley[t]=function(){return M[t].apply(M,arguments)},window.ParsleyValidator[t]=function(){var e;return a.warnOnce("Accessing the method '"+t+"' through Validator is deprecated. Simply call 'window.Parsley."+t+"(...)'"),(e=window.Parsley)[t].apply(e,arguments)}}),window.Parsley.UI=y,window.ParsleyUI={removeError:function(e,t,i){var n=!0!==i;return a.warnOnce("Accessing UI is deprecated. Call 'removeError' on the instance directly. Please comment in issue 1073 as to your need to call this method."),e.removeError(t,{updateClass:n})},getErrorsMessages:function(e){return a.warnOnce("Accessing UI is deprecated. Call 'getErrorsMessages' on the instance directly."),e.getErrorsMessages()}},e.each("addError updateError".split(" "),function(e,t){window.ParsleyUI[t]=function(e,i,n,r,s){var o=!0!==s;return a.warnOnce("Accessing UI is deprecated. Call '"+t+"' on the instance directly. Please comment in issue 1073 as to your need to call this method."),e[t](i,{message:n,assert:r,updateClass:o})}}),!1!==window.ParsleyConfig.autoBind&&e(function(){e("[data-parsley-validate]").length&&e("[data-parsley-validate]").parsley()});var T=e({}),R=function(){a.warnOnce("Parsley's pubsub module is deprecated; use the 'on' and 'off' methods on parsley instances or window.Parsley")},D="parsley:";e.listen=function(e,n){var r;if(R(),"object"==typeof arguments[1]&&"function"==typeof arguments[2]&&(r=arguments[1],n=arguments[2]),"function"!=typeof n)throw new Error("Wrong parameters");window.Parsley.on(i(e),t(n,r))},e.listenTo=function(e,n,r){if(R(),!(e instanceof x||e instanceof w))throw new Error("Must give Parsley instance");if("string"!=typeof n||"function"!=typeof r)throw new Error("Wrong parameters");e.on(i(n),t(r))},e.unsubscribe=function(e,t){if(R(),"string"!=typeof e||"function"!=typeof t)throw new Error("Wrong arguments");window.Parsley.off(i(e),t.parsleyAdaptedCallback)},e.unsubscribeTo=function(e,t){if(R(),!(e instanceof x||e instanceof w))throw new Error("Must give Parsley instance");e.off(i(t))},e.unsubscribeAll=function(t){R(),window.Parsley.off(i(t)),e("form,input,textarea,select").each(function(){var n=e(this).data("Parsley");n&&n.off(i(t))})},e.emit=function(e,t){var n;R();var r=t instanceof x||t instanceof w,s=Array.prototype.slice.call(arguments,r?2:1);s.unshift(i(e)),r||(t=window.Parsley),(n=t).trigger.apply(n,_toConsumableArray(s))};e.extend(!0,O,{asyncValidators:{"default":{fn:function(e){return e.status>=200&&e.status<300},url:!1},reverse:{fn:function(e){return e.status<200||e.status>=300},url:!1}},addAsyncValidator:function(e,t,i,n){return O.asyncValidators[e]={fn:t,url:i||!1,options:n||{}},this}}),O.addValidator("remote",{requirementType:{"":"string",validator:"string",reverse:"boolean",options:"object"},validateString:function(t,i,n,r){var s,a,o={},l=n.validator||(!0===n.reverse?"reverse":"default");if("undefined"==typeof O.asyncValidators[l])throw new Error("Calling an undefined async validator: `"+l+"`");i=O.asyncValidators[l].url||i,i.indexOf("{value}")>-1?i=i.replace("{value}",encodeURIComponent(t)):o[r.element.getAttribute("name")||r.element.getAttribute("id")]=t;var u=e.extend(!0,n.options||{},O.asyncValidators[l].options);s=e.extend(!0,{},{url:i,data:o,type:"GET"},u),r.trigger("field:ajaxoptions",r,s),a=e.param(s),"undefined"==typeof O._remoteCache&&(O._remoteCache={});var d=O._remoteCache[a]=O._remoteCache[a]||e.ajax(s),h=function(){var t=O.asyncValidators[l].fn.call(r,d,i,n);return t||(t=e.Deferred().reject()),e.when(t)};return d.then(h,h)},priority:-1}),O.on("form:submit",function(){O._remoteCache={}}),l.prototype.addAsyncValidator=function(){return a.warnOnce("Accessing the method `addAsyncValidator` through an instance is deprecated. Simply call `Parsley.addAsyncValidator(...)`"),O.addAsyncValidator.apply(O,arguments)},O.addMessages("en",{defaultMessage:"This value seems to be invalid.",type:{email:"This value should be a valid email.",url:"This value should be a valid url.",number:"This value should be a valid number.",integer:"This value should be a valid integer.",digits:"This value should be digits.",alphanum:"This value should be alphanumeric."},notblank:"This value should not be blank.",required:"This value is required.",pattern:"This value seems to be invalid.",min:"This value should be greater than or equal to %s.",max:"This value should be lower than or equal to %s.",range:"This value should be between %s and %s.",minlength:"This value is too short. It should have %s characters or more.",maxlength:"This value is too long. It should have %s characters or fewer.",length:"This value length is invalid. It should be between %s and %s characters long.",mincheck:"You must select at least %s choices.",maxcheck:"You must select %s choices or fewer.",check:"You must select between %s and %s choices.",equalto:"This value should be the same."}),O.setLocale("en");var I=new n;I.install();var q=O;return q});
jQuery(document).ready(function(e){function a(e,a){l(e,a),e.find(a.container).first().show()}function n(a,n){if(n.tabs){var t=e("<div />",{"class":n.tabMenuClassName}).insertBefore(a.children(n.container).filter(":first"));a.children(n.container).each(function(i,r){var l=e("<button/>").html(e(this).children(n.header).html()).addClass(0==i?n.tabMenuItemActiveClassName:"").addClass("item"+i).addClass("btn btn-default").prop("type","button").on("click keypress",{container:a.children(n.container),fieldset:e(r)},function(){var t=e(this),i=t.parent().children().index(t);s(a,n,t,i)});n.tabIndex&&l.prop("tabindex",i),t.append(l)})}}function t(a,n){n.navigation&&a.children(n.container).each(function(t){var i=e("<div />").addClass("powermail_fieldwrap").addClass("powermail_tab_navigation").appendTo(e(this));t>0&&i.append(c(a,n)),t<a.children(n.container).length-1&&i.append(o(a,n))})}function i(a,n){e.fn.parsley&&"data-parsley-validate"===a.data("parsley-validate")&&a.parsley().subscribe("parsley:field:validated",function(){v(a,n),C(a,n)})}function r(a,n){n.openTabOnError&&e.fn.parsley&&e.listen("parsley:field:error",function(){setTimeout(function(){a.find("."+n.tabMenuClassName+" > ."+n.tabMenuItemErrorClassName+":first").click()},50)})}function s(a,n,t,i){$activeTab=b(a,n),$activeTab.removeClass(n.tabMenuItemActiveClassName),t.addClass(n.tabMenuItemActiveClassName),l(a,n),e(".powermail_fieldset",a).slice(i,i+1).show()}function l(e,a){e.children(a.container).hide()}function c(a,n){return e("<a />").prop("href","#").addClass("btn btn-warning").html("<").click(function(e){e.preventDefault(),u(a,n)})}function o(a,n){return e("<a />").prop("href","#").addClass("btn btn-primary pull-right").html(">").click(function(e){e.preventDefault(),d(a,n)})}function d(e,a){var n=m(e,a);$activeTab=b(e,a),$activeTab.removeClass(a.tabMenuItemActiveClassName).next().addClass(a.tabMenuItemActiveClassName),f(e,a,n+1)}function u(e,a){var n=m(e,a);$activeTab=b(e,a),$activeTab.removeClass(a.tabMenuItemActiveClassName).prev().addClass(a.tabMenuItemActiveClassName),f(e,a,n-1)}function f(e,a,n){l(e,a),e.find(".powermail_fieldset").slice(n,n+1).show()}function m(e,a){var n=p(e,a),t=n.index(b(e,a));return parseInt(t)}function p(e,a){return e.find("."+a.tabMenuClassName).children()}function b(e,a){var n=p(e,a);return n.filter("."+a.tabMenuItemActiveClassName)}function v(e,a){var n=p(e,a);n.removeClass(a.tabMenuItemErrorClassName)}function C(a,n){a.parsley().isValid()||a.find(".parsley-error").each(function(){var t=a.find(".powermail_fieldset").index(e(this).closest(".powermail_fieldset")),i=p(a,n),r=i.slice(t,t+1);r.addClass(n.tabMenuItemErrorClassName)})}e.fn.powermailTabs=function(e){"use strict";var s=jQuery(this);e=jQuery.extend({container:"fieldset",header:"legend",tabs:!0,navigation:!0,openTabOnError:!0,tabIndex:!0,tabMenuClassName:"btn-group",tabMenuItemActiveClassName:"btn-primary",tabMenuItemErrorClassName:"btn-danger"},e),a(s,e),n(s,e),t(s,e),i(s,e),r(s,e)}});
function PowermailForm(e){"use strict";this.initialize=function(){t(),a(),i(),r(),o(),n(),f(),l()};var t=function(){e.fn.powermailTabs&&e(".powermail_morestep").each(function(){e(this).powermailTabs()})},a=function(){e("form[data-powermail-ajax]").length&&p()},i=function(){if(e('*[data-powermail-location="prefill"]').length&&navigator.geolocation){e(this);navigator.geolocation.getCurrentPosition(function(t){var a=t.coords.latitude,i=t.coords.longitude,r=C()+"/index.php?eID=powermailEidGetLocation";jQuery.ajax({url:r,data:"lat="+a+"&lng="+i,cache:!1,success:function(t){t&&e('*[data-powermail-location="prefill"]').val(t)}})})}},r=function(){e.fn.datetimepicker&&e(".powermail_date").each(function(){var t=e(this);if("date"===t.prop("type")||"datetime-local"===t.prop("type")||"time"===t.prop("type")){if(!t.data("datepicker-force")){if(e(this).data("date-value")){var a=g(e(this).data("date-value"),e(this).data("datepicker-format"),t.prop("type"));null!==a&&e(this).val(a)}return}t.prop("type","text"),t.val(e(this).data("date-value"))}var i=!0,r=!0;"date"===t.data("datepicker-settings")?r=!1:"time"===t.data("datepicker-settings")&&(i=!1),t.datetimepicker({format:t.data("datepicker-format"),timepicker:r,datepicker:i,lang:"en",i18n:{en:{months:t.data("datepicker-months").split(","),dayOfWeek:t.data("datepicker-days").split(",")}}})})},o=function(){e(".powermail_all_type_password.powermail_all_value").html("********")},n=function(){e.fn.parsley&&e(".powermail_reset").on("click","",function(){e('form[data-parsley-validate="data-parsley-validate"]').parsley().reset()})},l=function(){window.Parsley&&(x(),b())},p=function(){var t,a=!1;e(document).on("submit","form[data-powermail-ajax]",function(i){var r=e(this),o=r.closest(".tx-powermail");r.data("powermail-ajax-uri")&&(t=r.data("powermail-ajax-uri"));var n=r.data("powermail-form");a||(e.ajax({type:"POST",url:r.prop("action"),data:new FormData(r.get(0)),contentType:!1,processData:!1,beforeSend:function(){s(r)},complete:function(){d(r),f(),c(o)},success:function(i){var o=e('*[data-powermail-form="'+n+'"]:first',i);o.length?(e('*[data-powermail-form="'+n+'"]:first').closest(".tx-powermail").html(o),e.fn.powermailTabs&&e(".powermail_morestep").powermailTabs(),e.fn.parsley&&e('form[data-parsley-validate="data-parsley-validate"]').parsley(),w()):(t?D(t):r.submit(),a=!0)}}),i.preventDefault())})},s=function(t){d(t),e(".powermail_submit",t).length?e(".powermail_submit",t).parent().append(y()):t.closest(".tx-powermail").append(y())},d=function(e){e.closest(".tx-powermail").find(".powermail_progressbar").remove()},c=function(t){var a=e.Event("submitted.powermail.form");t.trigger(a)},f=function(){e(".powermail_fieldwrap_file").find(".deleteAllFiles").each(function(){u(e(this).closest(".powermail_fieldwrap_file").find('input[type="file"]'))}),e(".deleteAllFiles").click(function(){m(e(this).closest(".powermail_fieldwrap_file").find('input[type="hidden"]')),e(this).closest("ul").fadeOut(function(){e(this).remove()})})},u=function(e){e.prop("disabled","disabled").addClass("hide").prop("type","hidden")},m=function(e){e.prop("disabled",!1).removeClass("hide").prop("type","file")},w=function(){e("img.powermail_captchaimage").each(function(){var t=h(e(this).prop("src"));e(this).prop("src",t+"?hash="+v(5))})},h=function(e){var t=e.split("?");return t[0]},v=function(e){for(var t="",a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",i=0;i<e;i++)t+=a.charAt(Math.floor(Math.random()*a.length));return t},g=function(e,t,a){var i=Date.parseDate(e,t);if(null===i)return null;var r=new Date(i),o=r.getFullYear()+"-";o+=("0"+(r.getMonth()+1)).slice(-2)+"-",o+=("0"+r.getDate()).slice(-2);var n=("0"+r.getHours()).slice(-2)+":"+("0"+r.getMinutes()).slice(-2),l=o+"T"+n;return"date"===a?o:"datetime-local"===a?l:"time"===a?n:null},y=function(){return e("<div />").addClass("powermail_progressbar").html(e("<div />").addClass("powermail_progress").html(e("<div />").addClass("powermail_progess_inner")))},_=function(e){for(var t=e.get(0),a=0,i=0;i<t.files.length;i++){var r=t.files[i];r.size>a&&(a=r.size)}return parseInt(a)},x=function(){window.Parsley.addValidator("powermailfilesize",function(t,a){if(a.indexOf(",")!==-1){var i=a.split(","),r=parseInt(i[0]),o=e('*[name="tx_powermail_pi1[field]['+i[1]+'][]"]');if(o.length&&_(o)>r)return!1}return!0},32).addMessage("en","powermailfilesize","Error")},b=function(){window.Parsley.addValidator("powermailfileextensions",function(t,a){var i=e('*[name="tx_powermail_pi1[field]['+a+'][]"]');return!i.length||k(j(t),i.prop("accept"))},32).addMessage("en","powermailfileextensions","Error")},k=function(e,t){return t.indexOf("."+e)!==-1},j=function(e){return e.split(".").pop().toLowerCase()},D=function(e){e.indexOf("http")!==-1?window.location=e:window.location.pathname=e},C=function(){var t;return t=e("base").length>0?jQuery("base").prop("href"):"https:"!=window.location.protocol?"http://"+window.location.hostname:"https://"+window.location.hostname}}jQuery(document).ready(function(e){"use strict";var t=new window.PowermailForm(e);t.initialize()});
jQuery(function () {
  $('#powermail_field_iban').mask('SS00 0000 0000 0000 0000 0000 0000 0000');

  // change IBAN to uppercase in FE
  $('#powermail_field_iban').change(function() {
    $('#powermail_field_iban').val($('#powermail_field_iban').val().toUpperCase());
  });

  window.Parsley.addValidator(
    'custom200',
    function (value) {
      return IBAN.isValid(value.toUpperCase());
    },
    32
  ).addMessage('de', 'custom200', 'Error');

  window.Parsley.addValidator(
    'custom201',
    function (value) {
      if (IBAN.isValid(value.toUpperCase())) {
        if (
          value.trim().substring(0, 2).toUpperCase() == 'DE' ||
          value.trim().substring(0, 2).toUpperCase() == 'LU' ||
          value.trim().substring(0, 2).toUpperCase() == 'AT'
        ) {
          return true;
        }
      }
      return false;
    },
    32
  ).addMessage('de', 'custom201', 'Error');

  window.Parsley.addValidator(
    'custom210',
    function (value) {
      return /^([A-Z]{6}[A-Z2-9][A-NP-Z1-2])(X{3}|[A-WY-Z0-9][A-Z0-9]{2})?$/.test(
        value.toUpperCase()
      );
    },
    32
  ).addMessage('de', 'custom210', 'Error');

  window.Parsley.addValidator(
    'custom220',
    function (value, requirement) {
      if (requirement) {
        $eMailField = $(requirement);

        /* if the emailField changes validate custom220 again, because the fields belong together */
        $eMailField.on('change', function () {
          $('input[data-parsley-custom220="' + requirement + '"]')
            .parsley()
            .validate();
        });
        return $eMailField.val().toLowerCase() == value.toLowerCase();
      }
      return false;
    },
    32
  ).addMessage('de', 'custom220', 'Error');

  window.Parsley.addValidator(
    'custom230',
    function (value, requirement) {
      var pattern = new RegExp(requirement);
      return pattern.test(value);
    },
    32
  ).addMessage('de', 'custom230', 'Error');

  window.Parsley.addValidator(
    'custom240',
    function (value, requirement) {
      if (value.indexOf('@') === -1) {
        return true;
      }
      return false;
    },
    32
  ).addMessage('de', 'custom240', 'Error');
    /* newsletter form */
    newsletterFormAjax.init();
    /* preparation on submit */
    enrichFormData.init();

  /* termination form */
  terminationFormAjax.init();
  
  /* scroll to form confirmation */
  if ($('.tx-powermail .powermail_confirmation').length) {
    $('html, body').animate({
      scrollTop: $(".tx-powermail .powermail_confirmation").offset().top - 100
    }, 500);
  }


  var originContractUid = $('.form-data').data('origin'),
    $voucherValidateBtn = $('#powermail_field_voucher_validate'),
    $voucherRemoveBtn = $('#powermail_field_voucher_remove'),
    $voucherCodeInput = $('#powermail_field_voucher');

  $voucherValidateBtn.on('click', function (event) {
    var value = $voucherCodeInput.val();
    if (value !== '') {
      validateVoucher(value, false);
    }
  });

  $voucherCodeInput.keyup(function () {
    if ($(this).val().length !== 0 && $(this).prop('readonly') === false) {
      $voucherValidateBtn.show();
    } else {
      $voucherValidateBtn.hide();
    }
  });

  $voucherCodeInput.on('keypress', function (event) {
    var key = event.which;
    var $spinner = $('.powermail_field_voucher_wrapper .spinner-loader');
    if (key === 13 && $voucherCodeInput.val() !== '') {
      // the enter key code
      event.preventDefault();
      if ($spinner.is(':visible') && !$(this).is('[readonly]')) {
        var value = $voucherCodeInput.val();
        if (value !== '') {
          validateVoucher(value, false);
        }
      }
    }
  });

  $voucherRemoveBtn.on('click', function (event) {
    validateVoucher(originContractUid, originContractUid);
  });

  // show loading spinner on termination confirmation form submit
  var submitted = false;
  $('.termination_confirmation form').on('submit', function (event) {
    $('.termination_confirmation').addClass('loading');

    // disable future submit events
    if (submitted) {
      event.preventDefault();
      return false;
    }
    submitted = true;
  });
});

var newsletterFormAjax = (function () {
  var formWrapper = '.js-newsletter-teaser-ajax'; 

  /**
   * Le Constructor.
   */
  function initialize() {
    if (typeof $(formWrapper).get(0) === 'undefined') {
      return;
    }

    $(formWrapper).each(function () {
      var wrapper = $(this).parent();
      var form = $(this).find('form');

      var typeNum = 1552375384; 

      formTypenum = form.find(".powermail_hidden.powermail_formtypenum").val();
     
      if(typeof formTypenum != "undefined" && formTypenum) {
        typeNum = formTypenum;
      }

      // only bind action when not already initialized
      if ($(this).hasClass('initialized')) {
        return;
      }

      $(this).addClass('initialized');
      form.on('submit', function (event) {
        event.preventDefault();
        doAjaxRequest($(this), form, wrapper, typeNum);
      });
    });
  }

  /**
   * @param element
   * @param form
   * @param wrapper
   */
  function doAjaxRequest(element, form, wrapper, typeNum) {
    var request;

    request = $.ajax({
      url: form.attr('action') + '&type=' + typeNum,
      method: form.attr('method'),
      data: form.serialize(),
      beforeSend: function () {
        element.css('opacity', '0.5');
        form.find('[type=submit]').attr('disabled', 'disabled');
        wrapper.find('.spinner').removeClass('hide');
      },
    });

    // show response
    request.done(function (data) {
      wrapper.html(data);
      initialize();
    });

    // show error
    request.fail(function (jqXHR, textStatus, errorThrown) {
      Sentry.captureException(errorThrown);
      wrapper.html(
        'Während der Abfrage ist ein Fehler aufgetreten, bitte versuchen Sie es später erneut'
      );
    });
  }

  /**
   * public api
   */
  return {
    init: function () {
      initialize();
    },
  };
})();

var enrichFormData = (function () {
    var _form = $('#club-registration-form').find('form')[0];
    var disabled = false;

    function _initialize() {
        if (typeof _form === 'undefined') {
            return;
        }
        _updateSessionHash();

        $('#powermail_field_strasseundnr_01_1').on('focusout', function () {
            _geocodeUserAddress()
        });
        $('#powermail_field_strasseundnr_01_2').on('focusout', function () {
            _geocodeUserAddress()
        });
        $('[name="tx_powermail_pi1[field][plz]"]').on('focusout', function () {
            _geocodeUserAddress()
        });
        $('[name="tx_powermail_pi1[field][ort]"]').on('focusout', function () {
            _geocodeUserAddress()
        });

        $(_form).on('submit', function () {
            _handleSubmit()
        })
    }

    function _handleSubmit() {
        if ($(_form).data('enriched') === true) {
            return true;
        }
        event.preventDefault();
        $(_form).data('enriched', true).submit();
    }

    function _updateSessionHash() {
        var hash = $.sha256($('[name="tx_powermail_pi1[field][email]"]').val() + Date.now() + Math.random().toString(16).substr(2, 12));
        $('[name="tx_powermail_pi1[field][session]"]').val(hash);
        Cookies.set('sessionhash', hash, { expires: 0.083 }); // 0.083 day = 1h
    }

    function _isAddressCompleted() {
        return ($('#powermail_field_strasseundnr_01_1').val() !== ''
            && $('#powermail_field_strasseundnr_01_2').val() !== ''
            && $('[name="tx_powermail_pi1[field][plz]"]').val() !== ''
            && $('[name="tx_powermail_pi1[field][ort]"]').val())
    }

    function _geocodeUserAddress() {
        if (
            !_isAddressCompleted()
            || ($('#powermail_field_land').val() !== ''
                && $('#powermail_field_bundesland').val() !== '')
        ) {
            return;
        }
        var geocoder = new google.maps.Geocoder;
        var address = [
            $('#powermail_field_strasseundnr_01_1').val() + ' ' + $('#powermail_field_strasseundnr_01_2').val(),
            $('[name="tx_powermail_pi1[field][plz]"]').val(),
            $('[name="tx_powermail_pi1[field][ort]"]').val()
        ];

        geocoder.geocode({'address': address.join(', ')}, function (results) {
            if (results === null) {
                disabled = true;
                _errorAddress();
            }
            for (var i = 0; i < results.length; i++) {
                var addressComponents = results[i]['address_components']
                for (var j = 0; j < addressComponents.length; j++) {
                    if (addressComponents[j].types[0] === 'administrative_area_level_1') {
                        var state = addressComponents[j].short_name;
                        $('#powermail_field_bundesland').val(state);
                    }
                    if (addressComponents[j].types[0] === 'country') {
                        var country = addressComponents[j].short_name
                        $('#powermail_field_land').val(country);
                    }
                }
            }
            disabled = false;
        });
    }

    function _errorAddress() {
        $('#powermail_field_strasseundnr_01_1').addClass('parsley-error');
        $('#powermail_field_strasseundnr_01_2').addClass('parsley-error');
        $('[name="tx_powermail_pi1[field][plz]"]').addClass('parsley-error');
        $('[name="tx_powermail_pi1[field][ort]"]').addClass('parsley-error');
        var errorMessage = '<p class="error">Die Adresse ist ungültig, bitte überprüfen Sie Ihre Eingaben</p>';
        $('.club-selected-datainfobox-wrapper').prepend(errorMessage);
    }

    return {
        init: function () {
            _initialize();
        }
    }
})();

var terminationFormAjax = (function () {
  var formWrapper = '#powermailform17'; //
  var formSelector = '.form-termination';
  var typeNum = 1655296380;

  function toggleTerminationFormField(showDateField) {
    var kuendigungzumdatum = $(
        'label[for="powermail_field_kuendigungzumdatum"]'
    );
    var kuendigungzumdatumText = kuendigungzumdatum.text();

    if ( showDateField ) {
      kuendigungzumdatumText = kuendigungzumdatumText.replaceAll('*', '');
      kuendigungzumdatum.text(kuendigungzumdatumText + '*');
      $('.powermail_fieldwrap_kuendigungzumdatum').show();
    } else {
      kuendigungzumdatum.text(kuendigungzumdatumText.replaceAll('*', ''));
      $('.powermail_fieldwrap_kuendigungzumdatum').hide();
    }
  }


  /**
   * Le Constructor.
   */
  function initialize() {
    $(formWrapper).each(function () {
      // initialize toggled termination field status
      toggleTerminationFormField(
          (
              $('#powermail_field_kuendigungszeitpunkt_3').is(':checked')
          )
      );

      //Make other required
      $('#powermail_field_kuendigungszeitpunkt_1').change(function () {
        $('#powermail_field_kuendigungzumdatum').attr('required', false);

        toggleTerminationFormField(false);
      });

      $('#powermail_field_kuendigungszeitpunkt_2').change(function (e) {
        if ($(this).is(':checked')) {
          $('#powermail_field_kuendigungzumdatum').attr('required', false);

          toggleTerminationFormField(false);
        }
      });

      $('#powermail_field_kuendigungszeitpunkt_3').change(function (e) {
        if ($(this).is(':checked')) {
          $('#powermail_field_kuendigungzumdatum').attr('required', 'required');

          toggleTerminationFormField(true);
        }
      });
    });

    var form = $(formSelector);

    // only bind action when not already initialized
    if ($(this).hasClass('initialized')) {
      return;
    }

    $(this).addClass('initialized');
    var hasTypeNum = false;
    form.bind('submit', function (e) {
      if (!hasTypeNum) {
        e.preventDefault();

        var action = form.attr('action') + '&type=' + typeNum;
        form.attr('action', action);
        hasTypeNum = true;
        form.submit();
      }
    });
  }

  /**
   * public api
   */
  return {
    init: function () {
      initialize();
    },
  };
})();

function validateVoucher(code, origin) {
  var $voucherCodeInput = $('#powermail_field_voucher'),
    contract = $('#powermail_field_contractuid').val(),
    $voucherUidInput = $('#powermail_field_voucheruid'),
    $voucherResponseContainer = $('#powermail_field_voucher_response'),
    $voucherValidateBtn = $('#powermail_field_voucher_validate'),
    $voucherRemoveBtn = $('#powermail_field_voucher_remove'),
    $contractData = $('.contract-data'),
    $contractInsteadPrice = $('.insteadPriceLayer'),
    $contractExitIntent = $('.exit-intent-layer'),
    $contractContentElements = $('.contract-content-elements'),
    $spinner = $('.powermail_field_voucher_wrapper .spinner-loader'),
    $formData = $('.form-data'),
    studio = $formData.data('studiouid'),
    $contractUidInput = $(
      'input[name="tx_szstudiofinder_pi1[contractuid]"], input[name="tx_szstudiofinder_pi1[contract]"]'
    ),
    $contractPromotionInput = $(
      'input[name="tx_powermail_pi1[field][aktion]"]'
    ),
    postData = {
      'tx_szstudiofinder_pi1[code]': code,
      'tx_szstudiofinder_pi1[studio]': studio,
      'tx_szstudiofinder_pi1[contract]': contract,
      'tx_szstudiofinder_pi1[origin]': origin,
      type: 1564562434,
    };

  $spinner.show();

  $.ajax({
    url: $voucherCodeInput.data('validationurl'),
    method: 'POST',
    data: postData,
  }).done(function (data) {
    data = JSON.parse(data);

    $voucherResponseContainer.empty().html(data.message);
    $voucherResponseContainer.attr('class', data.class);

    if (data.success) {
      $contractUidInput.val(data.contractUid);
      $contractContentElements.html(data.contentElements);
      $contractData.html(data.contractData);
      $contractInsteadPrice.html(data.insteadPriceLayer);
      $contractExitIntent.html(data.exitIntent);
      $voucherUidInput.val(data.voucherUid);
      $contractPromotionInput.val(data.contractpromotion);
      $('.voucher-product').html(data.product);

      $formData.data('contractuid', data.contractUid);
      $formData.data('contractrunningtime', data.contractrunningtime);
      $formData.data('contracttitle', data.contracttitle);
      $formData.data(
        'contractmonthlycontributions',
        data.contractmonthlycontributions
      );
      $formData.data('aktion', data.contractpromotion);
      $formData.data('transactiontotal', data.transactiontotal);

      if (origin) {
        $voucherRemoveBtn.hide();
        $voucherCodeInput.val('');
        $voucherUidInput.val('');
        $voucherCodeInput.attr('readonly', false);
        $voucherValidateBtn.hide();
      } else {
        $voucherRemoveBtn.show();
        $voucherValidateBtn.hide();
        $voucherCodeInput.attr('readonly', true);
      }

      initExitIntentLayer();
      initOnlineForm();
    } else {
      $voucherCodeInput.attr('readonly', false);
      $voucherRemoveBtn.hide();
      $voucherValidateBtn.show();
    }
    $spinner.hide();
  });
}

/*!
 * JavaScript Cookie v2.0.3
 * https://github.com/js-cookie/js-cookie
 *
 * Copyright 2006, 2015 Klaus Hartl & Fagner Brack
 * Released under the MIT license
 */
(function (factory) {
	if (typeof define === 'function' && define.amd) {
		define(factory);
	} else if (typeof exports === 'object') {
		module.exports = factory();
	} else {
		var _OldCookies = window.Cookies;
		var api = window.Cookies = factory();
		api.noConflict = function () {
			window.Cookies = _OldCookies;
			return api;
		};
	}
}(function () {
	function extend() {
		var i = 0;
		var result = {};
		for (; i < arguments.length; i++) {
			var attributes = arguments[i];
			for (var key in attributes) {
				result[key] = attributes[key];
			}
		}
		return result;
	}

	function init(converter) {
		function api(key, value, attributes) {
			var result;

			// Write

			if (arguments.length > 1) {
				attributes = extend({
					path: '/'
				}, api.defaults, attributes);

				if (typeof attributes.expires === 'number') {
					var expires = new Date();
					expires.setMilliseconds(expires.getMilliseconds() + attributes.expires * 864e+5);
					attributes.expires = expires;
				}

				try {
					result = JSON.stringify(value);
					if (/^[\{\[]/.test(result)) {
						value = result;
					}
				} catch (e) {
				}

				value = encodeURIComponent(String(value));
				value = value.replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g, decodeURIComponent);

				key = encodeURIComponent(String(key));
				key = key.replace(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent);
				key = key.replace(/[\(\)]/g, escape);

				return (document.cookie = [
					key, '=', value,
					attributes.expires && '; expires=' + attributes.expires.toUTCString(), // use expires attribute, max-age is not supported by IE
					attributes.path && '; path=' + attributes.path,
					attributes.domain && '; domain=' + attributes.domain,
					attributes.secure ? '; secure' : ''
				].join(''));
			}

			// Read

			if (!key) {
				result = {};
			}

			// To prevent the for loop in the first place assign an empty array
			// in case there are no cookies at all. Also prevents odd result when
			// calling "get()"
			var cookies = document.cookie ? document.cookie.split('; ') : [];
			var rdecode = /(%[0-9A-Z]{2})+/g;
			var i = 0;

			for (; i < cookies.length; i++) {
				var parts = cookies[i].split('=');
				var name = parts[0].replace(rdecode, decodeURIComponent);
				var cookie = parts.slice(1).join('=');

				if (cookie.charAt(0) === '"') {
					cookie = cookie.slice(1, -1);
				}

				try {
					cookie = converter && converter(cookie, name) || cookie.replace(rdecode, decodeURIComponent);

					if (this.json) {
						try {
							cookie = JSON.parse(cookie);
						} catch (e) {
						}
					}

					if (key === name) {
						result = cookie;
						break;
					}

					if (!key) {
						result[name] = cookie;
					}
				} catch (e) {
				}
			}

			return result;
		}

		api.get = api.set = api;
		api.getJSON = function () {
			return api.apply({
				json: true
			}, [].slice.call(arguments));
		};
		api.defaults = {};

		api.remove = function (key, attributes) {
			api(key, '', extend(attributes, {
				expires: -1
			}));
		};

		api.withConverter = init;

		return api;
	}

	return init();
}));

//We trigger our target ":usercentrics-modal" which comes from the backend
//This is a workaround, because we can't add classes to a-href in this existing instance of the project
jQuery('a[target="_usercentrics-modal"]').on('click', function(e) {
    e.preventDefault();

    UC_UI.showSecondLayer();
});
(function ($) {
    'use strict';

    var initCouponsGenerator = function () {
        var pageType = 1498562210;
        var $form = $('.form-coupon');
        $form.bind('submit', function (e) {
            var $this = $(this);
            $this.find('.btn').prop('disabled', true);
            $this.find('#loading').removeClass('hidden');
            e.preventDefault();
            $.ajax({
                type: $this.attr('method'),
                url: $this.attr('action') + '&type=' + pageType,
                data: $this.serialize(),
                success: function (response) {
                    $this.find('.btn').prop('disabled', false);
                    $this.find('#loading').addClass('hidden');
                    $this.find('.response').html(response);

                    // show survey on successful coupon sending from sunpoint
                    /*if (location.origin.indexOf('sunpoint.de') >= 0 && response.indexOf('alert-success') >= 0) {
                        (function() {
                            var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
                            po.src = ["https:"===location.protocol?"https://":"http://","widget.surveymonkey.com/collect/website/js/tRaiETqnLgj758hTBazgd58Sh7FD2u7lD2o3CJj2F0nLyz_2FEKzAMJfwnFvVG3Le5.js"].join("");
                            var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
                        })();
                    }*/

                },
                error: function (error) {
                    console.error(error);
                }
            });
        });
    };

    $(function () {
        initCouponsGenerator();
    });
})(jQuery);

/*
 * jQuery SameHeight plugin
 */
;(function($){
    $.fn.sameHeight = function(opt) {
        var options = $.extend({
            skipClass: 'same-height-ignore',
            leftEdgeClass: 'same-height-left',
            rightEdgeClass: 'same-height-right',
            elements: '>*',
            flexible: false,
            multiLine: false,
            useMinHeight: false,
            biggestHeight: false
        },opt);
        return this.each(function(){
            var holder = $(this), postResizeTimer, ignoreResize;
            var elements = holder.find(options.elements).not('.' + options.skipClass);
            if(!elements.length) return;

            // resize handler
            function doResize() {
                elements.css(options.useMinHeight && supportMinHeight ? 'minHeight' : 'height', '');
                if(options.multiLine) {
                    // resize elements row by row
                    resizeElementsByRows(elements, options);
                } else {
                    // resize elements by holder
                    resizeElements(elements, holder, options);
                }
            }
            doResize();

            // handle flexible layout / font resize
            var delayedResizeHandler = function() {
                if(!ignoreResize) {
                    ignoreResize = true;
                    doResize();
                    clearTimeout(postResizeTimer);
                    postResizeTimer = setTimeout(function() {
                        doResize();
                        setTimeout(function(){
                            ignoreResize = false;
                        }, 10);
                    }, 100);
                }
            };

            // handle flexible/responsive layout
            if(options.flexible) {
                $(window).bind('resize orientationchange fontresize', delayedResizeHandler);
            }

            // handle complete page load including images and fonts
            $(window).bind('load', delayedResizeHandler);
        });
    };

    // detect css min-height support
    var supportMinHeight = typeof document.documentElement.style.maxHeight !== 'undefined';

    // get elements by rows
    function resizeElementsByRows(boxes, options) {
        var currentRow = $(), maxHeight, maxCalcHeight = 0, firstOffset = boxes.eq(0).offset().top;
        boxes.each(function(ind){
            var curItem = $(this);
            if(curItem.offset().top === firstOffset) {
                currentRow = currentRow.add(this);
            } else {
                maxHeight = getMaxHeight(currentRow);
                maxCalcHeight = Math.max(maxCalcHeight, resizeElements(currentRow, maxHeight, options));
                currentRow = curItem;
                firstOffset = curItem.offset().top;
            }
        });
        if(currentRow.length) {
            maxHeight = getMaxHeight(currentRow);
            maxCalcHeight = Math.max(maxCalcHeight, resizeElements(currentRow, maxHeight, options));
        }
        if(options.biggestHeight) {
            boxes.css(options.useMinHeight && supportMinHeight ? 'minHeight' : 'height', maxCalcHeight);
        }
    }

    // calculate max element height
    function getMaxHeight(boxes) {
        var maxHeight = 0;
        boxes.each(function(){
            maxHeight = Math.max(maxHeight, $(this).outerHeight());
        });
        return maxHeight;
    }

    // resize helper function
    function resizeElements(boxes, parent, options) {
        var calcHeight;
        var parentHeight = typeof parent === 'number' ? parent : parent.height();
        boxes.removeClass(options.leftEdgeClass).removeClass(options.rightEdgeClass).each(function(i){
            var element = $(this);
            var depthDiffHeight = 0;
            var isBorderBox = element.css('boxSizing') === 'border-box' || element.css('-moz-box-sizing') === 'border-box' || element.css('-webkit-box-sizing') === 'border-box';

            if(typeof parent !== 'number') {
                element.parents().each(function(){
                    var tmpParent = $(this);
                    if(parent.is(this)) {
                        return false;
                    } else {
                        depthDiffHeight += tmpParent.outerHeight() - tmpParent.height();
                    }
                });
            }
            calcHeight = parentHeight - depthDiffHeight;
            calcHeight -= isBorderBox ? 0 : element.outerHeight() - element.height();

            if(calcHeight > 0) {
                element.css(options.useMinHeight && supportMinHeight ? 'minHeight' : 'height', calcHeight);
            }
        });
        boxes.filter(':first').addClass(options.leftEdgeClass);
        boxes.filter(':last').addClass(options.rightEdgeClass);
        return calcHeight;
    }
}(jQuery));
//Callback function from googleMaps to trigger the studioFinder Elements
//See Packages/sz_studio_finder/Configuration/TypoScript/setup.txt, line 41.
window.studioFinderCallback = function() {
    initContacts();
    initSameHeight();
    initOnlineForm();
    scrollToCouponBeginning();
}

function initContacts() {
    jQuery('.szStudioFinderMap').each(function () {
        var holder = jQuery(this);

        holder.data('szStudioFinder', new szStudioFinder({
            holder: this,
            map: ($('.map-canvas').length > 0) ? '.map-canvas' : null,
            listOnly: true,
            autocomplete: '.szStudioFinderAutoComplete',
            searchform: '.szStudioFinderSearchForm',
            navigator: '.szStudioFinderGeolocation',
            category: '.szStudioFinderCategory',
            coupon: '.szStudioFinderCoupon',
            itemWrap: '.szStudioFinderItemWrap',
            item: '.marker-info',
            affiliation: holder.data('affiliation'),
            detailLink: '.detail-page',
            //zoomMoreIn: true
        }));
    });
    jQuery('.szStudioFinderOnlineForm').each(function () {
        // var holder = jQuery(this);
        //
        // holder.data('szStudioFinder', new szStudioFinder({
        //     holder: this,
        //     map: ($('.map-canvas').length > 0) ? '.map-canvas' : null,
        //     listOnly: true,
        //     autocomplete: '.szStudioFinderAutoComplete',
        //     searchform: '.szStudioFinderSearchForm',
        //     navigator: '.szStudioFinderGeolocation',
        //     itemWrap: '.szStudioFinderItemWrap',
        //     item: '.marker-info',
        //     affiliation: holder.data('affiliation'),
        //     detailLink: '.detail-page'
        // }));
      var holder = jQuery(this);

      initNewMapSearch(holder);
      initGetCurrentPositionButton(holder);

    });
    jQuery('.szStudioFinderMapTeaser').each(function () {
        var holder = jQuery(this);

        holder.data('szStudioFinder', new szStudioFinder({
            holder: this,
            teaser: true,
            map: '.map-canvas',
            autocomplete: '.szStudioFinderAutoComplete',
            searchform: '.szStudioFinderSearchForm',
            navigator: '.szStudioFinderGeolocation',
            itemWrap: '.szStudioFinderItemWrap',
            item: '.marker-info',
            radius: 50,
            affiliation: holder.data('affiliation'),
            detailLink: '.detail-page'
        }));
    });
    jQuery('.szStudioFinderSearchTeaser').each(function () {
        var holder = jQuery(this);

        holder.data('szStudioFinder', new szStudioFinder({
            holder: this,
            autocomplete: '.szStudioFinderAutoComplete',
            searchform: '.szStudioFinderSearchForm',
            navigator: '.szStudioFinderGeolocation'
        }));
    });


    jQuery('.szStudioDetailMap').each(function () {
        var holder = jQuery(this);

        holder.data('szStudioFinder', new szStudioFinder({
            holder: this,
            map: '.map-canvas',
            item: '.marker-info',
            itemWrap: '.szStudioFinderItemWrap',
            affiliation: holder.data('affiliation'),
            zoomMoreIn: false,
            cluster: false,
            defaultMarkerImageName: 'custom-cluster-pin-icon.png',
            markerZoom: 15
        }));
    });


    // fix for IE 11 for formsubmits
  $('.tx-sz-studio-finder .club-selected-datainfobox button').on('click', function(event) {
    event.preventDefault();

    var formid = $(this).attr('form');
    $( "#"+formid ).submit();
  });
  $('.tx-sz-studio-finder .club-selected-datainfobox button').on('keypress', function(event) {
    event.preventDefault();

    var key = event.which;
    if(key == 13)  // the enter key code
    {
      var formid = $(this).attr('form');
      $( "#"+formid ).submit();
      return false;
    }
  });

  // Check if form entries are valid and push dataLayer before continuing form submit
  var isSubmittable = false;
  var isSubmitted = false;
  var isLoadingSubmittedPage = false;

  var parsleyFormId = $('.tx-sz-studio-finder .club-selected-datainfobox button').attr('form');
  $('#'+parsleyFormId).submit(function(e) {
    self = this;

    if (!isSubmittable) {
      e.preventDefault();
    }
    if (!isSubmitted) {
      if ( $(this).parsley().isValid() ) {
        isSubmittable = true;
        isSubmitted = true;

        virtualPageURL = '/submit';
        virtualPageTitle = 'Submit Form';

        if (typeof codeCeptionTest !== 'undefined' && codeCeptionTest) {
            virtualPageURL = '/submit-test';
        }

        // voucher check on submit
        var $spinner = $('.powermail_field_voucher_wrapper .spinner-loader');
        var $voucherCodeInput = $('#powermail_field_voucher');
        var voucherValue = $voucherCodeInput.val();
        if (!$voucherCodeInput.is('[readonly]') && voucherValue !== '') {
            if ($('#powermail_field_voucher').length) {
                $('html,body').animate({scrollTop: $('#powermail_field_voucher').offset().top - 90}, 'slow');
            }
            validateVoucher(voucherValue, false);
            voucherTimeout = setInterval(function() {
                if ($voucherCodeInput.is('[readonly]')) { // voucher code was valid and redeemed

                    if (typeof dataLayer !== 'undefined' && typeof google_tag_manager === 'object') {
                        console.log('tracking -> Clubmitgliedschaft: ' + virtualPageURL);
                        dataLayer.push({
                            'event': 'Clubmitgliedschaft',
                            'virtualPageURL': virtualPageURL,
                            'virtualPageTitle': virtualPageTitle,
                            'studioTitle': $('.form-data').data('studiotitle'),
                            'transactionTotal': $('.form-data').data('transactiontotal'),
                            'transactionId': randomId(),
                            'eventCallback': function() {
                                if (!isLoadingSubmittedPage) {
                                    $('.club-selected-datainfobox').addClass('loading');
                                    $(self).submit();
                                    $('button.btn-info').prop('disabled','disabled');
                                }
                                isLoadingSubmittedPage = true;
                            }
                        });
                    }

                    // form submit fallback if dataLayer push failed
                    setTimeout(function() {
                        if (isLoadingSubmittedPage === false) {
                            console.log('form submit fallback if dataLayer push failed');
                            $('.club-selected-datainfobox').addClass('loading');
                            $(self).submit();
                            $('button.btn-info').prop('disabled','disabled');
                        }
                    }, 2000);

                    clearInterval(voucherTimeout);
                }
            }, 300);
        } else {
            if (typeof dataLayer !== 'undefined' && typeof google_tag_manager === 'object') {
                console.log('tracking -> Clubmitgliedschaft: ' + virtualPageURL);
                dataLayer.push({
                    'event': 'Clubmitgliedschaft',
                    'virtualPageURL': virtualPageURL,
                    'virtualPageTitle': virtualPageTitle,
                    'studioTitle': $('.form-data').data('studiotitle'),
                    'transactionTotal': $('.form-data').data('transactiontotal'),
                    'transactionId': randomId(),
                    'eventCallback': function() {
                        if (!isLoadingSubmittedPage) {
                            $('.club-selected-datainfobox').addClass('loading');
                            $(self).submit();
                            $('button.btn-info').prop('disabled','disabled');
                        }
                        isLoadingSubmittedPage = true;
                    }
                });
            }

            // form submit fallback if dataLayer push failed
            setTimeout(function() {
                if (isLoadingSubmittedPage === false) {
                    console.log('form submit fallback if dataLayer push failed');
                    $('.club-selected-datainfobox').addClass('loading');
                    $(self).submit();
                    $('button.btn-info').prop('disabled','disabled');
                }
            }, 2000);
        }


      } else {
        isSubmittable = false;
        isSubmitted = false;
      }
    }
  });

}

// align blocks height
function initSameHeight() {
    jQuery('.filter-area .contract').sameHeight({
        elements: '.contract-box .body-text',
        flexible: true,
        multiLine: true,
        biggestHeight: true
    });
}

function initOnlineForm() {
    var holder = jQuery('.tx-sz-studio-finder .filter-area');
    if (holder.length) {
        preFillPowermailForm(holder);
        setClubCardReceivingOptions(holder);
        setAktionInfo(holder);
        initExitIntentLayer();

        if (holder.find('.filter-steps').length) {
            onlineFormSteps(holder);
            $(document).ajaxComplete(function(event, xhr) {
                trackingOnlineForm(xhr.responseText);
                initCustomForms();
                onlineFormSteps(holder);
                fillAccountOwner(holder.find('.form-data form.form'));
                setClubCardReceivingOptions(holder, true);
                setAktionInfo(holder);
            });
        }
    }
}

function trackingOnlineForm(response) {
    var virtualPageURL = '',
        virtualPageTitle = '';

    if($('.powermail_form', response).length >= 1) {
        virtualPageURL = '/check';
        virtualPageTitle = 'Check Form';
    }
    if($('.powermail_confirmation', response).length >= 1) {
        virtualPageURL = '/confirmation';
        virtualPageTitle = 'Confirmation Form';

        $(document).on('click', ":submit", function (e) {
            // For security reason, disable button after send
            var that = this;
            setTimeout(function () { $(that).prop('disabled','disabled'); }, 0);
        });
    }
    if($('.powermail_create', response).length >= 1) {
        virtualPageURL = '/submit';
        virtualPageTitle = 'Submit Form';

        // hide info box after form submit
        $('.club-selected-datainfobox').hide();

        // change to last step after submit
        $('.new-step-line .step-item.active .num').addClass('checked').html('');
        $('.new-step-line .step-item.active').removeClass('active');
        $('.new-step-line .step-item:last-child').addClass('active');
    }

    console.log('tracking -> Clubmitgliedschaft: ' + virtualPageURL);
    if (virtualPageURL && typeof dataLayer !== 'undefined') {
        dataLayer.push({
            event: 'Clubmitgliedschaft',
            virtualPageURL: virtualPageURL,
            virtualPageTitle: virtualPageTitle,
            studioTitle: $('.form-data').data('studiotitle'),
            transactionTotal: $('.form-data').data('transactiontotal'),
            transactionId: randomId()
        });
    }
}

function onlineFormSteps(holder) {
    var offset = 15;
    var steps = (holder.find('#step-3').length) ? holder.find('#step-3') : holder.find('#step-2');
    if ($(window).width() < 991) {
        var fixedBlockHolder = find('.fixed-block-holder');
        if (fixedBlockHolder.length) {
            offset =+ fixedBlockHolder.height();
        }
    }

    // only allow scrolling down
    if ((steps.offset().top - offset) > $(window).scrollTop()) {
        $('html, body').animate({
            scrollTop: steps.offset().top - offset
        }, 1000);
    }
}

function preFillPowermailForm(holder) {
    var appendRegex = /^(append)/;
    var dataHolder  = holder.find('.form-data');
    if (dataHolder.length) {
        var form = dataHolder.find('form.form');
        var field;
        $.each(dataHolder.data(), function(key, val) {
            if (key.indexOf("append") === 0) {
                var powermailFieldPart = key.replace(appendRegex, '');
                powermailFieldPart = powermailFieldPart[0].toLowerCase() + powermailFieldPart.substring(1);
                field = form.find('.powermail_hidden.powermail_' + powermailFieldPart);
                field.val(field.val() + val);
            } else {
                field = form.find('.powermail_hidden.powermail_' + key);
                field.val(val);
            }
        });
        fillAccountOwner(form);
    }
}

function setClubCardReceivingOptions(holder, stepBack) {
    if(stepBack === undefined) {
        stepBack = false;
    }

    var dataHolder  = holder.find('.form-data');
    if (dataHolder.length) {
        var form = dataHolder.find('form.form');
        var field, field2;

        var clubcardOptionsLoaded = false;

        $.each(dataHolder.data(), function(key, val) {
            if (!clubcardOptionsLoaded) {
                if (key == 'sisycash') {
                    if (val == 1) {
                        if (!stepBack) {
                            field = form.find('.powermail_radio#powermail_field_clubkarteerhalten_1');
                            field.prop("checked", true);
                        }
                    } else {
                        field = form.find('.powermail_radio#powermail_field_clubkarteerhalten_2');
                        field.attr('disabled', true);

                        field2 = form.find('.powermail_radio#powermail_field_clubkarteerhalten_1');
                        field2.prop("checked", true);
                    }
                    clubcardOptionsLoaded = true;
                }
            }
        });
        jcf.refreshAll();
    }
}

function setAktionInfo(holder) {
    var dataHolder  = holder.find('.form-data');
    if (dataHolder.length) {
        var aktionName = dataHolder.find('.colorbox_customer_advertise').data('aktionname');

        var form = dataHolder.find('form.form');
        var field;

        field = form.find('.powermail_hidden.powermail_aktion');
        var textToAdd = 'Kunden werben Kunden';

        var kundenwerbenkundenField1 = dataHolder.find('#powermail_field_kunden_werben_kunden_1');
        var kundenwerbenkundenField2 = dataHolder.find('#powermail_field_kunden_werben_kunden_2');

        if (kundenwerbenkundenField1.length && kundenwerbenkundenField2.length) {
            kundenwerbenkundenField1.change(function() {
                if (kundenwerbenkundenField1.val() !== '' && kundenwerbenkundenField2.val() !== '') {
                    field.val(aktionName + "\n" + textToAdd);
                } else {
                    field.val(aktionName);
                }
            });
            kundenwerbenkundenField1.keyup(function() {
                if (kundenwerbenkundenField1.val() !== '' && kundenwerbenkundenField2.val() !== '') {
                    field.val(aktionName + "\n" + textToAdd);
                } else {
                    field.val(aktionName);
                }
            });
            kundenwerbenkundenField2.change(function() {
                if (kundenwerbenkundenField1.val() !== '' && kundenwerbenkundenField2.val() !== '') {
                    field.val(aktionName + "\n" + textToAdd);
                } else {
                    field.val(aktionName);
                }
            });
            kundenwerbenkundenField2.keyup(function() {
                if (kundenwerbenkundenField1.val() !== '' && kundenwerbenkundenField2.val() !== '') {
                    field.val(aktionName + "\n" + textToAdd);
                } else {
                    field.val(aktionName);
                }
            });
        }
    }
}

function fillAccountOwner(form) {
    var accountOwner = form.find('#powermail_field_kontoinhaber'),
        firstName = form.find('#powermail_field_vorname'),
        lastName = form.find('#powermail_field_nachname');

    if (accountOwner.length && firstName.length && lastName.length) {
        accountOwner.prop('readonly', true);
        firstName.change(function () {
            accountOwner.val(firstName.val() + ' ' + lastName.val());
        });
        lastName.change(function () {
            accountOwner.val(firstName.val() + ' ' + lastName.val())
        });
    }
}

function scrollToCouponBeginning() {
    if ($('#select-coupon').length) {
        $('html,body').animate({scrollTop: $('#select-coupon').offset().top - 70}, 'slow');
    }
}

function initExitIntentLayer() {

    if ($('#bio_ep').length) {
        bioEpSettings = {
            cookieExp: 0,
            showOncePerSession: false,
            addStyleElement: true,
            delay: 5,
            width: 400,
            height: 220,
            percentUp: 10
        };

        if ($(window).width() >= 991) {
            bioEpSettings.width = 830;
            bioEpSettings.height = 480;
            bioEpSettings.percentUp = -1;
        }
        bioEp.init(bioEpSettings);
    }

}

function randomId() {
    return (
        Number(String(Math.random()).slice(2)) +
        Date.now() +
        Math.round(performance.now())
    ).toString(36);
}
var searchRadius = 60;
var itemWrap = '.szStudioFinderItemWrap';
var item = '.marker-info';
var searchInputField;
var service = false;

function geoCodeCalcToRadian(a) {
  return a * (Math.PI / 180)
}

function geoCodeCalcDiffRadian(a, b) {
  return geoCodeCalcToRadian(b) - geoCodeCalcToRadian(a)
}

function geoCodeCalcCalcDistance(a, b, c, d) {
  return 2 * 6371.009 * Math.asin(Math.min(1, Math.sqrt(Math.pow(Math.sin(geoCodeCalcDiffRadian(a, c) / 2), 2) + Math.cos(geoCodeCalcToRadian(a)) * Math.cos(geoCodeCalcToRadian(c)) * Math.pow(Math.sin(geoCodeCalcDiffRadian(b, d) / 2), 2))))
}

function sortNumerically(arr) {
  arr.sort(function (a, b) {
    return a.distance < b.distance ? -1 : a.distance > b.distance ? 1 : 0
  });
  return arr;
}

function sortByTitle(arr) {
  arr.sort(function (a, b) {
    return a.title.localeCompare(b.title);
    // return a.title.toLowerCase() < b.title.toLowerCase() ? -1 : a.title.toLowerCase() > b.title.toLowerCase() ? 1 : 0
  });
  return arr;
}

/* match the best place got from reverse geocoder */
function matchPlace(results) {
  var place = {};

  $.map(results, function (result) {
    $.map(result.types, function (type) {
      /* add type "route" if some matches fails */
      if (type == 'street_address' || ($.isEmptyObject(place) && type == 'postal_code')) {
        place = result;
        return false;
      }
    });
  });

  return place;
}

/* do reverse geocoding to get full informations about the wanted place */
function doReverseGeocoding(latitude, longitude) {
  var latLng = new google.maps.LatLng(
    latitude,
    longitude
  );
  var geocoder = new google.maps.Geocoder;

  geocoder.geocode({'location': latLng}, function (results, status) {
    if (status === google.maps.GeocoderStatus.OK) {
      if (results) {
        var place = matchPlace(results);

        if ($.isEmptyObject(place)) {
          console.log('Geocoder failed, no location found');
          return 0;
        }

        // set result into input field
        searchInputField.val(results[1].formatted_address);
        sendSearch();
      } else {
        console.log('Reverse geocoder: no results found');
      }
    } else {
      console.log('Reverse geocoder failed due to: ' + status);
    }
  });
}

function replaceStudiosAndReInitJs (sortedArr) {
  $(itemWrap).text('');

  $.each(sortedArr, function() {
    $(itemWrap)[0].appendChild(this.listObj);
  });

  // update and display distance per item
  $(itemWrap).find(item).not('.hidden').each(function () {
    var elemB = $(this);

    if (elemB.data('distance')) {
      elemB.find('.distance-value').text(elemB.data('distance'));
      elemB.find('.distance').removeClass('hidden');
    } else {
      elemB.find('.distance-value').text();
      elemB.find('.distance').addClass('hidden');
    }
  });
}

function resetSearch() {
  var tempArr = [];

  $('.filter-results').hide();
  $('.filter-loading').hide();

  $(item).each(function(k, v) {
    $(this).removeClass('hidden');
    $(this).removeData('distance');
    $(this).removeAttr('data-distance');
    tempArr.push({
      'title': $(this).find('.studio-title').text(),
      'listObj': this
    });
  });

  tempArr = sortByTitle(tempArr);
  replaceStudiosAndReInitJs(tempArr);
}

function placesSearchCallback(results, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {

    var searchLat = results[0].geometry.location.lat();
    var searchLng = results[0].geometry.location.lng();

    searchRadius = !!searchRadius ? searchRadius : 10000;
    var tempArr = [];
    $(item).each(function(k, v) {
      var dist = geoCodeCalcCalcDistance(searchLat, searchLng, this.dataset.latitude, this.dataset.longitude);
      this.dataset.distance = dist.toFixed(2); // Auf zwei Nachkommastellen runden
      $(this).addClass('hidden');

      if (dist <= searchRadius) {
        $(this).removeClass('hidden');
      }

      tempArr.push({
        'distance': dist,
        'listObj': this
      });
    });

    tempArr = sortNumerically(tempArr);
    replaceStudiosAndReInitJs(tempArr);

    if ($(itemWrap).find(item).not('.hidden').length > 0) {
      $('.filter-results').show();
    }
  }
  $('.filter-loading').hide();
}

function sendSearch() {
  if (searchInputField && searchInputField.val() != '') {
    //var searchBox = new google.maps.places.SearchBox(searchInputField[0]);
    var request = {
      query: searchInputField.val(),
      fields: ['geometry.location'],
    };

    if(!service) {
      service = new google.maps.places.PlacesService(document.createElement('div'));
    }
    service.findPlaceFromQuery(request, placesSearchCallback);
  } else {
    resetSearch();
  }
}

function scrollToTopOnStepChange(holder) {
  var offset = 15;
  var steps = (holder.find('#step-3').length) ? holder.find('#step-3') : holder.find('#step-2');
  if ($(window).width() < 991) {
    var fixedBlockHolder = find('.fixed-block-holder');
    if (fixedBlockHolder.length) {
      offset =+ fixedBlockHolder.height();
    }
  }
  $('html, body').animate({
    scrollTop: steps.offset().top - offset
  }, 1000);
}

function initNewMapSearch(holder) {
  searchInputField = holder.find('#szStudioFinderAutoComplete');

  // hide results on init
  $('.filter-results').hide();

  // initialize loading animation
  $('.filter-loading').hide();
  animateLoading();

  var inputdebounceTimeout;

  $('.szStudioFinderSearchForm').on('submit', function(e) {
    e.preventDefault();
  });

  searchInputField.on('input', function () {
      $('.filter-loading').show();
      if (inputdebounceTimeout) {
        clearTimeout(inputdebounceTimeout);
      }
      inputdebounceTimeout = window.setTimeout(function() {
        sendSearch();
      }, 800);
  });


  // initialize automatic anchor scrolling
  if (holder.length) {
    if (holder.find('.filter-steps').not('.dont-scroll').length) {
      $(document).ajaxComplete(function(event, xhr) {
        scrollToTopOnStepChange(holder);
      });
    }
  }

}

function initGetCurrentPositionButton(holder) {
  var currentPositionButton = holder.find('.szStudioFinderGeolocation');

  currentPositionButton.on('click', function(e) {
    e.preventDefault();

    if (navigator.userAgent.match(/bot|spider/i)) {
      // It is a bot. We might want to set some defaults here, or do nothing.
    } else {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
          function (position) {
            doReverseGeocoding(position.coords.latitude, position.coords.longitude);
          },
          function (failure) {
            $.get('https://ipinfo.io/json', function (response) {
              var loc = response.loc.split(',');
              doReverseGeocoding(loc[0], loc[1]);
            });
          }
        );
      } else {
        console.log('Native geolocation API is not supported.');
        $.get('https://ipinfo.io/json', function (response) {
          var loc = response.loc.split(',');
          doReverseGeocoding(loc[0], loc[1]);
        });
      }
    }
  });
}

$.fn.animateRotate = function(angle, duration, easing, complete) {
  var args = $.speed(duration, easing, complete);
  var step = args.step;
  return this.each(function(i, e) {
    args.complete = $.proxy(args.complete, e);
    args.step = function(now) {
      $.style(e, 'transform', 'rotate(' + now + 'deg)');
      if (step) return step.apply(e, arguments);
    };

    $({deg: 0}).animate({deg: angle}, args);
  });
};

function animateLoading() {
  $('.filter-loading i').animateRotate(360, {
    duration: 1337,
    easing: 'linear',
    complete: function () {
      animateLoading();
    },
    step: function () {}
  });
}

function szStudioFinder(opt) {
  this.options = jQuery.extend({
    holder: null,
    map: null,
    teaser: false,
    autocomplete: null,
    navigator: null,
    searchform: null,
    category: null,
    coupon: null,
    cluster: true,
    itemWrap: null,
    item: null,
    detailLink: null,
    affiliation: '1',
    markerZoom: 18,
    radius: 60,
    maxPinsAfterFilter: 4,
    zoomMoreIn: false,
    setZoom: 0,
    defaultMarkerImageName: 'custom-pin-icon-number.png',
    defaultOptions: {
      zoom: 3,
      center: new google.maps.LatLng(51.165691, 10.451526),
      scaleControl: false,
      panControl: false,
      rotateControl: false,
      zoomControl: true,
      mapTypeControl: false,
      overviewMapControl: false,
      streetViewControl: false,
      scrollwheel: false,
      draggable: true,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      styles: []
    },
    geometryLayer: false
  }, opt);
  this.init();
}

szStudioFinder.prototype = {

  /* initialize plugin */
  init: function () {
    if (this.options.holder) {

      this.cookie = this.getCookie('studio');

      if (!this.cookie) {
        this.cookie = {};
      }

      this.findElementsAndSetVars();
      if (this.options.map) {
        this.makeMap();
      }
      this.makeAutoComplete();
      this.makeEventListener();
    }
  },

  /* find all needed Elements and Set the global Vars */
  findElementsAndSetVars: function () {
    this.holder = jQuery(this.options.holder);
    this.autocomplete = this.holder.find(this.options.autocomplete);
    this.searchForm = this.holder.find(this.options.searchform);

    if (this.options.category) {
      this.category = this.holder.find(this.options.category);
    }

    if (this.options.map) {
      this.map = this.holder.find(this.options.map);
      this.markerData = this.holder.find(this.options.item);
      this.marker = [];
      this.filter = null;
      this.bounds = null;
      this.smallBounds = null;
      this.markerIcon = {
        url: '/typo3conf/ext/sz_studio_finder/Resources/Public/Images/mapmarker/' + this.options.affiliation + '/' + this.options.defaultMarkerImageName, // url
        size: new google.maps.Size(30, 40), // size
        origin: new google.maps.Point(0, 0), // origin
        anchor: new google.maps.Point(15, 40) // anchor
      };
      if (this.options.cluster) {
        this.markerCluster = null;
      }
    }
  },

  /* make the map */
  makeMap: function () {
    var _this = this;

    /* do not create the map */
    if (!_this.map.length) {
      return 0;
    }

    _this.mapOptions = jQuery.extend({}, _this.options.defaultOptions, {});
    _this.mapCanvas = new google.maps.Map(_this.map[0], _this.mapOptions);

    if (_this.options.teaser) {
      /* set the infowindow */
      _this.infowindow = new google.maps.InfoWindow({
        content: '',
        maxWidth: 400
      });
    }

    _this.buildBounds();

    $.getJSON('/typo3conf/ext/sz_studio_finder/Resources/Public/JavaScript/map-styles.min.json', function(data) {
      var usRoadMapType = new google.maps.StyledMapType(data, { name: 'Custom Map' });
      _this.mapCanvas.mapTypes.set('usroadatlas', usRoadMapType);
      _this.mapCanvas.setMapTypeId('usroadatlas');
    });
  },

  /* add new marker */
  addMarker: function () {
    var _this = this,
      cnt = 1;

    $(_this.options.itemWrap).find(_this.options.item).not('.hidden').each(function () {
      var elem = $(this);
      if (typeof elem.data('latitude') !== "undefined" && typeof elem.data('longitude') !== "undefined" && _this.checkMarker(elem)) {
        var latLng = new google.maps.LatLng(
          elem.data('latitude'),
          elem.data('longitude')
        );

        var marker = new google.maps.Marker({
          position: latLng,
          map: _this.mapCanvas,
          icon: _this.markerIcon,
          data: {
            studioId: elem.attr('id')
          }
        });

        if (!_this.options.teaser) {
          if (elem.data('distance')) {
            elem.find('.distance-value').text(elem.data('distance'));
            elem.find('.distance').removeClass('hidden');
          } else {
            elem.find('.distance-value').text();
            elem.find('.distance').addClass('hidden');
          }

          if (_this.cookie.sudioId && _this.cookie.sudioId === elem.attr('id')) {
            elem.addClass('selected');
            elem.find('.location .lastViewed').text('(zuletzt aufgerufen)');
          }

          google.maps.event.addDomListener(marker, 'click', function() {
            var listItem = $('#' + this.data.studioId);
            _this.toggleListAndTriggerJump(listItem, latLng);
          });

          $(elem).on('click', function() {
            _this.scrollToListItem(elem);
            _this.jumpToMarker(this, latLng);
          });
        } else {
          google.maps.event.addListener(marker, 'click', function () {
            _this.infowindow.setContent(elem.find('.infowindow').html());
            _this.infowindow.open(_this.mapCanvas, marker);
          });
        }

        _this.marker.push(marker);
        if ((_this.smallBounds === null || _this.smallBounds === undefined || _this.smallBounds === false) ||
          (_this.smallBounds === true && cnt <= _this.options.maxPinsAfterFilter)) {
          _this.bounds.extend(latLng);
          cnt++;
        }
      }
    });
  },

  /* builds the bounds */
  buildBounds: function () {
    var _this = this;

    if (_this.options.cluster) {
      if (_this.markerCluster !== null) {
        _this.markerCluster.clearMarkers();
      }
    }

    _this.bounds = new google.maps.LatLngBounds();

    if (_this.markerData.length > 0) {
      _this.addMarker();
    }

    if ($(_this.options.itemWrap).find('#studio-empty').length > 0) {
      $(_this.options.itemWrap).find('#studio-empty').remove();
    }
    if (_this.marker.length === 0) {
      $(_this.options.itemWrap).append(
        '<li class="opener" id="studio-empty">'+$(_this.options.itemWrap).data('empty')+'</li>'
      );
    }
    if (_this.marker.length === 1) {
      _this.mapCanvas.setCenter(_this.marker[0].getPosition());
      _this.mapCanvas.setZoom(_this.options.markerZoom);
    } else {
      _this.mapCanvas.fitBounds(_this.bounds);

      if (_this.options.cluster) {
        _this.markerCluster = new MarkerClusterer(_this.mapCanvas, _this.marker, {
          styles: [{
            url: '/typo3conf/ext/sz_studio_finder/Resources/Public/Images/mapmarker/' + _this.options.affiliation + '/custom-cluster-pin-icon.png',
            textColor: 'white',
            textSize: '15',
            height: 46,
            width: 30,
            anchor: [5, 30],
            iconAnchor: [15, 41]
          }],
          gridSize: 37,
          averageCenter: false
        });
      }
    }
  },

  checkMarker: function (elem) {
    var _this = this;

    if (_this.filter === null) {
      if (elem.not(':visible') ){
        elem.show();
      }
      return true;
    }

    if (_this.marker) {
      var markerCats = elem.data('cats') ? String(elem.data('cats')).split(',') : [],
        markerCoupons = elem.data('coupons'),
        doMatchAllCats = true;

      if (_this.filter['cats'].length) {
        for (n in _this.filter['cats']) {
          if ($.inArray(_this.filter['cats'][n].toString(), markerCats) === -1) {
            doMatchAllCats = false;
            break;
          }
        }
      }

      if (_this.filter['coupons'] && doMatchAllCats) {
        if (!markerCoupons) {
          doMatchAllCats = false;
        }
      }

      if (doMatchAllCats) {
        elem.show();
      } else {
        elem.hide();
      }

      return doMatchAllCats;
    }
  },

  /* remove all marker */
  removeMarker: function () {
    var _this = this;

    if (_this.options.teaser) {
      _this.infowindow.close();
    }

    if (_this.marker) {
      $(_this.marker).each(function (index, marker) {
        marker.setMap(null);
      });
      _this.marker = [];
    }
  },

  lastViewed: function () {
    var _this = this,
      lastViewedStudio = $(_this.options.itemWrap).find(_this.options.item + '.selected');
    if (lastViewedStudio.length > 0 && !lastViewedStudio.hasClass('hidden')) {
      lastViewedStudio.removeClass('selected');
      var latLng = new google.maps.LatLng(
        lastViewedStudio.data('latitude'),
        lastViewedStudio.data('longitude')
      );
      _this.toggleListAndTriggerJump(lastViewedStudio, latLng);
    }
  },

  toggleListAndTriggerJump: function(elem, latLng) {
    var _this = this,
      $listItemLink = elem.find('> a');

    $listItemLink.trigger('click', null);
    _this.jumpToMarker(elem, latLng);
  },

  scrollToListItem: function(elem) {
    var $holder = $('.scroll-holder');

    if (elem.hasClass('active') && $holder.innerHeight() < $holder.find('.filter-accordion').innerHeight()) {
      // we had to set a time out for mor than 300ms to allow thing other to close (slideAccordion)
      setTimeout(function () {
        $holder.animate({
          scrollTop: elem.offset().top - ($holder.find('li:visible:first').offset().top - 1)
        }, {
          duration: 1000,
          queue: false
        });
      }, 350);
    }

  },

  /* jumps to the selected Marker */
  jumpToMarker: function($elem, latLng) {
    var _this = this;
    var selector = (!!$elem.data && !!$elem.data.studioId) ? '#' + $elem.data.studioId : $elem;
    if ($(selector).hasClass('active')) {
      _this.mapCanvas.setCenter(latLng);
      _this.mapCanvas.setZoom(_this.options.markerZoom);
      if (selector !== $elem) {
        $elem.setAnimation(google.maps.Animation.BOUNCE);
        window.setTimeout(function() {
          $elem.setAnimation(null);
        }, 800);
      }
    }
    else {
      _this.mapCanvas.setCenter(_this.options.defaultOptions.center);
      _this.mapCanvas.setZoom(_this.options.markerZoom);
      _this.mapCanvas.fitBounds(_this.bounds);
    }
  },

  /* match the best place got from reverse geocoder */
  matchPlace: function (results) {
    var place = {};

    $.map(results, function (result) {
      $.map(result.types, function (type) {
        /* add type "route" if some matches fails */
        if (type == 'street_address' || ($.isEmptyObject(place) && type == 'postal_code')) {
          place = result;
          return false;
        }
      });
    });

    return place;
  },

  /* do reverse geocoding to get full informations about the wanted place */
  doReverseGeocoding: function (latitude, longitude) {
    var _this = this, latLng = new google.maps.LatLng(
      latitude,
      longitude
    );
    _this.geocoder.geocode({'location': latLng}, function (results, status) {
      if (status === google.maps.GeocoderStatus.OK) {
        if (results) {
          var place = _this.matchPlace(results);

          if ($.isEmptyObject(place)) {
            console.log('Geocoder failed, no location found');
            return 0;
          }
          // attr has to be set for send the form
          $(_this.autocomplete).attr('value',results[1].formatted_address);
          $(_this.autocomplete).val(results[1].formatted_address);

          if (_this.options.map) {
            _this.autocomplete[0].focus();
            $(_this.autocomplete[0]).click();
            _this.triggerAutoCompletion(); // "prevent showing the autocomplete-form"-hack
            window.setTimeout(function() {
              _this.triggerAutoCompletion();
            }, 150);
          }

        } else {
          console.log('Reverse geocoder: no results found');
        }
      } else {
        console.log('Reverse geocoder failed due to: ' + status);
      }
    });
  },

  getCurrentClientLocation: function() {
    var _this = this;
    if (navigator.userAgent.match(/bot|spider/i)) {
      // It is a bot. We might want to set some defaults here, or do nothing.
    } else {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {
            _this.doReverseGeocoding(position.coords.latitude, position.coords.longitude);
          },
          function (failure) {
            $.get('https://ipinfo.io/json', function (response) {
              var loc = response.loc.split(',');
              _this.doReverseGeocoding(loc[0], loc[1]);
            });
          }
        );
      } else {
        console.log('Native geolocation API is not supported.');
      }
    }
  },

  /* make the AutoComplete function */
  makeAutoComplete: function () {
    var _this = this,
      autoCompleteTriggerFirstTime = 0;

    /* do not create AutoComplete function */
    if (!_this.autocomplete.length) {
      return 0;
    }

    /* set prefilled autocomplete value and triggerAutoCompletion if ready */
    if (_this.cookie && _this.cookie.autocomplete) {
      _this.autocomplete.val(_this.cookie.autocomplete);
      if (_this.options.map) {
        google.maps.event.addListenerOnce(_this.mapCanvas, 'idle', function() {
          var interval = setInterval(function(){
            if (autoCompleteTriggerFirstTime === 0) {
              // do not trigger continously on first call
              autoCompleteTriggerFirstTime = 1;
              _this.triggerAutoCompletion();
            } else {
              clearInterval(interval);
            }
          }, 100);
        });
      }
    } else {
      autoCompleteTriggerFirstTime = false;
      if (_this.options.map && !_this.options.teaser) {
        google.maps.event.addListenerOnce(_this.mapCanvas, 'idle', function () {
          _this.lastViewed();
        });
      }
    }

    /* create AutoComplete object */
    _this.autocompleteElement = new google.maps.places.Autocomplete(
      _this.autocomplete[0], {
        types: ['geocode'],
        fields: ["geometry.location"],
        componentRestrictions: {
          country: ["de","ch","at","lux"]
        }
      }
    );

    /* create geocoder object */
    _this.geocoder = new google.maps.Geocoder;

    if (_this.options.map) {
      /* do not submit the search form */
      _this.searchForm.submit(function (e) {
        e.preventDefault();
        _this.triggerAutoCompletion();
        /* if autocomplete is empty rest */
        if ($(_this.autocomplete).val() === '') {
          _this.smallBounds = false;
          _this.resetMarker();
          _this.scrollHolderToTop();
          _this.update(true);
          _this.updateCookie();
          _this.increaseZoom();
        }
      });

      /* add AutoComplete changed event listener */
      google.maps.event.addListener(_this.autocompleteElement, 'place_changed', function () {
        var place = _this.autocompleteElement.getPlace();
        if (!place.geometry) {
          console.log("Autocomplete's returned place contains no geometry");
          return;
        }
        _this.smallBounds = true;

        _this.sortListByDistanceToLatLng(place.geometry.location.lat(), place.geometry.location.lng(), _this.options.radius);
        if (autoCompleteTriggerFirstTime === false || autoCompleteTriggerFirstTime === 1) {
          _this.scrollHolderToTop();
        }
        _this.updateCookie();
        _this.update(true);
        _this.lastViewed();

        autoCompleteTriggerFirstTime = 1;
      });
    } else {
      _this.searchForm.find('button[type="submit"]').click(function(){
        _this.triggerAutoCompletion();
      });
      _this.searchForm.submit(function(){
        _this.updateCookie();
      });
    }
  },

  scrollHolderToTop: function () {
    $holder = $('.scroll-holder');
    if($holder.length) {
      // Scroll back to the box top
      $holder.animate({
        scrollTop: 0
      }, {
        duration: 1000,
        queue: false
      });
    }
  },

  triggerAutoCompletion: function () {
    var _this = this;

    var ex1 = new Event('keydown');
    ex1.code = "ArrowDown";
    ex1.key = "ArrowDown";
    ex1.keyCode = 40;
    google.maps.event.trigger(_this.autocomplete[0], 'keydown', ex1);

    var ex2 = new Event('keydown');
    ex2.code = "Enter";
    ex2.key = "Enter";
    ex2.keyCode = 13;
    ex2.triggered = true;
    google.maps.event.trigger(_this.autocomplete[0], 'keydown', ex2);
  },

  /* make the event listeners */
  makeEventListener: function () {
    var _this = this;

    /* event listener for category */
    if (_this.options.category) {
      $(_this.options.category).on('change', function () {
        _this.triggerFilter(function (filterCount) {
          _this.toggleFilterOpenClose(filterCount.length);
        });
      });
      $(_this.options.category + ' button[type=reset]').on('click', function () {
        window.setTimeout(function() {
          _this.toggleFilterOpenClose(0);
          _this.filter = null;
          _this.update(true)
        }, 50);
      });
    }

    if (_this.options.coupon) {
      if ($(_this.options.coupon).find('input[type=checkbox]:checked').length > 0){
        _this.triggerFilter();
      }
      $(_this.options.coupon).on('change', function () {
        _this.triggerFilter();
      });
    }

    /* event listener for last viewed studio */
    if (_this.options.detailLink) {
      if (!_this.options.teaser){
        _this.initDetailLink();
      } else {
        google.maps.event.addListener(_this.infowindow, 'domready', function() {
          var $link = $('.gm-style-iw').find(_this.options.detailLink);
          $link.on("click", function(){
            _this.updateCookie($link.data('id'));
          });
        });
      }
    }

    /* event listener for navigator geoposition */
    if (_this.options.navigator) {
      $(_this.options.navigator).click(function (e) {
        e.preventDefault();
        _this.getCurrentClientLocation();
        if (_this.options.map === null) {
          window.setTimeout(function () {
            $(_this.searchForm).submit();
          }, 500);
        }
      });
    }
    _this.increaseZoom();
    _this.setZoom();
  },

  increaseZoom: function () {
    var _this = this;

    /* increase the zoom on the map */
    if (_this.options.zoomMoreIn && _this.options.map && !_this.options.teaser) {
      var listener = google.maps.event.addListener(_this.mapCanvas, "idle", function () {
        _this.mapCanvas.setZoom(_this.mapCanvas.getZoom() + 1);

        var f = 0;
        for (var i = 0; i < _this.marker.length; i++){
          if(_this.mapCanvas.getBounds().contains(_this.marker[i].getPosition())) {
            f++;
          }
        }
        if(f === 0) {
          _this.mapCanvas.fitBounds(_this.bounds);
        }
        google.maps.event.removeListener(listener);
      });
    }
  },
  setZoom: function () {
    var _this = this;

    /* set the zoom on the map */
    if (_this.options.setZoom > 0 && _this.options.map) {
      var listener = google.maps.event.addListener(_this.mapCanvas, "idle", function () {

        var f = 0;
        for (var i = 0; i < _this.marker.length; i++){
          if(_this.mapCanvas.getBounds().contains(_this.marker[i].getPosition())) {
            f++;
          }
        }
        if(f === 0) {
          _this.mapCanvas.fitBounds(_this.bounds);
        }

        console.log('_this.options.setZoom3');
        console.log(_this.options.setZoom);

        _this.mapCanvas.setZoom(_this.options.setZoom);

        google.maps.event.removeListener(listener);
      });
    }
  },

  initDetailLink: function () {
    var _this = this;

    $(_this.options.detailLink).each(function() {
      $(this).on("click", function(){
        _this.updateCookie($(this).data('id'));
      });
    });
  },

  triggerFilter: function (callBack) {
    var _this = this;
    window.setTimeout(function() {
      _this.filter = [];
      _this.filter['cats'] = [];
      _this.filter['coupons'] = false;

      if (_this.options.category){
        var categoryFilter = $(_this.options.category + ' label.jcf-label-active');
        if(typeof callBack === 'function') {
          callBack(categoryFilter);
        }
        $.each(categoryFilter, function() {
          _this.filter['cats'].push($(this).find('input[type=checkbox]').data('cat-id'));

        });
      }

      if (_this.options.coupon && $(_this.options.coupon).find('input[type=checkbox]:checked').length){
        _this.filter['coupons'] = true;
      }

      _this.update(true);
    }, 50);
  },

  toggleFilterOpenClose: function (filterCount) {
    var parent = $('.filter-open-close');
    if(filterCount === 0) {
      parent.find('.count-cat').text('');
    } else {
      parent.find('.count-cat').text('(' + filterCount + ')');
    }

    parent.data('OpenClose').hideSlide(function() {
      // Scroll to top of list
      $('html, body').animate({
        scrollTop: $('.filter-results').offset().top - 150
      }, {
        duration: 500,
        queue: false
      });
    });
  },

  update: function (resetMarkers) {
    var _this = this;

    if (_this.options.map) {
      if (resetMarkers) {
        _this.removeMarker();
      }
      _this.buildBounds();
    }
  },

  geoCodeCalcToRadian: function(a) {
    return a * (Math.PI / 180)
  },

  geoCodeCalcDiffRadian: function(a, b) {
    return this.geoCodeCalcToRadian(b) - this.geoCodeCalcToRadian(a)
  },

  geoCodeCalcCalcDistance: function(a, b, c, d) {
    return 2 * 6371.009 * Math.asin(Math.min(1, Math.sqrt(Math.pow(Math.sin(this.geoCodeCalcDiffRadian(a, c) / 2), 2) + Math.cos(this.geoCodeCalcToRadian(a)) * Math.cos(this.geoCodeCalcToRadian(c)) * Math.pow(Math.sin(this.geoCodeCalcDiffRadian(b, d) / 2), 2))))
  },

  sortNumerically: function(arr) {
    arr.sort(function (a, b) {
      return a.distance < b.distance ? -1 : a.distance > b.distance ? 1 : 0
    });
    return arr;
  },

  sortByTitle: function(arr) {
    arr.sort(function (a, b) {
      return a.title.localeCompare(b.title);
      // return a.title.toLowerCase() < b.title.toLowerCase() ? -1 : a.title.toLowerCase() > b.title.toLowerCase() ? 1 : 0
    });
    return arr;
  },

  /* make sort */
  sortListByDistanceToLatLng: function(clientLat, clientLng, maxDist) {
    maxDist = !!maxDist ? maxDist : 10000;
    var tempArr = [],
      _this = this;
    $(_this.options.item).each(function(k, v) {
      var dist = _this.geoCodeCalcCalcDistance(clientLat, clientLng, this.dataset.latitude, this.dataset.longitude);
      this.dataset.distance = dist.toFixed(2); // Auf zwei Nachkommastellen runden
      $(this).addClass('hidden');

      if (dist <= maxDist) {
        $(this).removeClass('hidden');
      }

      tempArr.push({
        'distance': dist,
        'listObj': this
      });
    });
    _this.replaceStudiosAndReInitJs(this.sortNumerically(tempArr));
  },


  /* reset all marker */
  resetMarker: function () {
    var tempArr = [],
      _this = this;

    $(_this.options.item).each(function(k, v) {
      var _self = $(this);
      _self.removeClass('hidden');
      _self.removeAttr('data-distance');

      tempArr.push({
        'title': _self.find('.studio-title').text(),
        'listObj': this
      });
    });

    _this.replaceStudiosAndReInitJs(this.sortByTitle(tempArr));
  },

  replaceStudiosAndReInitJs: function (sortedArr) {
    var _this = this;
    $(_this.options.itemWrap).text('');

    $.each(sortedArr, function() {
      $(_this.options.itemWrap)[0].appendChild(this.listObj);
    });

    if (!_this.options.teaser) {
      if (_this.options.detailLink) {
        _this.initDetailLink();
      }
      initAccordionStudioFinder();
    }
  },

  /* update cookie values */
  updateCookie: function (studioId) {
    var _this = this;

    if (studioId) {
      _this.cookie.sudioId = 'studio-' + studioId;
    }
    _this.cookie.autocomplete = _this.autocomplete.val();
    _this.setCookie('studio', _this.cookie);
  },

  /* get the cookie values */
  getCookie: function (name) {
    $.cookie.json = true;
    return $.cookie(name);
  },

  /* set the cookie values */
  setCookie: function (name, value) {
    $.cookie.json = true;
    $.cookie(name, value, {path: '/'});
  }
};
jQuery(function () {
    initSteps();
    initSurveyResult();
});

function initSteps() {
    var form = $(".question-form"), current = 0, next = 1, currentSlide = '';
    form.find('.question.hide-first').hide();

    var userSelections = {};

    var updateIndex = function (current, next) {
        form.find('.question').each(function () {
            var _this = $(this);
            if (_this.data('number') === current) {
                _this.fadeOut('fast');
            }
            if (_this.data('number') === next) {
                setTimeout(function () {
                    _this.fadeIn('slow');
                }, 200);
            }
        });
    };

    form.find('.surveystep.next').not('.surveysubmit').click(function (e) {
        e.preventDefault();
        currentSlide = form.find('#q-' + current);
        if (currentSlide.find('input:checked').length > 0) {
            next = $(this).data('next');
            userSelections[current] = currentSlide.find('input:checked').val();
            updateIndex(current, next);
            current = next;
            var offset = 55;
            if ($(window).width() < 991) {
                offset = 80;
            }
            $('html, body').animate({
                scrollTop: form.offset().top - offset
            }, 200);
        } else {
            currentSlide.find('.error').text('Bitte auswählen!');
        }
    });
    form.find('.surveystep.next.surveysubmit').click(function (e) {
        currentSlide.find('input').prop('disabled', true);

        userSelections[current] = form.find('.surveystep.next.surveysubmit').find('input:checked').val();

        $('<input />').attr('type', 'hidden')
            .attr('name', "tx_szsurvey_pi1[userdata]")
            .attr('value', JSON.stringify(userSelections))
            .appendTo(this);

        form.submit();
    })
}

function initSurveyResult() {
    var pageType = 1500887651,
        $form = $('.form-survey');

    $form.bind('submit', function (e) {
        var $this = $(this);
        e.preventDefault();
        $this.find('.loading').removeClass('hidden');
        $.ajax({
            type: $this.attr('method'),
            url: $this.attr('action') + '&type=' + pageType,
            data: $this.serialize(),
            success: function (response) {
                $this.find('.btn-send-result').prop('disabled', false);
                $this.find('.loading').addClass('hidden');
                $this.find('.response').empty().html(response);
            },
            error: function (error) {
                console.error(error);
            }
        });
    });
}
/**
 * easytimer.js
 * Generated: 2019-07-22
 * Version: 4.0.1
 */

!function(t,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n((t=t||self).easytimer={})}(this,function(t){"use strict";function q(t){return(q="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function i(t,n,e){var o,r="";if((t="number"==typeof t?String(t):t).length>n)return t;for(o=0;o<n;o+=1)r+=String(e);return(r+t).slice(-r.length)}function I(){this.secondTenths=0,this.seconds=0,this.minutes=0,this.hours=0,this.days=0,this.toString=function(){var t=0<arguments.length&&void 0!==arguments[0]?arguments[0]:["hours","minutes","seconds"],n=1<arguments.length&&void 0!==arguments[1]?arguments[1]:":",e=2<arguments.length&&void 0!==arguments[2]?arguments[2]:2;t=t||["hours","minutes","seconds"],n=n||":",e=e||2;var o,r=[];for(o=0;o<t.length;o+=1)void 0!==this[t[o]]&&("secondTenths"===t[o]?r.push(this[t[o]]):r.push(i(this[t[o]],e,"0")));return r.join(n)}}var n="undefined"!=typeof window?window.CustomEvent:void 0;"undefined"!=typeof window&&"function"!=typeof n&&((n=function(t,n){n=n||{bubbles:!1,cancelable:!1,detail:void 0};var e=document.createEvent("CustomEvent");return e.initCustomEvent(t,n.bubbles,n.cancelable,n.detail),e}).prototype=window.Event.prototype,window.CustomEvent=n);var _="secondTenths",z="seconds",R="minutes",B="hours",F="days",G=[_,z,R,B,F],H={secondTenths:100,seconds:1e3,minutes:6e4,hours:36e5,days:864e5},J={secondTenths:10,seconds:60,minutes:60,hours:24},K="undefined"!=typeof module&&module.exports&&"function"==typeof require?require("events"):void 0;function N(){return"undefined"!=typeof document}function Q(){return K}function W(t,n){return(t%n+n)%n}function e(){var n,e,o,r,i,s,u,c,a,d,f=new I,h=new I,l=N()?document.createElement("span"):Q()?new K.EventEmitter:void 0,v=!1,p=!1,m={},y={detail:{timer:this}};function w(t,n){var e,o,r=h[n];return o=V(t,H[e=n]),h[e]=o,f[e]=e===F?o:0<=o?W(o,J[e]):J[e]-W(o,J[e]),h[n]!==r}function t(){b(),function(){for(var t in f)f.hasOwnProperty(t)&&"number"==typeof f[t]&&(f[t]=0);for(var n in h)h.hasOwnProperty(n)&&"number"==typeof h[n]&&(h[n]=0)}()}function b(){clearInterval(n),n=void 0,p=v=!1}function g(t){k()?(a=E(),s=L(i.target)):function(t){e=function(t){if(n=t="string"==typeof t?t:z,0<=G.indexOf(n))return t;var n;throw new Error("Error in precision parameter: ".concat(t," is not a valid value"))}((t=t||{}).precision),r="function"==typeof t.callback?t.callback:function(){},c=!0===t.countdown,o=!0===c?-1:1,"object"===q(t.startValues)?(n=t.startValues,u=C(n),f.secondTenths=u[0],f.seconds=u[1],f.minutes=u[2],f.hours=u[3],f.days=u[4],h=O(u,h)):u=null;var n;a=E(),S(),s="object"===q(t.target)?L(t.target):c?(t.target={seconds:0},L(t.target)):null;m={precision:e,callback:r,countdown:"object"===q(t)&&!0===t.countdown,target:s,startValues:u},i=t}(t),function(){var t=H[e];if(x(j(Date.now())))return;n=setInterval(T,t),v=!0,p=!1}()}function E(){return j(Date.now())-h.secondTenths*H[_]*o}function T(){var t=j(Date.now());!function(t){t[_]&&M("secondTenthsUpdated",y);t[z]&&M("secondsUpdated",y);t[R]&&M("minutesUpdated",y);t[B]&&M("hoursUpdated",y);t[F]&&M("daysUpdated",y)}(S()),r(y.detail.timer),x(t)&&(U(),M("targetAchieved",y))}function S(){var t=0<arguments.length&&void 0!==arguments[0]?arguments[0]:j(Date.now()),n=0<o?t-a:a-t,e={};return e[_]=w(n,_),e[z]=w(n,z),e[R]=w(n,R),e[B]=w(n,B),e[F]=w(n,F),e}function j(t){return Math.floor(t/H[e])*H[e]}function x(t){return s instanceof Array&&d<=t}function C(t){var n,e,o,r,i,s;if("object"===q(t))if(t instanceof Array){if(5!==t.length)throw new Error("Array size not valid");s=t}else{for(var u in t)if(G.indexOf(u)<0)throw new Error("Error in startValues or target parameter: ".concat(u," is not a valid input value"));s=[t.secondTenths||0,t.seconds||0,t.minutes||0,t.hours||0,t.days||0]}return n=s[0],e=s[1]+V(n,10),o=s[2]+V(e,60),r=s[3]+V(o,60),i=s[4]+V(r,24),s[0]=n%10,s[1]=e%60,s[2]=o%60,s[3]=r%24,s[4]=i,s}function V(t,n){var e=t/n;return e<0?Math.ceil(e):Math.floor(e)}function L(t){if(t){var n=O(s=C(t));return d=a+n.secondTenths*H[_]*o,s}}function O(t,n){var e=n||{};return e.days=t[4],e.hours=24*e.days+t[3],e.minutes=60*e.hours+t[2],e.seconds=60*e.minutes+t[1],e.secondTenths=10*e.seconds+t[[0]],e}function U(){t(),M("stopped",y)}function A(t,n){N()?l.addEventListener(t,n):Q()&&l.on(t,n)}function D(t,n){N()?l.removeEventListener(t,n):Q()&&l.removeListener(t,n)}function M(t,n){N()?l.dispatchEvent(new CustomEvent(t,n)):Q()&&l.emit(t,n)}function P(){return v}function k(){return p}void 0!==this&&(this.start=function(){var t=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};P()||(g(t),M("started",y))},this.pause=function(){b(),p=!0,M("paused",y)},this.stop=U,this.reset=function(){t(),g(i),M("reset",y)},this.isRunning=P,this.isPaused=k,this.getTimeValues=function(){return f},this.getTotalTimeValues=function(){return h},this.getConfig=function(){return m},this.addEventListener=A,this.on=A,this.removeEventListener=D,this.off=D)}t.Timer=e,t.default=e,Object.defineProperty(t,"__esModule",{value:!0})});

if ( $( '.aktiontimer' ).length ) {

    $('.aktiontimer').each(function (index) {
        var self = $(this);

        var timediffdays = $(this).data('timediffdays');
        var timediffhours = $(this).data('timediffhours');
        var timediffminutes = $(this).data('timediffminutes');
        var timediffseconds = $(this).data('timediffseconds');

        var timerInstance = new easytimer.Timer();
        timerInstance.start({countdown: true, startValues: {seconds: timediffseconds, minutes: timediffminutes, hours: timediffhours, days: timediffdays},
            callback: function (timer) {
                self.find('.timerdays').text(timer.getTimeValues().days.toString());
                self.find('.timerhours').text(timer.getTimeValues().hours.toString());
                self.find('.timerminutes').text(timer.getTimeValues().minutes.toString());
                self.find('.timerseconds').text(timer.getTimeValues().seconds.toString());
            }
        });
        timerInstance.addEventListener('targetAchieved', function (e) {
            self.hide();
        });

    });

}

$(document).ready(function () {

    // get Video elements
    var video =  document.querySelectorAll('.video_responsive-data');

    // get current window width
    var windowWidth = window.innerWidth ? window.innerWidth : $(window).width();

    // add source to video tag
    function addSourceToVideo(element, src, type) {
        let source = document.createElement('source');
        source.src = src;
        source.type = type;
        element.appendChild(source);
    }

    // add poster
    function addPoster(element, src) {
        element.setAttribute('poster',src);
    }

    // prepare source
    function prepareSource(element, breakpoint, width) {

        // get current
        if (width > breakpoint ) {
            // Desktop stuff
            addSourceToVideo( element, element.dataset.desktopWebm, 'video/webm');
            addSourceToVideo( element, element.dataset.desktopMp4, 'video/mp4');
            addPoster(element, element.dataset.posterDesktop);
        } else {
            // Mobile stuff
            addSourceToVideo(element, element.dataset.mobileWebm, 'video/webm');
            addSourceToVideo(element, element.dataset.mobileMp4, 'video/mp4');
            addPoster(element, element.dataset.posterMobile);
        }
    }

    // Init video
    function initResponsiveVideo() {
        if (video !== undefined) {
            video.forEach(function(element) {
                // get breakpoint
                let breakpoint = element.dataset.breakpoint;
                prepareSource(element, breakpoint, windowWidth);
            });
        }
    }

    // only on resize
    function changeResponsiveVideo(targetWidth) {
        if (video !== undefined) {
            video.forEach(function(element) {
                // get breakpoint
                let breakpoint = element.dataset.breakpoint;
                // change source only if user resize over the breakpoint
                if((windowWidth >= breakpoint && targetWidth < breakpoint) || (windowWidth < breakpoint && targetWidth >= breakpoint)) {
                    // clean all source tags
                    element.innerHTML = "";
                    // prepare
                    prepareSource(element, breakpoint, targetWidth);
                    // reload video
                    element.load();
                    element.play();
                }
            });
            // set new windowWidth
            windowWidth = targetWidth;
        }
    }

    initResponsiveVideo();
    $( window ).resize(function(e) {
        changeResponsiveVideo(e.target.innerWidth);
    });

});

/*! SmoothScroll v16.1.4 | (c) 2020 Chris Ferdinandi | MIT License | http://github.com/cferdinandi/smooth-scroll */
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).SmoothScroll=t()}(this,(function(){"use strict";window.Element&&!Element.prototype.closest&&(Element.prototype.closest=function(e){var t,n=(this.document||this.ownerDocument).querySelectorAll(e),o=this;do{for(t=n.length;--t>=0&&n.item(t)!==o;);}while(t<0&&(o=o.parentElement));return o}),function(){if("function"==typeof window.CustomEvent)return!1;function e(e,t){t=t||{bubbles:!1,cancelable:!1,detail:void 0};var n=document.createEvent("CustomEvent");return n.initCustomEvent(e,t.bubbles,t.cancelable,t.detail),n}e.prototype=window.Event.prototype,window.CustomEvent=e}(),
/**
	 * requestAnimationFrame() polyfill
	 * By Erik Möller. Fixes from Paul Irish and Tino Zijdel.
	 * @link http://paulirish.com/2011/requestanimationframe-for-smart-animating/
	 * @link http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
	 * @license MIT
	 */
function(){for(var e=0,t=["ms","moz","webkit","o"],n=0;n<t.length&&!window.requestAnimationFrame;++n)window.requestAnimationFrame=window[t[n]+"RequestAnimationFrame"],window.cancelAnimationFrame=window[t[n]+"CancelAnimationFrame"]||window[t[n]+"CancelRequestAnimationFrame"];window.requestAnimationFrame||(window.requestAnimationFrame=function(t,n){var o=(new Date).getTime(),i=Math.max(0,16-(o-e)),a=window.setTimeout((function(){t(o+i)}),i);return e=o+i,a}),window.cancelAnimationFrame||(window.cancelAnimationFrame=function(e){clearTimeout(e)})}();var e={ignore:"[data-scroll-ignore]",header:null,topOnEmptyHash:!0,speed:500,speedAsDuration:!1,durationMax:null,durationMin:null,clip:!0,offset:0,easing:"easeInOutCubic",customEasing:null,updateURL:!0,popstate:!0,emitEvents:!0},t=function(){var e={};return Array.prototype.forEach.call(arguments,(function(t){for(var n in t){if(!t.hasOwnProperty(n))return;e[n]=t[n]}})),e},n=function(e){"#"===e.charAt(0)&&(e=e.substr(1));for(var t,n=String(e),o=n.length,i=-1,a="",r=n.charCodeAt(0);++i<o;){if(0===(t=n.charCodeAt(i)))throw new InvalidCharacterError("Invalid character: the input contains U+0000.");t>=1&&t<=31||127==t||0===i&&t>=48&&t<=57||1===i&&t>=48&&t<=57&&45===r?a+="\\"+t.toString(16)+" ":a+=t>=128||45===t||95===t||t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122?n.charAt(i):"\\"+n.charAt(i)}return"#"+a},o=function(){return Math.max(document.body.scrollHeight,document.documentElement.scrollHeight,document.body.offsetHeight,document.documentElement.offsetHeight,document.body.clientHeight,document.documentElement.clientHeight)},i=function(e){return e?(t=e,parseInt(window.getComputedStyle(t).height,10)+e.offsetTop):0;var t},a=function(e,t,n){0===e&&document.body.focus(),n||(e.focus(),document.activeElement!==e&&(e.setAttribute("tabindex","-1"),e.focus(),e.style.outline="none"),window.scrollTo(0,t))},r=function(e,t,n,o){if(t.emitEvents&&"function"==typeof window.CustomEvent){var i=new CustomEvent(e,{bubbles:!0,detail:{anchor:n,toggle:o}});document.dispatchEvent(i)}};return function(c,u){var s,l,d,m,f={};f.cancelScroll=function(e){cancelAnimationFrame(m),m=null,e||r("scrollCancel",s)},f.animateScroll=function(n,c,u){f.cancelScroll();var l=t(s||e,u||{}),w="[object Number]"===Object.prototype.toString.call(n),h=w||!n.tagName?null:n;if(w||h){var p=window.pageYOffset;l.header&&!d&&(d=document.querySelector(l.header));var g,y,v,S=i(d),E=w?n:function(e,t,n,i){var a=0;if(e.offsetParent)do{a+=e.offsetTop,e=e.offsetParent}while(e);return a=Math.max(a-t-n,0),i&&(a=Math.min(a,o()-window.innerHeight)),a}(h,S,parseInt("function"==typeof l.offset?l.offset(n,c):l.offset,10),l.clip),b=E-p,A=o(),O=0,C=function(e,t){var n=t.speedAsDuration?t.speed:Math.abs(e/1e3*t.speed);return t.durationMax&&n>t.durationMax?t.durationMax:t.durationMin&&n<t.durationMin?t.durationMin:parseInt(n,10)}(b,l),M=function(e){g||(g=e),O+=e-g,v=p+b*function(e,t){var n;return"easeInQuad"===e.easing&&(n=t*t),"easeOutQuad"===e.easing&&(n=t*(2-t)),"easeInOutQuad"===e.easing&&(n=t<.5?2*t*t:(4-2*t)*t-1),"easeInCubic"===e.easing&&(n=t*t*t),"easeOutCubic"===e.easing&&(n=--t*t*t+1),"easeInOutCubic"===e.easing&&(n=t<.5?4*t*t*t:(t-1)*(2*t-2)*(2*t-2)+1),"easeInQuart"===e.easing&&(n=t*t*t*t),"easeOutQuart"===e.easing&&(n=1- --t*t*t*t),"easeInOutQuart"===e.easing&&(n=t<.5?8*t*t*t*t:1-8*--t*t*t*t),"easeInQuint"===e.easing&&(n=t*t*t*t*t),"easeOutQuint"===e.easing&&(n=1+--t*t*t*t*t),"easeInOutQuint"===e.easing&&(n=t<.5?16*t*t*t*t*t:1+16*--t*t*t*t*t),e.customEasing&&(n=e.customEasing(t)),n||t}(l,y=(y=0===C?0:O/C)>1?1:y),window.scrollTo(0,Math.floor(v)),function(e,t){var o=window.pageYOffset;if(e==t||o==t||(p<t&&window.innerHeight+o)>=A)return f.cancelScroll(!0),a(n,t,w),r("scrollStop",l,n,c),g=null,m=null,!0}(v,E)||(m=window.requestAnimationFrame(M),g=e)};0===window.pageYOffset&&window.scrollTo(0,0),function(e,t,n){t||history.pushState&&n.updateURL&&history.pushState({smoothScroll:JSON.stringify(n),anchor:e.id},document.title,e===document.documentElement?"#top":"#"+e.id)}(n,w,l),"matchMedia"in window&&window.matchMedia("(prefers-reduced-motion)").matches?a(n,Math.floor(E),!1):(r("scrollStart",l,n,c),f.cancelScroll(!0),window.requestAnimationFrame(M))}};var w=function(e){if(!e.defaultPrevented&&!(0!==e.button||e.metaKey||e.ctrlKey||e.shiftKey)&&"closest"in e.target&&(l=e.target.closest(c))&&"a"===l.tagName.toLowerCase()&&!e.target.closest(s.ignore)&&l.hostname===window.location.hostname&&l.pathname===window.location.pathname&&/#/.test(l.href)){var t,o;try{t=n(decodeURIComponent(l.hash))}catch(e){t=n(l.hash)}if("#"===t){if(!s.topOnEmptyHash)return;o=document.documentElement}else o=document.querySelector(t);(o=o||"#top"!==t?o:document.documentElement)&&(e.preventDefault(),function(e){if(history.replaceState&&e.updateURL&&!history.state){var t=window.location.hash;t=t||"",history.replaceState({smoothScroll:JSON.stringify(e),anchor:t||window.pageYOffset},document.title,t||window.location.href)}}(s),f.animateScroll(o,l))}},h=function(){if(null!==history.state&&history.state.smoothScroll&&history.state.smoothScroll===JSON.stringify(s)){var e=history.state.anchor;"string"==typeof e&&e&&!(e=document.querySelector(n(history.state.anchor)))||f.animateScroll(e,null,{updateURL:!1})}};f.destroy=function(){s&&(document.removeEventListener("click",w,!1),window.removeEventListener("popstate",h,!1),f.cancelScroll(),s=null,l=null,d=null,m=null)};return function(){if(!("querySelector"in document&&"addEventListener"in window&&"requestAnimationFrame"in window&&"closest"in window.Element.prototype))throw"Smooth Scroll: This browser does not support the required JavaScript methods and browser APIs.";f.destroy(),s=t(e,u||{}),d=s.header?document.querySelector(s.header):null,document.addEventListener("click",w,!1),s.updateURL&&s.popstate&&window.addEventListener("popstate",h,!1)}(),f}}))