
/*
 * jQuery FlexSlider v2.1
 * http://www.woothemes.com/flexslider/
 *
 * Copyright 2012 WooThemes
 * Free to use under the GPLv2 license.
 * http://www.gnu.org/licenses/gpl-2.0.html
 *
 * Contributing author: Tyler Smith (@mbmufffin)
 */

;(function ($) {

  //FlexSlider: Object Instance
  $.flexslider = function(el, options) {
    var slider = $(el),
        vars = $.extend({}, $.flexslider.defaults, options),
        namespace = vars.namespace,
        touch = ("ontouchstart" in window) || window.DocumentTouch && document instanceof DocumentTouch,
        eventType = (touch) ? "touchend" : "click",
        vertical = vars.direction === "vertical",
        reverse = vars.reverse,
        carousel = (vars.itemWidth > 0),
        fade = vars.animation === "fade",
        asNav = vars.asNavFor !== "",
        methods = {};

    // Store a reference to the slider object
    $.data(el, "flexslider", slider);

    // Privat slider methods
    methods = {
      init: function() {
        slider.animating = false;
        slider.currentSlide = vars.startAt;
        slider.animatingTo = slider.currentSlide;
        slider.atEnd = (slider.currentSlide === 0 || slider.currentSlide === slider.last);
        slider.containerSelector = vars.selector.substr(0,vars.selector.search(' '));
        slider.slides = $(vars.selector, slider);
        slider.container = $(slider.containerSelector, slider);
        slider.count = slider.slides.length;
        // SYNC:
        slider.syncExists = $(vars.sync).length > 0;
        // SLIDE:
        if (vars.animation === "slide") vars.animation = "swing";
        slider.prop = (vertical) ? "top" : "marginLeft";
        slider.args = {};
        // SLIDESHOW:
        slider.manualPause = false;
        // TOUCH/USECSS:
        slider.transitions = !vars.video && !fade && vars.useCSS && (function() {
          var obj = document.createElement('div'),
              props = ['perspectiveProperty', 'WebkitPerspective', 'MozPerspective', 'OPerspective', 'msPerspective'];
          for (var i in props) {
            if ( obj.style[ props[i] ] !== undefined ) {
              slider.pfx = props[i].replace('Perspective','').toLowerCase();
              slider.prop = "-" + slider.pfx + "-transform";
              return true;
            }
          }
          return false;
        }());
        // CONTROLSCONTAINER:
        if (vars.controlsContainer !== "") slider.controlsContainer = $(vars.controlsContainer).length > 0 && $(vars.controlsContainer);
        // MANUAL:
        if (vars.manualControls !== "") slider.manualControls = $(vars.manualControls).length > 0 && $(vars.manualControls);

        // RANDOMIZE:
        if (vars.randomize) {
          slider.slides.sort(function() { return (Math.round(Math.random())-0.5); });
          slider.container.empty().append(slider.slides);
        }

        slider.doMath();

        // ASNAV:
        if (asNav) methods.asNav.setup();

        // INIT
        slider.setup("init");

        // CONTROLNAV:
        if (vars.controlNav) methods.controlNav.setup();

        // DIRECTIONNAV:
        if (vars.directionNav) methods.directionNav.setup();

        // KEYBOARD:
        if (vars.keyboard && ($(slider.containerSelector).length === 1 || vars.multipleKeyboard)) {
          $(document).bind('keyup', function(event) {
            var keycode = event.keyCode;
            if (!slider.animating && (keycode === 39 || keycode === 37)) {
              var target = (keycode === 39) ? slider.getTarget('next') :
                           (keycode === 37) ? slider.getTarget('prev') : false;
              slider.flexAnimate(target, vars.pauseOnAction);
            }
          });
        }
        // MOUSEWHEEL:
        if (vars.mousewheel) {
          slider.bind('mousewheel', function(event, delta, deltaX, deltaY) {
            event.preventDefault();
            var target = (delta < 0) ? slider.getTarget('next') : slider.getTarget('prev');
            slider.flexAnimate(target, vars.pauseOnAction);
          });
        }

        // PAUSEPLAY
        if (vars.pausePlay) methods.pausePlay.setup();

        // SLIDSESHOW
        if (vars.slideshow) {
          if (vars.pauseOnHover) {
            slider.hover(function() {
              if (!slider.manualPlay && !slider.manualPause) slider.pause();
            }, function() {
              if (!slider.manualPause && !slider.manualPlay) slider.play();
            });
          }
          // initialize animation
          (vars.initDelay > 0) ? setTimeout(slider.play, vars.initDelay) : slider.play();
        }

        // TOUCH
        if (touch && vars.touch) methods.touch();

        // FADE&&SMOOTHHEIGHT || SLIDE:
        if (!fade || (fade && vars.smoothHeight)) $(window).bind("resize focus", methods.resize);


        // API: start() Callback
        setTimeout(function(){
          vars.start(slider);
        }, 200);
      },
      asNav: {
        setup: function() {
          slider.asNav = true;
          slider.animatingTo = Math.floor(slider.currentSlide/slider.move);
          slider.currentItem = slider.currentSlide;
          slider.slides.removeClass(namespace + "active-slide").eq(slider.currentItem).addClass(namespace + "active-slide");
          slider.slides.click(function(e){
            e.preventDefault();
            var $slide = $(this),
                target = $slide.index();
            if (!$(vars.asNavFor).data('flexslider').animating && !$slide.hasClass('active')) {
              slider.direction = (slider.currentItem < target) ? "next" : "prev";
              slider.flexAnimate(target, vars.pauseOnAction, false, true, true);
            }
          });
        }
      },
      controlNav: {
        setup: function() {
          if (!slider.manualControls) {
            methods.controlNav.setupPaging();
          } else { // MANUALCONTROLS:
            methods.controlNav.setupManual();
          }
        },
        setupPaging: function() {
          var type = (vars.controlNav === "thumbnails") ? 'control-thumbs' : 'control-paging',
              j = 1,
              item;

          slider.controlNavScaffold = $('<ol class="'+ namespace + 'control-nav ' + namespace + type + '"></ol>');

          if (slider.pagingCount > 1) {
            for (var i = 0; i < slider.pagingCount; i++) {
              item = (vars.controlNav === "thumbnails") ? '<img src="' + slider.slides.eq(i).attr("data-thumb") + '"/>' : '<a>' + j + '</a>';
              slider.controlNavScaffold.append('<li>' + item + '</li>');
              j++;
            }
          }

          // CONTROLSCONTAINER:
          (slider.controlsContainer) ? $(slider.controlsContainer).append(slider.controlNavScaffold) : slider.append(slider.controlNavScaffold);
          methods.controlNav.set();

          methods.controlNav.active();

          slider.controlNavScaffold.delegate('a, img', eventType, function(event) {
            event.preventDefault();
            var $this = $(this),
                target = slider.controlNav.index($this);

            if (!$this.hasClass(namespace + 'active')) {
              slider.direction = (target > slider.currentSlide) ? "next" : "prev";
              slider.flexAnimate(target, vars.pauseOnAction);
            }
          });
          // Prevent iOS click event bug
          if (touch) {
            slider.controlNavScaffold.delegate('a', "click touchstart", function(event) {
              event.preventDefault();
            });
          }
        },
        setupManual: function() {
          slider.controlNav = slider.manualControls;
          methods.controlNav.active();

          slider.controlNav.live(eventType, function(event) {
            event.preventDefault();
            var $this = $(this),
                target = slider.controlNav.index($this);

            if (!$this.hasClass(namespace + 'active')) {
              (target > slider.currentSlide) ? slider.direction = "next" : slider.direction = "prev";
              slider.flexAnimate(target, vars.pauseOnAction);
            }
          });
          // Prevent iOS click event bug
          if (touch) {
            slider.controlNav.live("click touchstart", function(event) {
              event.preventDefault();
            });
          }
        },
        set: function() {
          var selector = (vars.controlNav === "thumbnails") ? 'img' : 'a';
          slider.controlNav = $('.' + namespace + 'control-nav li ' + selector, (slider.controlsContainer) ? slider.controlsContainer : slider);
        },
        active: function() {
          slider.controlNav.removeClass(namespace + "active").eq(slider.animatingTo).addClass(namespace + "active");
        },
        update: function(action, pos) {
          if (slider.pagingCount > 1 && action === "add") {
            slider.controlNavScaffold.append($('<li><a>' + slider.count + '</a></li>'));
          } else if (slider.pagingCount === 1) {
            slider.controlNavScaffold.find('li').remove();
          } else {
            slider.controlNav.eq(pos).closest('li').remove();
          }
          methods.controlNav.set();
          (slider.pagingCount > 1 && slider.pagingCount !== slider.controlNav.length) ? slider.update(pos, action) : methods.controlNav.active();
        }
      },
      directionNav: {
        setup: function() {
          var directionNavScaffold = $('<ul class="' + namespace + 'direction-nav"><li><a class="' + namespace + 'prev" href="#">' + vars.prevText + '</a></li><li><a class="' + namespace + 'next" href="#">' + vars.nextText + '</a></li></ul>');

          // CONTROLSCONTAINER:
          if (slider.controlsContainer) {
            $(slider.controlsContainer).append(directionNavScaffold);
            slider.directionNav = $('.' + namespace + 'direction-nav li a', slider.controlsContainer);
          } else {
            slider.append(directionNavScaffold);
            slider.directionNav = $('.' + namespace + 'direction-nav li a', slider);
          }

          methods.directionNav.update();

          slider.directionNav.bind(eventType, function(event) {
            event.preventDefault();
            var target = ($(this).hasClass(namespace + 'next')) ? slider.getTarget('next') : slider.getTarget('prev');
            slider.flexAnimate(target, vars.pauseOnAction);
          });
          // Prevent iOS click event bug
          if (touch) {
            slider.directionNav.bind("click touchstart", function(event) {
              event.preventDefault();
            });
          }
        },
        update: function() {
          var disabledClass = namespace + 'disabled';
          if (slider.pagingCount === 1) {
            slider.directionNav.addClass(disabledClass);
          } else if (!vars.animationLoop) {
            if (slider.animatingTo === 0) {
              slider.directionNav.removeClass(disabledClass).filter('.' + namespace + "prev").addClass(disabledClass);
            } else if (slider.animatingTo === slider.last) {
              slider.directionNav.removeClass(disabledClass).filter('.' + namespace + "next").addClass(disabledClass);
            } else {
              slider.directionNav.removeClass(disabledClass);
            }
          } else {
            slider.directionNav.removeClass(disabledClass);
          }
        }
      },
      pausePlay: {
        setup: function() {
          var pausePlayScaffold = $('<div class="' + namespace + 'pauseplay"><a></a></div>');

          // CONTROLSCONTAINER:
          if (slider.controlsContainer) {
            slider.controlsContainer.append(pausePlayScaffold);
            slider.pausePlay = $('.' + namespace + 'pauseplay a', slider.controlsContainer);
          } else {
            slider.append(pausePlayScaffold);
            slider.pausePlay = $('.' + namespace + 'pauseplay a', slider);
          }

          methods.pausePlay.update((vars.slideshow) ? namespace + 'pause' : namespace + 'play');

          slider.pausePlay.bind(eventType, function(event) {
            event.preventDefault();
            if ($(this).hasClass(namespace + 'pause')) {
              slider.manualPause = true;
              slider.manualPlay = false;
              slider.pause();
            } else {
              slider.manualPause = false;
              slider.manualPlay = true;
              slider.play();
            }
          });
          // Prevent iOS click event bug
          if (touch) {
            slider.pausePlay.bind("click touchstart", function(event) {
              event.preventDefault();
            });
          }
        },
        update: function(state) {
          (state === "play") ? slider.pausePlay.removeClass(namespace + 'pause').addClass(namespace + 'play').text(vars.playText) : slider.pausePlay.removeClass(namespace + 'play').addClass(namespace + 'pause').text(vars.pauseText);
        }
      },
      touch: function() {
        var startX,
          startY,
          offset,
          cwidth,
          dx,
          startT,
          scrolling = false;

        el.addEventListener('touchstart', onTouchStart, false);
        function onTouchStart(e) {
          if (slider.animating) {
            e.preventDefault();
          } else if (e.touches.length === 1) {
            slider.pause();
            // CAROUSEL:
            cwidth = (vertical) ? slider.h : slider. w;
            startT = Number(new Date());
            // CAROUSEL:
            offset = (carousel && reverse && slider.animatingTo === slider.last) ? 0 :
                     (carousel && reverse) ? slider.limit - (((slider.itemW + vars.itemMargin) * slider.move) * slider.animatingTo) :
                     (carousel && slider.currentSlide === slider.last) ? slider.limit :
                     (carousel) ? ((slider.itemW + vars.itemMargin) * slider.move) * slider.currentSlide :
                     (reverse) ? (slider.last - slider.currentSlide + slider.cloneOffset) * cwidth : (slider.currentSlide + slider.cloneOffset) * cwidth;
            startX = (vertical) ? e.touches[0].pageY : e.touches[0].pageX;
            startY = (vertical) ? e.touches[0].pageX : e.touches[0].pageY;

            el.addEventListener('touchmove', onTouchMove, false);
            el.addEventListener('touchend', onTouchEnd, false);
          }
        }

        function onTouchMove(e) {
          dx = (vertical) ? startX - e.touches[0].pageY : startX - e.touches[0].pageX;
          scrolling = (vertical) ? (Math.abs(dx) < Math.abs(e.touches[0].pageX - startY)) : (Math.abs(dx) < Math.abs(e.touches[0].pageY - startY));

          if (!scrolling || Number(new Date()) - startT > 500) {
            e.preventDefault();
            if (!fade && slider.transitions) {
              if (!vars.animationLoop) {
                dx = dx/((slider.currentSlide === 0 && dx < 0 || slider.currentSlide === slider.last && dx > 0) ? (Math.abs(dx)/cwidth+2) : 1);
              }
              slider.setProps(offset + dx, "setTouch");
            }
          }
        }

        function onTouchEnd(e) {
          if (slider.animatingTo === slider.currentSlide && !scrolling && !(dx === null)) {
            var updateDx = (reverse) ? -dx : dx,
                target = (updateDx > 0) ? slider.getTarget('next') : slider.getTarget('prev');

            if (slider.canAdvance(target) && (Number(new Date()) - startT < 550 && Math.abs(updateDx) > 50 || Math.abs(updateDx) > cwidth/2)) {
              slider.flexAnimate(target, vars.pauseOnAction);
            } else {
              slider.flexAnimate(slider.currentSlide, vars.pauseOnAction, true);
            }
          }
          // finish the touch by undoing the touch session
          el.removeEventListener('touchmove', onTouchMove, false);
          el.removeEventListener('touchend', onTouchEnd, false);
          startX = null;
          startY = null;
          dx = null;
          offset = null;
        }
      },
      resize: function() {
        if (!slider.animating && slider.is(':visible')) {
          if (!carousel) slider.doMath();

          if (fade) {
            // SMOOTH HEIGHT:
            methods.smoothHeight();
          } else if (carousel) { //CAROUSEL:
            slider.slides.width(slider.computedW);
            slider.update(slider.pagingCount);
            slider.setProps();
          }
          else if (vertical) { //VERTICAL:
            slider.viewport.height(slider.h);
            slider.setProps(slider.h, "setTotal");
          } else {
            // SMOOTH HEIGHT:
            if (vars.smoothHeight) methods.smoothHeight();
            slider.newSlides.width(slider.computedW);
            slider.setProps(slider.computedW, "setTotal");
          }
        }
      },
      smoothHeight: function(dur) {
        if (!vertical || fade) {
          var $obj = (fade) ? slider : slider.viewport;
          (dur) ? $obj.animate({"height": slider.slides.eq(slider.animatingTo).height()}, dur) : $obj.height(slider.slides.eq(slider.animatingTo).height());
        }
      },
      sync: function(action) {
        var $obj = $(vars.sync).data("flexslider"),
            target = slider.animatingTo;

        switch (action) {
          case "animate": $obj.flexAnimate(target, vars.pauseOnAction, false, true); break;
          case "play": if (!$obj.playing && !$obj.asNav) { $obj.play(); } break;
          case "pause": $obj.pause(); break;
        }
      }
    }

    // public methods
    slider.flexAnimate = function(target, pause, override, withSync, fromNav) {
      if (asNav && slider.pagingCount === 1) slider.direction = (slider.currentItem < target) ? "next" : "prev";

      if (!slider.animating && (slider.canAdvance(target, fromNav) || override) && slider.is(":visible")) {
        if (asNav && withSync) {
          var master = $(vars.asNavFor).data('flexslider');
          slider.atEnd = target === 0 || target === slider.count - 1;
          master.flexAnimate(target, true, false, true, fromNav);
          slider.direction = (slider.currentItem < target) ? "next" : "prev";
          master.direction = slider.direction;

          if (Math.ceil((target + 1)/slider.visible) - 1 !== slider.currentSlide && target !== 0) {
            slider.currentItem = target;
            slider.slides.removeClass(namespace + "active-slide").eq(target).addClass(namespace + "active-slide");
            target = Math.floor(target/slider.visible);
          } else {
            slider.currentItem = target;
            slider.slides.removeClass(namespace + "active-slide").eq(target).addClass(namespace + "active-slide");
            return false;
          }
        }

        slider.animating = true;
        slider.animatingTo = target;
        // API: before() animation Callback
        vars.before(slider);

        // SLIDESHOW:
        if (pause) slider.pause();

        // SYNC:
        if (slider.syncExists && !fromNav) methods.sync("animate");

        // CONTROLNAV
        if (vars.controlNav) methods.controlNav.active();

        // !CAROUSEL:
        // CANDIDATE: slide active class (for add/remove slide)
        if (!carousel) slider.slides.removeClass(namespace + 'active-slide').eq(target).addClass(namespace + 'active-slide');

        // INFINITE LOOP:
        // CANDIDATE: atEnd
        slider.atEnd = target === 0 || target === slider.last;

        // DIRECTIONNAV:
        if (vars.directionNav) methods.directionNav.update();

        if (target === slider.last) {
          // API: end() of cycle Callback
          vars.end(slider);
          // SLIDESHOW && !INFINITE LOOP:
          if (!vars.animationLoop) slider.pause();
        }

        // SLIDE:
        if (!fade) {
          var dimension = (vertical) ? slider.slides.filter(':first').height() : slider.computedW,
              margin, slideString, calcNext;

          // INFINITE LOOP / REVERSE:
          if (carousel) {
            margin = (vars.itemWidth > slider.w) ? vars.itemMargin * 2 : vars.itemMargin;
            calcNext = ((slider.itemW + margin) * slider.move) * slider.animatingTo;
            slideString = (calcNext > slider.limit && slider.visible !== 1) ? slider.limit : calcNext;
          } else if (slider.currentSlide === 0 && target === slider.count - 1 && vars.animationLoop && slider.direction !== "next") {
            slideString = (reverse) ? (slider.count + slider.cloneOffset) * dimension : 0;
          } else if (slider.currentSlide === slider.last && target === 0 && vars.animationLoop && slider.direction !== "prev") {
            slideString = (reverse) ? 0 : (slider.count + 1) * dimension;
          } else {
            slideString = (reverse) ? ((slider.count - 1) - target + slider.cloneOffset) * dimension : (target + slider.cloneOffset) * dimension;
          }
          slider.setProps(slideString, "", vars.animationSpeed);
          if (slider.transitions) {
            if (!vars.animationLoop || !slider.atEnd) {
              slider.animating = false;
              slider.currentSlide = slider.animatingTo;
            }
            slider.container.unbind("webkitTransitionEnd transitionend");
            slider.container.bind("webkitTransitionEnd transitionend", function() {
              slider.wrapup(dimension);
            });
          } else {
            slider.container.animate(slider.args, vars.animationSpeed, vars.easing, function(){
              slider.wrapup(dimension);
            });
          }
        } else { // FADE:
          slider.slides.eq(slider.currentSlide).fadeOut(vars.animationSpeed, vars.easing);
          slider.slides.eq(target).fadeIn(vars.animationSpeed, vars.easing, slider.wrapup);
        }
        // SMOOTH HEIGHT:
        if (vars.smoothHeight) methods.smoothHeight(vars.animationSpeed);
      }
    }
    slider.wrapup = function(dimension) {
      // SLIDE:
      if (!fade && !carousel) {
        if (slider.currentSlide === 0 && slider.animatingTo === slider.last && vars.animationLoop) {
          slider.setProps(dimension, "jumpEnd");
        } else if (slider.currentSlide === slider.last && slider.animatingTo === 0 && vars.animationLoop) {
          slider.setProps(dimension, "jumpStart");
        }
      }
      slider.animating = false;
      slider.currentSlide = slider.animatingTo;
      // API: after() animation Callback
      vars.after(slider);
    }

    // SLIDESHOW:
    slider.animateSlides = function() {
      if (!slider.animating) slider.flexAnimate(slider.getTarget("next"));
    }
    // SLIDESHOW:
    slider.pause = function() {
      clearInterval(slider.animatedSlides);
      slider.playing = false;
      // PAUSEPLAY:
      if (vars.pausePlay) methods.pausePlay.update("play");
      // SYNC:
      if (slider.syncExists) methods.sync("pause");
    }
    // SLIDESHOW:
    slider.play = function() {
      slider.animatedSlides = setInterval(slider.animateSlides, vars.slideshowSpeed);
      slider.playing = true;
      // PAUSEPLAY:
      if (vars.pausePlay) methods.pausePlay.update("pause");
      // SYNC:
      if (slider.syncExists) methods.sync("play");
    }
    slider.canAdvance = function(target, fromNav) {
      // ASNAV:
      var last = (asNav) ? slider.pagingCount - 1 : slider.last;
      return (fromNav) ? true :
             (asNav && slider.currentItem === slider.count - 1 && target === 0 && slider.direction === "prev") ? true :
             (asNav && slider.currentItem === 0 && target === slider.pagingCount - 1 && slider.direction !== "next") ? false :
             (target === slider.currentSlide && !asNav) ? false :
             (vars.animationLoop) ? true :
             (slider.atEnd && slider.currentSlide === 0 && target === last && slider.direction !== "next") ? false :
             (slider.atEnd && slider.currentSlide === last && target === 0 && slider.direction === "next") ? false :
             true;
    }
    slider.getTarget = function(dir) {
      slider.direction = dir;
      if (dir === "next") {
        return (slider.currentSlide === slider.last) ? 0 : slider.currentSlide + 1;
      } else {
        return (slider.currentSlide === 0) ? slider.last : slider.currentSlide - 1;
      }
    }

    // SLIDE:
    slider.setProps = function(pos, special, dur) {
      var target = (function() {
        var posCheck = (pos) ? pos : ((slider.itemW + vars.itemMargin) * slider.move) * slider.animatingTo,
            posCalc = (function() {
              if (carousel) {
                return (special === "setTouch") ? pos :
                       (reverse && slider.animatingTo === slider.last) ? 0 :
                       (reverse) ? slider.limit - (((slider.itemW + vars.itemMargin) * slider.move) * slider.animatingTo) :
                       (slider.animatingTo === slider.last) ? slider.limit : posCheck;
              } else {
                switch (special) {
                  case "setTotal": return (reverse) ? ((slider.count - 1) - slider.currentSlide + slider.cloneOffset) * pos : (slider.currentSlide + slider.cloneOffset) * pos;
                  case "setTouch": return (reverse) ? pos : pos;
                  case "jumpEnd": return (reverse) ? pos : slider.count * pos;
                  case "jumpStart": return (reverse) ? slider.count * pos : pos;
                  default: return pos;
                }
              }
            }());
            return (posCalc * -1) + "px";
          }());

      if (slider.transitions) {
        target = (vertical) ? "translate3d(0," + target + ",0)" : "translate3d(" + target + ",0,0)";
        dur = (dur !== undefined) ? (dur/1000) + "s" : "0s";
        slider.container.css("-" + slider.pfx + "-transition-duration", dur);
      }

      slider.args[slider.prop] = target;
      if (slider.transitions || dur === undefined) slider.container.css(slider.args);
    }

    slider.setup = function(type) {
      // SLIDE:
      if (!fade) {
        var sliderOffset, arr;

        if (type === "init") {
          slider.viewport = $('<div class="' + namespace + 'viewport"></div>').css({"overflow": "hidden", "position": "relative"}).appendTo(slider).append(slider.container);
          // INFINITE LOOP:
          slider.cloneCount = 0;
          slider.cloneOffset = 0;
          // REVERSE:
          if (reverse) {
            arr = $.makeArray(slider.slides).reverse();
            slider.slides = $(arr);
            slider.container.empty().append(slider.slides);
          }
        }
        // INFINITE LOOP && !CAROUSEL:
        if (vars.animationLoop && !carousel) {
          slider.cloneCount = 2;
          slider.cloneOffset = 1;
          // clear out old clones
          if (type !== "init") slider.container.find('.clone').remove();
          slider.container.append(slider.slides.first().clone().addClass('clone')).prepend(slider.slides.last().clone().addClass('clone'));
        }
        slider.newSlides = $(vars.selector, slider);

        sliderOffset = (reverse) ? slider.count - 1 - slider.currentSlide + slider.cloneOffset : slider.currentSlide + slider.cloneOffset;
        // VERTICAL:
        if (vertical && !carousel) {
          slider.container.height((slider.count + slider.cloneCount) * 200 + "%").css("position", "absolute").width("100%");
          setTimeout(function(){
            slider.newSlides.css({"display": "list-item"});
            slider.doMath();
            slider.viewport.height(slider.h);
            slider.setProps(sliderOffset * slider.h, "init");
          }, (type === "init") ? 100 : 0);
        } else {
          slider.container.width((slider.count + slider.cloneCount) * 200 + "%");
          slider.setProps(sliderOffset * slider.computedW, "init");
          setTimeout(function(){
            slider.doMath();
            slider.newSlides.css({"width": slider.computedW, "float": "left", "display": "list-item"});
            // SMOOTH HEIGHT:
            if (vars.smoothHeight) methods.smoothHeight();
          }, (type === "init") ? 100 : 0);
        }
      } else { // FADE:
        slider.slides.css({"width": "100%", "float": "left", "marginRight": "-100%", "position": "relative"});
        if (type === "init") slider.slides.eq(slider.currentSlide).fadeIn(vars.animationSpeed, vars.easing);
        // SMOOTH HEIGHT:
        if (vars.smoothHeight) methods.smoothHeight();
      }
      // !CAROUSEL:
      // CANDIDATE: active slide
      if (!carousel) slider.slides.removeClass(namespace + "active-slide").eq(slider.currentSlide).addClass(namespace + "active-slide");
    }

    slider.doMath = function() {
      var slide = slider.slides.first(),
          slideMargin = vars.itemMargin,
          minItems = vars.minItems,
          maxItems = vars.maxItems;

      slider.w = slider.width();
      slider.h = slide.height();
      slider.boxPadding = slide.outerWidth() - slide.width();

      // CAROUSEL:
      if (carousel) {
        slider.itemT = vars.itemWidth + slideMargin;
        slider.minW = (minItems) ? minItems * slider.itemT : slider.w;
        slider.maxW = (maxItems) ? maxItems * slider.itemT : slider.w;
        slider.itemW = (slider.minW > slider.w) ? (slider.w - (slideMargin * minItems))/minItems :
                       (slider.maxW < slider.w) ? (slider.w - (slideMargin * maxItems))/maxItems :
                       (vars.itemWidth > slider.w) ? slider.w : vars.itemWidth;
        slider.visible = Math.floor(slider.w/(slider.itemW + slideMargin));
        slider.move = (vars.move > 0 && vars.move < slider.visible ) ? vars.move : slider.visible;
        slider.pagingCount = Math.ceil(((slider.count - slider.visible)/slider.move) + 1);
        slider.last =  slider.pagingCount - 1;
        slider.limit = (slider.pagingCount === 1) ? 0 :
                       (vars.itemWidth > slider.w) ? ((slider.itemW + (slideMargin * 2)) * slider.count) - slider.w - slideMargin : ((slider.itemW + slideMargin) * slider.count) - slider.w - slideMargin;
      } else {
        slider.itemW = slider.w;
        slider.pagingCount = slider.count;
        slider.last = slider.count - 1;
      }
      slider.computedW = slider.itemW - slider.boxPadding;
    }

    slider.update = function(pos, action) {
      slider.doMath();

      // update currentSlide and slider.animatingTo if necessary
      if (!carousel) {
        if (pos < slider.currentSlide) {
          slider.currentSlide += 1;
        } else if (pos <= slider.currentSlide && pos !== 0) {
          slider.currentSlide -= 1;
        }
        slider.animatingTo = slider.currentSlide;
      }

      // update controlNav
      if (vars.controlNav && !slider.manualControls) {
        if ((action === "add" && !carousel) || slider.pagingCount > slider.controlNav.length) {
          methods.controlNav.update("add");
        } else if ((action === "remove" && !carousel) || slider.pagingCount < slider.controlNav.length) {
          if (carousel && slider.currentSlide > slider.last) {
            slider.currentSlide -= 1;
            slider.animatingTo -= 1;
          }
          methods.controlNav.update("remove", slider.last);
        }
      }
      // update directionNav
      if (vars.directionNav) methods.directionNav.update();

    }

    slider.addSlide = function(obj, pos) {
      var $obj = $(obj);

      slider.count += 1;
      slider.last = slider.count - 1;

      // append new slide
      if (vertical && reverse) {
        (pos !== undefined) ? slider.slides.eq(slider.count - pos).after($obj) : slider.container.prepend($obj);
      } else {
        (pos !== undefined) ? slider.slides.eq(pos).before($obj) : slider.container.append($obj);
      }

      // update currentSlide, animatingTo, controlNav, and directionNav
      slider.update(pos, "add");

      // update slider.slides
      slider.slides = $(vars.selector + ':not(.clone)', slider);
      // re-setup the slider to accomdate new slide
      slider.setup();

      //FlexSlider: added() Callback
      vars.added(slider);
    }
    slider.removeSlide = function(obj) {
      var pos = (isNaN(obj)) ? slider.slides.index($(obj)) : obj;

      // update count
      slider.count -= 1;
      slider.last = slider.count - 1;

      // remove slide
      if (isNaN(obj)) {
        $(obj, slider.slides).remove();
      } else {
        (vertical && reverse) ? slider.slides.eq(slider.last).remove() : slider.slides.eq(obj).remove();
      }

      // update currentSlide, animatingTo, controlNav, and directionNav
      slider.doMath();
      slider.update(pos, "remove");

      // update slider.slides
      slider.slides = $(vars.selector + ':not(.clone)', slider);
      // re-setup the slider to accomdate new slide
      slider.setup();

      // FlexSlider: removed() Callback
      vars.removed(slider);
    }

    //FlexSlider: Initialize
    methods.init();
  }

  //FlexSlider: Default Settings
  $.flexslider.defaults = {
    namespace: "flex-",             //{NEW} String: Prefix string attached to the class of every element generated by the plugin
    selector: ".slides > li",       //{NEW} Selector: Must match a simple pattern. '{container} > {slide}' -- Ignore pattern at your own peril
    animation: "fade",              //String: Select your animation type, "fade" or "slide"
    easing: "swing",               //{NEW} String: Determines the easing method used in jQuery transitions. jQuery easing plugin is supported!
    direction: "horizontal",        //String: Select the sliding direction, "horizontal" or "vertical"
    reverse: false,                 //{NEW} Boolean: Reverse the animation direction
    animationLoop: true,             //Boolean: Should the animation loop? If false, directionNav will received "disable" classes at either end
    smoothHeight: false,            //{NEW} Boolean: Allow height of the slider to animate smoothly in horizontal mode
    startAt: 0,                     //Integer: The slide that the slider should start on. Array notation (0 = first slide)
    slideshow: true,                //Boolean: Animate slider automatically
    slideshowSpeed: 7000,           //Integer: Set the speed of the slideshow cycling, in milliseconds
    animationSpeed: 600,            //Integer: Set the speed of animations, in milliseconds
    initDelay: 0,                   //{NEW} Integer: Set an initialization delay, in milliseconds
    randomize: false,               //Boolean: Randomize slide order

    // Usability features
    pauseOnAction: true,            //Boolean: Pause the slideshow when interacting with control elements, highly recommended.
    pauseOnHover: false,            //Boolean: Pause the slideshow when hovering over slider, then resume when no longer hovering
    useCSS: true,                   //{NEW} Boolean: Slider will use CSS3 transitions if available
    touch: true,                    //{NEW} Boolean: Allow touch swipe navigation of the slider on touch-enabled devices
    video: false,                   //{NEW} Boolean: If using video in the slider, will prevent CSS3 3D Transforms to avoid graphical glitches

    // Primary Controls
    controlNav: true,               //Boolean: Create navigation for paging control of each clide? Note: Leave true for manualControls usage
    directionNav: true,             //Boolean: Create navigation for previous/next navigation? (true/false)
    prevText: "Previous",           //String: Set the text for the "previous" directionNav item
    nextText: "Next",               //String: Set the text for the "next" directionNav item

    // Secondary Navigation
    keyboard: true,                 //Boolean: Allow slider navigating via keyboard left/right keys
    multipleKeyboard: false,        //{NEW} Boolean: Allow keyboard navigation to affect multiple sliders. Default behavior cuts out keyboard navigation with more than one slider present.
    mousewheel: false,              //{UPDATED} Boolean: Requires jquery.mousewheel.js (https://github.com/brandonaaron/jquery-mousewheel) - Allows slider navigating via mousewheel
    pausePlay: false,               //Boolean: Create pause/play dynamic element
    pauseText: "Pause",             //String: Set the text for the "pause" pausePlay item
    playText: "Play",               //String: Set the text for the "play" pausePlay item

    // Special properties
    controlsContainer: "",          //{UPDATED} jQuery Object/Selector: Declare which container the navigation elements should be appended too. Default container is the FlexSlider element. Example use would be $(".flexslider-container"). Property is ignored if given element is not found.
    manualControls: "",             //{UPDATED} jQuery Object/Selector: Declare custom control navigation. Examples would be $(".flex-control-nav li") or "#tabs-nav li img", etc. The number of elements in your controlNav should match the number of slides/tabs.
    sync: "",                       //{NEW} Selector: Mirror the actions performed on this slider with another slider. Use with care.
    asNavFor: "",                   //{NEW} Selector: Internal property exposed for turning the slider into a thumbnail navigation for another slider

    // Carousel Options
    itemWidth: 0,                   //{NEW} Integer: Box-model width of individual carousel items, including horizontal borders and padding.
    itemMargin: 0,                  //{NEW} Integer: Margin between carousel items.
    minItems: 0,                    //{NEW} Integer: Minimum number of carousel items that should be visible. Items will resize fluidly when below this.
    maxItems: 0,                    //{NEW} Integer: Maxmimum number of carousel items that should be visible. Items will resize fluidly when above this limit.
    move: 0,                        //{NEW} Integer: Number of carousel items that should move on animation. If 0, slider will move all visible items.

    // Callback API
    start: function(){},            //Callback: function(slider) - Fires when the slider loads the first slide
    before: function(){},           //Callback: function(slider) - Fires asynchronously with each slider animation
    after: function(){},            //Callback: function(slider) - Fires after each slider animation completes
    end: function(){},              //Callback: function(slider) - Fires when the slider reaches the last slide (asynchronous)
    added: function(){},            //{NEW} Callback: function(slider) - Fires after a slide is added
    removed: function(){}           //{NEW} Callback: function(slider) - Fires after a slide is removed
  }


  //FlexSlider: Plugin Function
  $.fn.flexslider = function(options) {
    if (options === undefined) options = {};

    if (typeof options === "object") {
      return this.each(function() {
        var $this = $(this),
            selector = (options.selector) ? options.selector : ".slides > li",
            $slides = $this.find(selector);

        if ($slides.length === 1) {
          $slides.fadeIn(400);
          if (options.start) options.start($this);
        } else if ($this.data('flexslider') === undefined) {
          new $.flexslider(this, options);
        }
      });
    } else {
      // Helper strings to quickly perform functions on the slider
      var $slider = $(this).data('flexslider');
      switch (options) {
        case "play": $slider.play(); break;
        case "pause": $slider.pause(); break;
        case "next": $slider.flexAnimate($slider.getTarget("next"), true); break;
        case "prev":
        case "previous": $slider.flexAnimate($slider.getTarget("prev"), true); break;
        default: if (typeof options === "number") $slider.flexAnimate(options, true);
      }
    }
  }

})(jQuery);
jQuery(document).ready(function () {
	$('.tx-bilfingerpresenter').parent('div').addClass('bilfingerpresenterbox');

        $(window).load(function () {
            //$('.in2flexconf').each(function(){
                // Options Flexslider
                var options = new Array();

                options['slideshowSpeed'] = 7000;
                if (parseInt($('.settings_additional_slideshowSpeed').html()) > 0) {
                    options['slideshowSpeed'] = parseInt($('.settings_additional_slideshowSpeed').html());
                }

                //options['easing'] = 'linear';
                options['animationSpeed'] = 600;
                if (parseInt($('.settings_additional_animationSpeed').html()) > 0) {
                    options['animationSpeed'] = parseInt($('.settings_additional_animationSpeed').html());
                }

                options['initDelay'] = 0;
                if (parseInt($('.settings_additional_initDelay').html()) > 0) {
                    options['initDelay'] = parseInt($('.settings_additional_initDelay').html());
                }
           // });

		$('.flexslider').flexslider({
			animation : 'fade',
			controlsContainer : ".flex-container",
			pauseOnHover:true,
			slideshowSpeed:options['slideshowSpeed'], //Integer: Set the speed of the slideshow cycling, in milliseconds
			animationSpeed:options['animationSpeed'],
			before : function(slider) {
				$('.imagecontrols div').each(function(){
					$(this).removeClass('active');
				});
				var number = slider.currentSlide + 1;
				var total = slider.count;
				if (number == total) {
					number = 0;
				}
				var controlid = '#item_' + number;
				$(controlid).addClass('active');
			}
		});
	});

	$('.imagecontrols div').click( function() {
		var myclass = $(this).attr('id');
		var number = myclass.split("_");
		var id = parseInt(number[1]);
		$('.flexslider').flexslider(id);
		$('.imagecontrols div').each(function () {
			$(this).removeClass('active');
		});
		$(this).addClass('active');
	});

});

!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.listen("parsley:field:error",function(){setTimeout(function(){a.find("."+n.tabMenuClassName+" > ."+n.tabMenuItemErrorClassName+":first").click()},50)})}function s(a,n,t,i){$activeTab=p(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=p(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=p(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=b(e,a),t=n.index(p(e,a));return parseInt(t)}function b(e,a){return e.find("."+a.tabMenuClassName).children()}function p(e,a){var n=b(e,a);return n.filter("."+a.tabMenuItemActiveClassName)}function v(e,a){var n=b(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=b(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)}});
/*! fancyBox v2.1.1 fancyapps.com | fancyapps.com/fancybox/#license */
(function(v,q,f,r){var p=f(v),n=f(q),b=f.fancybox=function(){b.open.apply(this,arguments)},A=null,m=q.createTouch!==r,y=function(a){return a&&a.hasOwnProperty&&a instanceof f},t=function(a){return a&&"string"===f.type(a)},D=function(a){return t(a)&&0<a.indexOf("%")},k=function(a,d){var e=parseInt(a,10)||0;d&&D(a)&&(e*=b.getViewport()[d]/100);return Math.ceil(e)},w=function(a,b){return k(a,b)+"px"};f.extend(b,{version:"2.1.1",defaults:{padding:15,margin:20,width:800,height:600,minWidth:100,minHeight:100,
maxWidth:9999,maxHeight:9999,autoSize:!0,autoHeight:!1,autoWidth:!1,autoResize:!m,autoCenter:!m,fitToView:!0,aspectRatio:!1,topRatio:0.5,leftRatio:0.5,scrolling:"auto",wrapCSS:"",arrows:!0,closeBtn:!0,closeClick:!1,nextClick:!1,mouseWheel:!0,autoPlay:!1,playSpeed:3E3,preload:3,modal:!1,loop:!0,ajax:{dataType:"html",headers:{"X-fancyBox":!0}},iframe:{scrolling:"auto",preload:!0},swf:{wmode:"transparent",allowfullscreen:"true",allowscriptaccess:"always"},keys:{next:{13:"left",34:"up",39:"left",40:"up"},
prev:{8:"right",33:"down",37:"right",38:"down"},close:[27],play:[32],toggle:[70]},direction:{next:"left",prev:"right"},scrollOutside:!0,index:0,type:null,href:null,content:null,title:null,tpl:{wrap:'<div class="fancybox-wrap" tabIndex="-1"><div class="fancybox-skin"><div class="fancybox-outer"><div class="fancybox-inner"></div></div></div></div>',image:'<img class="fancybox-image" src="{href}" alt="" />',iframe:'<iframe id="fancybox-frame{rnd}" name="fancybox-frame{rnd}" class="fancybox-iframe" frameborder="0" vspace="0" hspace="0"'+
(f.browser.msie?' allowtransparency="true"':"")+"></iframe>",error:'<p class="fancybox-error">The requested content cannot be loaded.<br/>Please try again later.</p>',closeBtn:'<a title="Close" class="fancybox-item fancybox-close" href="javascript:;"></a>',next:'<a title="Next" class="fancybox-nav fancybox-next" href="javascript:;"><span></span></a>',prev:'<a title="Previous" class="fancybox-nav fancybox-prev" href="javascript:;"><span></span></a>'},openEffect:"fade",openSpeed:250,openEasing:"swing",
openOpacity:!0,openMethod:"zoomIn",closeEffect:"fade",closeSpeed:250,closeEasing:"swing",closeOpacity:!0,closeMethod:"zoomOut",nextEffect:"elastic",nextSpeed:250,nextEasing:"swing",nextMethod:"changeIn",prevEffect:"elastic",prevSpeed:250,prevEasing:"swing",prevMethod:"changeOut",helpers:{overlay:!0,title:!0},onCancel:f.noop,beforeLoad:f.noop,afterLoad:f.noop,beforeShow:f.noop,afterShow:f.noop,beforeChange:f.noop,beforeClose:f.noop,afterClose:f.noop},group:{},opts:{},previous:null,coming:null,current:null,
isActive:!1,isOpen:!1,isOpened:!1,wrap:null,skin:null,outer:null,inner:null,player:{timer:null,isActive:!1},ajaxLoad:null,imgPreload:null,transitions:{},helpers:{},open:function(a,d){if(a&&(f.isPlainObject(d)||(d={}),!1!==b.close(!0)))return f.isArray(a)||(a=y(a)?f(a).get():[a]),f.each(a,function(e,c){var j={},g,h,i,l,k;"object"===f.type(c)&&(c.nodeType&&(c=f(c)),y(c)?(j={href:c.data("fancybox-href")||c.attr("href"),title:c.data("fancybox-title")||c.attr("title"),isDom:!0,element:c},f.metadata&&f.extend(!0,
j,c.metadata())):j=c);g=d.href||j.href||(t(c)?c:null);h=d.title!==r?d.title:j.title||"";l=(i=d.content||j.content)?"html":d.type||j.type;!l&&j.isDom&&(l=c.data("fancybox-type"),l||(l=(l=c.prop("class").match(/fancybox\.(\w+)/))?l[1]:null));t(g)&&(l||(b.isImage(g)?l="image":b.isSWF(g)?l="swf":"#"===g.charAt(0)?l="inline":t(c)&&(l="html",i=c)),"ajax"===l&&(k=g.split(/\s+/,2),g=k.shift(),k=k.shift()));i||("inline"===l?g?i=f(t(g)?g.replace(/.*(?=#[^\s]+$)/,""):g):j.isDom&&(i=c):"html"===l?i=g:!l&&(!g&&
j.isDom)&&(l="inline",i=c));f.extend(j,{href:g,type:l,content:i,title:h,selector:k});a[e]=j}),b.opts=f.extend(!0,{},b.defaults,d),d.keys!==r&&(b.opts.keys=d.keys?f.extend({},b.defaults.keys,d.keys):!1),b.group=a,b._start(b.opts.index)},cancel:function(){var a=b.coming;a&&!1!==b.trigger("onCancel")&&(b.hideLoading(),b.ajaxLoad&&b.ajaxLoad.abort(),b.ajaxLoad=null,b.imgPreload&&(b.imgPreload.onload=b.imgPreload.onerror=null),a.wrap&&a.wrap.stop(!0).trigger("onReset").remove(),b.current||b.trigger("afterClose"),
b.coming=null)},close:function(a){b.cancel();!1!==b.trigger("beforeClose")&&(b.unbindEvents(),!b.isOpen||!0===a?(f(".fancybox-wrap").stop(!0).trigger("onReset").remove(),b._afterZoomOut()):(b.isOpen=b.isOpened=!1,b.isClosing=!0,f(".fancybox-item, .fancybox-nav").remove(),b.wrap.stop(!0,!0).removeClass("fancybox-opened"),"fixed"===b.wrap.css("position")&&b.wrap.css(b._getPosition(!0)),b.transitions[b.current.closeMethod]()))},play:function(a){var d=function(){clearTimeout(b.player.timer)},e=function(){d();
b.current&&b.player.isActive&&(b.player.timer=setTimeout(b.next,b.current.playSpeed))},c=function(){d();f("body").unbind(".player");b.player.isActive=!1;b.trigger("onPlayEnd")};if(!0===a||!b.player.isActive&&!1!==a){if(b.current&&(b.current.loop||b.current.index<b.group.length-1))b.player.isActive=!0,f("body").bind({"afterShow.player onUpdate.player":e,"onCancel.player beforeClose.player":c,"beforeLoad.player":d}),e(),b.trigger("onPlayStart")}else c()},next:function(a){var d=b.current;d&&(t(a)||(a=
d.direction.next),b.jumpto(d.index+1,a,"next"))},prev:function(a){var d=b.current;d&&(t(a)||(a=d.direction.prev),b.jumpto(d.index-1,a,"prev"))},jumpto:function(a,d,e){var c=b.current;c&&(a=k(a),b.direction=d||c.direction[a>=c.index?"next":"prev"],b.router=e||"jumpto",c.loop&&(0>a&&(a=c.group.length+a%c.group.length),a%=c.group.length),c.group[a]!==r&&(b.cancel(),b._start(a)))},reposition:function(a,d){var e;b.isOpen&&(e=b._getPosition(d),a&&"scroll"===a.type?(delete e.position,b.wrap.stop(!0,!0).animate(e,
200)):b.wrap.css(e))},update:function(a){var d=a&&a.type,e=!d||"orientationchange"===d;e&&(clearTimeout(A),A=null);if(b.isOpen&&!A){if(e||m)b.wrap.removeAttr("style").addClass("fancybox-tmp"),b.trigger("onUpdate");A=setTimeout(function(){var c=b.current;c&&(b.wrap.removeClass("fancybox-tmp"),"scroll"!==d&&b._setDimension(),"scroll"===d&&c.canShrink||b.reposition(a),b.trigger("onUpdate"),A=null)},m?500:e?20:300)}},toggle:function(a){b.isOpen&&(b.current.fitToView="boolean"===f.type(a)?a:!b.current.fitToView,
b.update())},hideLoading:function(){n.unbind("keypress.fb");f("#fancybox-loading").remove()},showLoading:function(){var a,d;b.hideLoading();n.bind("keypress.fb",function(a){if(27===(a.which||a.keyCode))a.preventDefault(),b.cancel()});a=f('<div id="fancybox-loading"><div></div></div>').click(b.cancel).appendTo("body");b.defaults.fixed||(d=b.getViewport(),a.css({position:"absolute",top:0.5*d.h+d.y,left:0.5*d.w+d.x}))},getViewport:function(){var a=b.current&&b.current.locked||!1,d={x:p.scrollLeft(),
y:p.scrollTop()};a?(d.w=a[0].clientWidth,d.h=a[0].clientHeight):(d.w=m&&v.innerWidth?v.innerWidth:p.width(),d.h=m&&v.innerHeight?v.innerHeight:p.height());return d},unbindEvents:function(){b.wrap&&y(b.wrap)&&b.wrap.unbind(".fb");n.unbind(".fb");p.unbind(".fb")},bindEvents:function(){var a=b.current,d;a&&(p.bind("orientationchange.fb"+(a.autoResize?" resize.fb":"")+(a.autoCenter&&!a.locked?" scroll.fb":""),b.update),(d=a.keys)&&n.bind("keydown.fb",function(e){var c=e.which||e.keyCode,j=e.target||e.srcElement;
!e.ctrlKey&&(!e.altKey&&!e.shiftKey&&!e.metaKey&&(!j||!j.type&&!f(j).is("[contenteditable]")))&&f.each(d,function(d,j){if(1<a.group.length&&j[c]!==r)return b[d](j[c]),e.preventDefault(),!1;if(-1<f.inArray(c,j))return b[d](),e.preventDefault(),!1})}),f.fn.mousewheel&&a.mouseWheel&&b.wrap.bind("mousewheel.fb",function(d,c,j,g){for(var h=f(d.target||null),i=!1;h.length&&!i&&!h.is(".fancybox-skin")&&!h.is(".fancybox-wrap");)i=h[0]&&!(h[0].style.overflow&&"hidden"===h[0].style.overflow)&&(h[0].clientWidth&&
h[0].scrollWidth>h[0].clientWidth||h[0].clientHeight&&h[0].scrollHeight>h[0].clientHeight),h=f(h).parent();if(0!==c&&!i&&1<b.group.length&&!a.canShrink){if(0<g||0<j)b.prev(0<g?"down":"left");else if(0>g||0>j)b.next(0>g?"up":"right");d.preventDefault()}}))},trigger:function(a,d){var e,c=d||b.coming||b.current;if(c){f.isFunction(c[a])&&(e=c[a].apply(c,Array.prototype.slice.call(arguments,1)));if(!1===e)return!1;"onCancel"===a&&!b.isOpened&&(b.isActive=!1);c.helpers&&f.each(c.helpers,function(d,e){e&&
(b.helpers[d]&&f.isFunction(b.helpers[d][a]))&&(e=f.extend(!0,{},b.helpers[d].defaults,e),b.helpers[d][a](e,c))});f.event.trigger(a+".fb")}},isImage:function(a){return t(a)&&a.match(/(^data:image\/.*,)|(\.(jp(e|g|eg)|gif|png|bmp|webp)((\?|#).*)?$)/i)},isSWF:function(a){return t(a)&&a.match(/\.(swf)((\?|#).*)?$/i)},_start:function(a){var d={},e,c,a=k(a);e=b.group[a]||null;if(!e)return!1;d=f.extend(!0,{},b.opts,e);e=d.margin;c=d.padding;"number"===f.type(e)&&(d.margin=[e,e,e,e]);"number"===f.type(c)&&
(d.padding=[c,c,c,c]);d.modal&&f.extend(!0,d,{closeBtn:!1,closeClick:!1,nextClick:!1,arrows:!1,mouseWheel:!1,keys:null,helpers:{overlay:{closeClick:!1}}});d.autoSize&&(d.autoWidth=d.autoHeight=!0);"auto"===d.width&&(d.autoWidth=!0);"auto"===d.height&&(d.autoHeight=!0);d.group=b.group;d.index=a;b.coming=d;if(!1===b.trigger("beforeLoad"))b.coming=null;else{c=d.type;e=d.href;if(!c)return b.coming=null,b.current&&b.router&&"jumpto"!==b.router?(b.current.index=a,b[b.router](b.direction)):!1;b.isActive=
!0;if("image"===c||"swf"===c)d.autoHeight=d.autoWidth=!1,d.scrolling="visible";"image"===c&&(d.aspectRatio=!0);"iframe"===c&&m&&(d.scrolling="scroll");d.wrap=f(d.tpl.wrap).addClass("fancybox-"+(m?"mobile":"desktop")+" fancybox-type-"+c+" fancybox-tmp "+d.wrapCSS).appendTo(d.parent||"body");f.extend(d,{skin:f(".fancybox-skin",d.wrap),outer:f(".fancybox-outer",d.wrap),inner:f(".fancybox-inner",d.wrap)});f.each(["Top","Right","Bottom","Left"],function(a,b){d.skin.css("padding"+b,w(d.padding[a]))});b.trigger("onReady");
if("inline"===c||"html"===c){if(!d.content||!d.content.length)return b._error("content")}else if(!e)return b._error("href");"image"===c?b._loadImage():"ajax"===c?b._loadAjax():"iframe"===c?b._loadIframe():b._afterLoad()}},_error:function(a){f.extend(b.coming,{type:"html",autoWidth:!0,autoHeight:!0,minWidth:0,minHeight:0,scrolling:"no",hasError:a,content:b.coming.tpl.error});b._afterLoad()},_loadImage:function(){var a=b.imgPreload=new Image;a.onload=function(){this.onload=this.onerror=null;b.coming.width=
this.width;b.coming.height=this.height;b._afterLoad()};a.onerror=function(){this.onload=this.onerror=null;b._error("image")};a.src=b.coming.href;(a.complete===r||!a.complete)&&b.showLoading()},_loadAjax:function(){var a=b.coming;b.showLoading();b.ajaxLoad=f.ajax(f.extend({},a.ajax,{url:a.href,error:function(a,e){b.coming&&"abort"!==e?b._error("ajax",a):b.hideLoading()},success:function(d,e){"success"===e&&(a.content=d,b._afterLoad())}}))},_loadIframe:function(){var a=b.coming,d=f(a.tpl.iframe.replace(/\{rnd\}/g,
(new Date).getTime())).attr("scrolling",m?"auto":a.iframe.scrolling).attr("src",a.href);f(a.wrap).bind("onReset",function(){try{f(this).find("iframe").hide().attr("src","//about:blank").end().empty()}catch(a){}});a.iframe.preload&&(b.showLoading(),d.one("load",function(){f(this).data("ready",1);m||f(this).bind("load.fb",b.update);f(this).parents(".fancybox-wrap").width("100%").removeClass("fancybox-tmp").show();b._afterLoad()}));a.content=d.appendTo(a.inner);a.iframe.preload||b._afterLoad()},_preloadImages:function(){var a=
b.group,d=b.current,e=a.length,c=d.preload?Math.min(d.preload,e-1):0,f,g;for(g=1;g<=c;g+=1)f=a[(d.index+g)%e],"image"===f.type&&f.href&&((new Image).src=f.href)},_afterLoad:function(){var a=b.coming,d=b.current,e,c,j,g,h;b.hideLoading();if(a&&!1!==b.isActive)if(!1===b.trigger("afterLoad",a,d))a.wrap.stop(!0).trigger("onReset").remove(),b.coming=null;else{d&&(b.trigger("beforeChange",d),d.wrap.stop(!0).removeClass("fancybox-opened").find(".fancybox-item, .fancybox-nav").remove(),"fixed"===d.wrap.css("position")&&
d.wrap.css(b._getPosition(!0)));b.unbindEvents();e=a.content;c=a.type;j=a.scrolling;f.extend(b,{wrap:a.wrap,skin:a.skin,outer:a.outer,inner:a.inner,current:a,previous:d});g=a.href;switch(c){case "inline":case "ajax":case "html":a.selector?e=f("<div>").html(e).find(a.selector):y(e)&&(e.data("fancybox-placeholder")||e.data("fancybox-placeholder",f('<div class="fancybox-placeholder"></div>').insertAfter(e).hide()),e=e.show().detach(),a.wrap.bind("onReset",function(){f(this).find(e).length&&e.hide().replaceAll(e.data("fancybox-placeholder")).data("fancybox-placeholder",
!1)}));break;case "image":e=a.tpl.image.replace("{href}",g);break;case "swf":e='<object id="fancybox-swf" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="100%" height="100%"><param name="movie" value="'+g+'"></param>',h="",f.each(a.swf,function(a,b){e+='<param name="'+a+'" value="'+b+'"></param>';h+=" "+a+'="'+b+'"'}),e+='<embed src="'+g+'" type="application/x-shockwave-flash" width="100%" height="100%"'+h+"></embed></object>"}(!y(e)||!e.parent().is(a.inner))&&a.inner.append(e);b.trigger("beforeShow");
a.inner.css("overflow","yes"===j?"scroll":"no"===j?"hidden":j);b._setDimension();a.wrap.removeClass("fancybox-tmp");a.pos=f.extend({},a.dim,b._getPosition(!0));b.isOpen=!1;b.coming=null;b.bindEvents();if(b.isOpened){if(d.prevMethod)b.transitions[d.prevMethod]()}else f(".fancybox-wrap").not(a.wrap).stop(!0).trigger("onReset").remove();b.transitions[b.isOpened?a.nextMethod:a.openMethod]();b._preloadImages()}},_setDimension:function(){var a=b.getViewport(),d=0,e=!1,c=!1,e=b.wrap,j=b.skin,g=b.inner,h=
b.current,c=h.width,i=h.height,l=h.minWidth,u=h.minHeight,m=h.maxWidth,n=h.maxHeight,t=h.scrolling,r=h.scrollOutside?h.scrollbarWidth:0,x=h.margin,p=x[1]+x[3],q=x[0]+x[2],y,s,v,B,z,E,A,C,F;e.add(j).add(g).width("auto").height("auto");x=j.outerWidth(!0)-j.width();y=j.outerHeight(!0)-j.height();s=p+x;v=q+y;B=D(c)?(a.w-s)*k(c)/100:c;z=D(i)?(a.h-v)*k(i)/100:i;if("iframe"===h.type){if(F=h.content,h.autoHeight&&1===F.data("ready"))try{F[0].contentWindow.document.location&&(g.width(B).height(9999),E=F.contents().find("body"),
r&&E.css("overflow-x","hidden"),z=E.height())}catch(G){}}else if(h.autoWidth||h.autoHeight)g.addClass("fancybox-tmp"),h.autoWidth||g.width(B),h.autoHeight||g.height(z),h.autoWidth&&(B=g.width()),h.autoHeight&&(z=g.height()),g.removeClass("fancybox-tmp");c=k(B);i=k(z);C=B/z;l=k(D(l)?k(l,"w")-s:l);m=k(D(m)?k(m,"w")-s:m);u=k(D(u)?k(u,"h")-v:u);n=k(D(n)?k(n,"h")-v:n);E=m;A=n;p=a.w-p;q=a.h-q;h.aspectRatio?(c>m&&(c=m,i=c/C),i>n&&(i=n,c=i*C),c<l&&(c=l,i=c/C),i<u&&(i=u,c=i*C)):(c=Math.max(l,Math.min(c,m)),
i=Math.max(u,Math.min(i,n)));if(h.fitToView)if(m=Math.min(a.w-s,m),n=Math.min(a.h-v,n),g.width(k(c)).height(k(i)),e.width(k(c+x)),a=e.width(),s=e.height(),h.aspectRatio)for(;(a>p||s>q)&&(c>l&&i>u)&&!(19<d++);)i=Math.max(u,Math.min(n,i-10)),c=i*C,c<l&&(c=l,i=c/C),c>m&&(c=m,i=c/C),g.width(k(c)).height(k(i)),e.width(k(c+x)),a=e.width(),s=e.height();else c=Math.max(l,Math.min(c,c-(a-p))),i=Math.max(u,Math.min(i,i-(s-q)));r&&("auto"===t&&i<z&&c+x+r<p)&&(c+=r);g.width(k(c)).height(k(i));e.width(k(c+x));
a=e.width();s=e.height();e=(a>p||s>q)&&c>l&&i>u;c=h.aspectRatio?c<E&&i<A&&c<B&&i<z:(c<E||i<A)&&(c<B||i<z);f.extend(h,{dim:{width:w(a),height:w(s)},origWidth:B,origHeight:z,canShrink:e,canExpand:c,wPadding:x,hPadding:y,wrapSpace:s-j.outerHeight(!0),skinSpace:j.height()-i});!F&&(h.autoHeight&&i>u&&i<n&&!c)&&g.height("auto")},_getPosition:function(a){var d=b.current,e=b.getViewport(),c=d.margin,f=b.wrap.width()+c[1]+c[3],g=b.wrap.height()+c[0]+c[2],c={position:"absolute",top:c[0],left:c[3]};d.autoCenter&&
d.fixed&&!a&&g<=e.h&&f<=e.w?c.position="fixed":d.locked||(c.top+=e.y,c.left+=e.x);c.top=w(Math.max(c.top,c.top+(e.h-g)*d.topRatio));c.left=w(Math.max(c.left,c.left+(e.w-f)*d.leftRatio));return c},_afterZoomIn:function(){var a=b.current;a&&(b.isOpen=b.isOpened=!0,b.wrap.addClass("fancybox-opened").css("overflow","visible"),b.reposition(),(a.closeClick||a.nextClick)&&b.inner.css("cursor","pointer").bind("click.fb",function(d){if(!f(d.target).is("a")&&!f(d.target).parent().is("a"))b[a.closeClick?"close":
"next"]()}),a.closeBtn&&f(a.tpl.closeBtn).appendTo(b.skin).bind("click.fb",b.close),a.arrows&&1<b.group.length&&((a.loop||0<a.index)&&f(a.tpl.prev).appendTo(b.outer).bind("click.fb",b.prev),(a.loop||a.index<b.group.length-1)&&f(a.tpl.next).appendTo(b.outer).bind("click.fb",b.next)),b.trigger("afterShow"),!a.loop&&a.index===a.group.length-1?b.play(!1):b.opts.autoPlay&&!b.player.isActive&&(b.opts.autoPlay=!1,b.play()))},_afterZoomOut:function(){var a=b.current;f(".fancybox-wrap").stop(!0).trigger("onReset").remove();
f.extend(b,{group:{},opts:{},router:!1,current:null,isActive:!1,isOpened:!1,isOpen:!1,isClosing:!1,wrap:null,skin:null,outer:null,inner:null});b.trigger("afterClose",a)}});b.transitions={getOrigPosition:function(){var a=b.current,d=a.element,e=a.orig,c={},f=50,g=50,h=a.hPadding,i=a.wPadding,l=b.getViewport();!e&&(a.isDom&&d.is(":visible"))&&(e=d.find("img:first"),e.length||(e=d));y(e)?(c=e.offset(),e.is("img")&&(f=e.outerWidth(),g=e.outerHeight())):(c.top=l.y+(l.h-g)*a.topRatio,c.left=l.x+(l.w-f)*
a.leftRatio);a.locked&&(c.top-=l.y,c.left-=l.x);return c={top:w(c.top-h*a.topRatio),left:w(c.left-i*a.leftRatio),width:w(f+i),height:w(g+h)}},step:function(a,d){var e,c,f=d.prop;c=b.current;var g=c.wrapSpace,h=c.skinSpace;if("width"===f||"height"===f)e=d.end===d.start?1:(a-d.start)/(d.end-d.start),b.isClosing&&(e=1-e),c="width"===f?c.wPadding:c.hPadding,c=a-c,b.skin[f](k("width"===f?c:c-g*e)),b.inner[f](k("width"===f?c:c-g*e-h*e))},zoomIn:function(){var a=b.current,d=a.pos,e=a.openEffect,c="elastic"===
e,j=f.extend({opacity:1},d);delete j.position;c?(d=this.getOrigPosition(),a.openOpacity&&(d.opacity=0.1)):"fade"===e&&(d.opacity=0.1);b.wrap.css(d).animate(j,{duration:"none"===e?0:a.openSpeed,easing:a.openEasing,step:c?this.step:null,complete:b._afterZoomIn})},zoomOut:function(){var a=b.current,d=a.closeEffect,e="elastic"===d,c={opacity:0.1};e&&(c=this.getOrigPosition(),a.closeOpacity&&(c.opacity=0.1));b.wrap.animate(c,{duration:"none"===d?0:a.closeSpeed,easing:a.closeEasing,step:e?this.step:null,
complete:b._afterZoomOut})},changeIn:function(){var a=b.current,d=a.nextEffect,e=a.pos,c={opacity:1},f=b.direction,g;e.opacity=0.1;"elastic"===d&&(g="down"===f||"up"===f?"top":"left","down"===f||"right"===f?(e[g]=w(k(e[g])-200),c[g]="+=200px"):(e[g]=w(k(e[g])+200),c[g]="-=200px"));"none"===d?b._afterZoomIn():b.wrap.css(e).animate(c,{duration:a.nextSpeed,easing:a.nextEasing,complete:b._afterZoomIn})},changeOut:function(){var a=b.previous,d=a.prevEffect,e={opacity:0.1},c=b.direction;"elastic"===d&&
(e["down"===c||"up"===c?"top":"left"]=("up"===c||"left"===c?"-":"+")+"=200px");a.wrap.animate(e,{duration:"none"===d?0:a.prevSpeed,easing:a.prevEasing,complete:function(){f(this).trigger("onReset").remove()}})}};b.helpers.overlay={defaults:{closeClick:!0,speedOut:200,showEarly:!0,css:{},locked:!0},overlay:null,update:function(){var a="100%",b;this.overlay.width(a).height("100%");f.browser.msie?(b=Math.max(q.documentElement.offsetWidth,q.body.offsetWidth),n.width()>b&&(a=n.width())):n.width()>p.width()&&
(a=n.width());this.overlay.width(a).height(n.height())},onReady:function(a,b){f(".fancybox-overlay").stop(!0,!0);this.overlay||f.extend(this,{overlay:f('<div class="fancybox-overlay"></div>').appendTo(b.parent||"body"),margin:n.height()>p.height()||"scroll"===f("body").css("overflow-y")?f("body").css("margin-right"):!1,el:q.all&&!q.querySelector?f("html"):f("body")});b.fixed&&!m&&(this.overlay.addClass("fancybox-overlay-fixed"),b.autoCenter&&a.locked&&(b.locked=this.overlay.append(b.wrap)));!0===
a.showEarly&&this.beforeShow.apply(this,arguments)},beforeShow:function(a,d){var e=this.overlay.unbind(".fb").width("auto").height("auto").css(a.css);a.closeClick&&e.bind("click.fb",function(a){f(a.target).hasClass("fancybox-overlay")&&b.close()});d.fixed&&!m?d.locked&&(this.el.addClass("fancybox-lock"),!1!==this.margin&&f("body").css("margin-right",k(this.margin)+d.scrollbarWidth)):this.update();e.show()},onUpdate:function(a,b){(!b.fixed||m)&&this.update()},afterClose:function(a){var d=this,a=a.speedOut||
0;d.overlay&&!b.isActive&&d.overlay.fadeOut(a||0,function(){f("body").css("margin-right",d.margin);d.el.removeClass("fancybox-lock");d.overlay.remove();d.overlay=null})}};b.helpers.title={defaults:{type:"float",position:"bottom"},beforeShow:function(a){var d=b.current,e=d.title,c=a.type;f.isFunction(e)&&(e=e.call(d.element,d));if(t(e)&&""!==f.trim(e)){d=f('<div class="fancybox-title fancybox-title-'+c+'-wrap">'+e+"</div>");switch(c){case "inside":c=b.skin;break;case "outside":c=b.wrap;break;case "over":c=
b.inner;break;default:c=b.skin,d.appendTo("body"),f.browser.msie&&d.width(d.width()),d.wrapInner('<span class="child"></span>'),b.current.margin[2]+=Math.abs(k(d.css("margin-bottom")))}d["top"===a.position?"prependTo":"appendTo"](c)}}};f.fn.fancybox=function(a){var d,e=f(this),c=this.selector||"",j=function(g){var h=f(this).blur(),i=d,j,k;!g.ctrlKey&&(!g.altKey&&!g.shiftKey&&!g.metaKey)&&!h.is(".fancybox-wrap")&&(j=a.groupAttr||"data-fancybox-group",k=h.attr(j),k||(j="rel",k=h.get(0)[j]),k&&(""!==
k&&"nofollow"!==k)&&(h=c.length?f(c):e,h=h.filter("["+j+'="'+k+'"]'),i=h.index(this)),a.index=i,!1!==b.open(h,a)&&g.preventDefault())},a=a||{};d=a.index||0;!c||!1===a.live?e.unbind("click.fb-start").bind("click.fb-start",j):n.undelegate(c,"click.fb-start").delegate(c+":not('.fancybox-item, .fancybox-nav')","click.fb-start",j);return this};n.ready(function(){f.scrollbarWidth===r&&(f.scrollbarWidth=function(){var a=f('<div style="width:50px;height:50px;overflow:auto"><div/></div>').appendTo("body"),
b=a.children(),b=b.innerWidth()-b.height(99).innerWidth();a.remove();return b});if(f.support.fixedPosition===r){var a=f.support,d=f('<div style="position:fixed;top:20px;"></div>').appendTo("body"),e=20===d[0].offsetTop||15===d[0].offsetTop;d.remove();a.fixedPosition=e}f.extend(b.defaults,{scrollbarWidth:f.scrollbarWidth(),fixed:f.support.fixedPosition,parent:f("body")})})})(window,document,jQuery);
/**
 *
 * add js for the following module
 *
 * - anchorlisting
 * - berichterstattung
 * - bilfingergallery
 * - contactbutton
 * - inline_image
 * - storytelling
 * - tagcloudbutton
 * - publications
 * - metanavigation
 * - AccordionPresenter
 * - greyScale
 *
 * */
var syncTheFourthLevelHeightTimer;
var syncTheFourthLevelHeight;

(function ($) {

	syncTheFourthLevelHeight = function () {
		var state = $('#thefourthlevel').attr('data-sync-height') == 'true' ? true : false;
		if (state) {
			$(window).setTheFourthLevelHeight();
		} else {
			window.clearInterval(syncTheFourthLevelHeightTimer);
		}
	};

	$.fn.startSyncTheFourthLevelHeight = function () {
		$('#thefourthlevel').attr('data-sync-height', true);
		syncTheFourthLevelHeightTimer = window.setInterval('syncTheFourthLevelHeight()', 1);
	};

	$.fn.stopSyncTheFourthLevelHeight = function () {
		$('#thefourthlevel').attr('data-sync-height', false);
		$(window).setTheFourthLevelHeight();
	};

	function getURLParameter(name) {
		var part = decodeURI((RegExp(name + '=' + '(.+?)(&|$)').exec(location.search) || [, null])[1]);
		if (part && part != 'null') {
			return part;
		}
		return false;
	}

	$(function () {

		/*
		 * Imagemap
		 */
		$('img[usemap]').rwdImageMaps();

		/*
		 * email2powermail link
		 */

		$('.pm-mail-address').on('click', function (event) {
			event.preventDefault();
			if (!$(event.target).is('.pm-mail-address a')) {
				$(this).find("a.email2powermail").trigger('click');
			}
		});

		if ($('a.email2powermail').length > 0) {
			$('a.email2powermail').fancybox({
				afterClose: function () {
					if ($.browser.msie && parseInt($.browser.version) === 9) {
						window.location.reload(); // reload on fancybox close in ie9 because of a breakpoint bug
					}
				}
			});
		}


		/*
		 *
		 * anchorlisting
		 *
		 */

		$(".anchorlistinghead").nextUntil('p.anchorlistinghead').slideToggle('fast');
		// TG: for academy needed in postloaded ajax-calls => reparsing the dom necessary
		$(document).on('click', '.anchorlistinghead', function () {
			$(window).startSyncTheFourthLevelHeight();
			$(this).nextUntil('p.anchorlistinghead').slideToggle('fast', function () {
				$(window).stopSyncTheFourthLevelHeight();
			});
			$(this).toggleClass('listopen');
		});
		// Anchorlisting mit Downloads
		if ($('.anchorlisting_downloads').length > 0) {
			$('.anchorlisting_downloads').each(function () {
				if ($(this).next('.anchorlisting_downloads').length == 0) {
					$(this).addClass('last_anchorlisting_downloads');
				}
			});
		}
		$('.anchorlisting_downloads').find('.csc-header').click(function () {
			$(window).startSyncTheFourthLevelHeight();
			$(this).next('.tx-damfrontend-pi2').slideToggle('fast', function () {
				$(window).stopSyncTheFourthLevelHeight();
			});
			$(this).toggleClass('listopen');
		});


		/*
		 *
		 * berichterstattung
		 *
		 */

		$('.more').click(function () {
			$('.navi-bericht').toggleClass('height_auto');
		});

		$('.single-year').click(function () {
			var myself = $(this);
			var idString = myself.attr('id');
			var contentId = idString.split('-');
			$('.content-bericht').css('display', 'none');
			$('#content-' + contentId[1]).css('display', 'block');
			$('.single-year').css('color', 'black');
			$(this).css('color', '#008ad9');
		});

		if ($(".berichterstattung").length > 0 && getURLParameter('reportid')) {
			var reportId = getURLParameter('reportid');
			var myself = "div#id-" + reportId + ".single-year";
			var idString = $(myself).attr('id');
			var contentId = idString.split('-');
			$('.content-bericht').css('display', 'none');
			$('#content-' + contentId[1]).css('display', 'block');
			$('.single-year').css('color', 'black');
			$(myself).css('color', '#008ad9');
		}


		/*
		 *
		 * bilfingergallery
		 *
		 */

		$('.previewline_overlay').click(function () {
			$('.imagecontainer').find('a:first').trigger('click');
		});

		if ($('.fancybox').length > 0) {
			$(".fancybox").fancybox({
				padding: 10,
				minHeight: 50,
				openOpacity: false,
				beforeLoad: function () {
					var el, id = $(this.element).data('title-id');
					if (id) {
						el = $('#' + id);
						if (el.length) {
							this.title = el.html();
						}
					}
				},
				helpers: {
					title: { type: 'inside' }
				}
			});
		}


		/*
		 *
		 * inline_image
		 *
		 */

		if ($('body').width() >= 768) {
			$(".inlineimage img").click(function () {
				$this = $(this);
				$this.closest('.csc-textpic-image').find('.inline_image_icon').toggle(0);
				$this.stop(true, true).toggleClass("resize_image", 1000);
				$this.closest('.csc-textpic-image').toggleClass("wide_image", 0);
				$(window).startSyncTheFourthLevelHeight();
				$this.closest('.csc-textpic-image').find('.inlineimage-text').hide().toggleClass("resize_image_text", 1000).show('blind', function () {
					$(window).stopSyncTheFourthLevelHeight();
				});
			});

			$(".inlineimage .inline_image_icon").click(function () {
				$(this).next().click();
			})
		}


		/*
		 *
		 * storytelling
		 *
		 */

		$('.storytelling .csc-textpic-text').click(function () {
			var url = $(this).closest('.storytelling').find('img').parent('a').attr('href');
			var target = $(this).closest('.storytelling').find('img').parent('a').attr('target');
			if (url && url != undefined) {
				if (target == '_blank') {
					window.open(url, 'storytelling');
				} else if (target == '_top') {
					window.open(url, 'storytelling');
				} else {
					window.location = url;
				}
			}
		});

		$('.embeddedbutton').click(function (e) {
			var embeddedlink = $(this).siblings('.embeddedlink');
			embeddedlink.fadeToggle();
			embeddedlink.children('input').select();
		});

		$('.sharebuttons').click(function (e) {
			console.log('test');
			$(this).toggleClass('activesharebuttton');
			$(this).children('.shareslider').toggle();
			$(this).siblings('.sharebar_link').children('.bottomLinkElementPage').toggleClass('removedtext');
			$(this).siblings('.sharebar_link').children('.bottomLinkElementPage').find('span').toggle();
		});

		// stop all other link stuff
		$('.sharebar').click(function (e) {
			e.stopPropagation();
		});


		/*
		 *
		 * tagcloudbutton
		 *
		 */

		$('.tagcloudbutton').click(function () {
			$(this).toggleClass('active');
			$(this).next('.tagcloud').toggleClass('hideOnPhone').toggleClass('see_mobile');
			//$(this).parent().toggleClass('see_mobile');
			var offset = $(this).offset(); // get the margin from top
			$('html, body').animate({scrollTop: offset.top}, 800); // scroll down smoothly
		});


		/*
		 *
		 * publications
		 *
		 */
		$(function () {
			// Submit button
			$("#orderPublicationsBtn").click(
				function (e) {
					if (!$(this).hasClass('disabledSubmit')) {
						var selectedPublications = "";
						$("#publication-selection-list li").each(
							function () {
								if (!$(this).hasClass('exhausted_true')) {
									selectedPublications += $(this).find(".publication-name").html();
									selectedPublications += " " + $(this).find(".publication-language").html() + ",";
								}
							}
						);
					} else {
						e.preventDefault();
					}

					$("#selectedPublications").val(selectedPublications);
				}
			);

			// Publication menu
			$('#publication-categories a').click(
				function () {
					var clickedIndex = $(this).parent().index();

					$("#publication-categories .publication-category").each(
						function (index) {
							$(this).toggleClass("activepublication", clickedIndex == index);
						});
					$("#publication-lists .publication-list").each(
						function (index) {
							$(this).toggleClass("activepublication", clickedIndex == index);
						});

					return false;
				});

			// Publication selection
			$('#publication-lists .language input').change(
				function () {
					var publication = $(this).parents(".publication"),
						name = publication.find('.publication-title').html(),
						language = $(this).val(),
						url = $(this).attr('data-url'),
						publicationId = encodeURI(url),
						selected = $(this).prop("checked"),
						fileInfo = $(this).attr('data-file-info');

					var exhausted = false
					if ($(this).hasClass('exhausted')) {
						var exhausted = true;
					}

					if (selected)
						addPublication(name, language, url, fileInfo, exhausted, publicationId);
					else
						removePublication(publicationId);
				});

			function addPublication(name, language, url, fileInfo, exhausted, publicationId) {
				var template =
					"<div class='publication'>" +
						"<a class='icon-button remove' href='#' title='Entfernen'><span>Entfernen</span></a>" +
						"<div class='publication-label'>" +
						"<a class='publication-name' href='" + url + "' title='" + name + "'>" + name + "</a>" +
						"<span class='publication-language add-info'>[" + language + "]</span>" +
						"</div>" +
						"</div>" +
						"<div class='publication-download'>" +
						"<a class='download' href='" + url + "' title='" + name + "' target='_blank'>Download</a>" +
						"<span class='download-info add-info'>[" + fileInfo + "]</span>" +
						"</div>";

				$('#publication-selection-list').prepend(
					"<li data-publication='" + publicationId + "' class='exhausted_" + exhausted + "'>" + template + "</li>"
				);

				$("#publication-selection-list li[data-publication='" + publicationId + "'] .icon-button.remove").click(
					function () {
						var publicationId = $(this).parents("li").attr("data-publication");
						// Uncheck related input
						$("#publication-lists input[data-url='" + publicationId + "']").prop("checked", false);
						// Remove element from list
						removePublication(publicationId);

						return false;
					}
				);

				updateSelectionTitle();
				checkSubmitButton();
			}

			function removePublication(publicationId) {
				$("#publication-selection-list li[data-publication='" + publicationId + "']").remove();
				updateSelectionTitle();
				checkSubmitButton();
			}

			function updateSelectionTitle() {
				if ($("#publication-selection-list li").length > 0)
					$("#publication-selection h4").hide();
				else
					$("#publication-selection h4").show();
			}

			/*
			 function getURLParameter(name) {
			 var part = decodeURI((RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]);
			 if (part && part != 'null') {
			 return part;
			 }
			 return false;
			 }
			 */

			if ($("#publications").length > 0 && getURLParameter('tab')) {
				var puplication_hash = getURLParameter('tab');
				$("#publication-lists .activepublication").removeClass('activepublication');
				$("#publication-categories .activepublication").removeClass('activepublication');
				$("#publication-lists .publication-list").eq(puplication_hash).addClass('activepublication');
				$("#publication-categories .publication-category").eq(puplication_hash).addClass('activepublication');
			}

			// run onload
			checkSubmitButton();

			function checkSubmitButton() {
				// default: the submit-button is disabled
				$('#orderPublicationsBtn').addClass('disabledSubmit');

				// activate when a un-exhausted selection is found
				$('#publication-selection-list').children('li').each(function () {
					if ($(this).hasClass('exhausted_false')) {
						//activate
						$('#orderPublicationsBtn').removeClass('disabledSubmit');
					}
					else {
						// show info for exhausted selection
						if (!$(this).hasClass('exhaustedInfoAdded')) {
							$(this).find('.publication-label').append(' <span class="exhaustedInfo">(' + $('.localization_exhausted').val() + ')</span>');
							$(this).addClass('exhaustedInfoAdded');
						}
					}
				})
			}

		});

		/*
		 *
		 * metanavi
		 *
		 */

		$('.flyoutarrow').click(function () {

			if (!$('.metanaviopenmenu').hasClass('metaopen')) {
				$('body').append('<div id="metanavioverlay" class="metanavioverlay"></div>');
			}
			var thisp = $(this).parent();
			if ($(thisp).hasClass('metaopenact')) {
				$(thisp).removeClass('metaopen').removeClass('metaopenact');
				$('#metanavioverlay').remove();
				if ($('body').hasClass('breakpoint-480') || $('body').hasClass('breakpoint-320')) {
					$('.metanavigationwrap').removeClass('mobileflyoutopen');
				}
			} else {
				$('.metanaviopenmenu').removeClass('metaopen').removeClass('metaopenact');
				$(thisp).addClass('metaopen').addClass('metaopenact');
				if ($('body').hasClass('breakpoint-480') || $('body').hasClass('breakpoint-320')) {
					$('.metanavigationwrap').addClass('mobileflyoutopen');
					//$('head').append('<style type="text/css">.metanavigationwrap.mobileflyoutopen .metanavigationinner:before{ height: '+$('.metanavigation > li').outerHeight()+'px; }</style>');
				}
			}
		});

		$(document).on('click', '#metanavioverlay', function () {
			$(this).remove();
			$('.metanaviopenmenu').removeClass('metaopen').removeClass('metaopenact');
		});

		/*
		 *
		 * AccordionPresenter
		 *
		 */

		// set the AccordionPresenter

		//var accordionMaxLenght = 0;
		var accordionMaxLenght = new Array();
		accordionMaxLenght[1330] = 120;
		accordionMaxLenght[1323] = 120;
		accordionMaxLenght[1280] = 70;
		accordionMaxLenght[1024] = 70;
		accordionMaxLenght[768] = 45;

		$(document).ready(function () {
			$('.accordion_item img').wrap("<div class='img_wrapper'>");

			// Intitialize Accordion
			resetAccordionWidth($('.img_wrapper'), $('.accordion_item'));
			setAccordionPresenter($('.img_wrapper'), $('.accordion_item'));
			var size = getBreakpointSize();
			if (accordionMaxLenght[size]) {
				accordionCutText(accordionMaxLenght[size], '.accordion_item', '.contentpresenter_captionaddtext');
			}

			// IE8
			if ($.browser.msie && parseInt($.browser.version, 10) === 8) {
				setTimeout(function () {
					resetAccordionWidth($('.img_wrapper'), $('.accordion_item'));
					setAccordionPresenter($('.img_wrapper'), $('.accordion_item'));
					var size = getBreakpointSize();
					if (accordionMaxLenght[size]) {
						accordionCutText(accordionMaxLenght[size], '.accordion_item', '.contentpresenter_captionaddtext');
					}
				}, 1000);
			}
		});


		// set the AccordionPresenter on desktop at breakpoint
		$(window).bind('exitBreakpoint1330 enterBreakpoint1330 enterBreakpoint1323 exitBreakpoint1323 enterBreakpoint1280 exitBreakpoint1280 enterBreakpoint1024 exitBreakpoint1024 enterBreakpoint990 exitBreakpoint990 enterBreakpoint768', function () {
			resetAccordionWidth($('.img_wrapper'), $('.accordion_item'));
			setAccordionPresenter($('.img_wrapper'), $('.accordion_item'));
			var size = getBreakpointSize();
			if (accordionMaxLenght[size]) {
				accordionCutText(accordionMaxLenght[size], '.accordion_item', '.contentpresenter_captionaddtext');
			}
		});

		// set the AccordionPresenter on mobile
		$(document).on('click', '.contentpresenter_header', function () {
			$(window).startSyncTheFourthLevelHeight();
			$(this).nextUntil('div.contentpresenter_header').toggleClass('open_caption', function () {
				$(window).stopSyncTheFourthLevelHeight();
			});
			$(this).toggleClass('open_caption');
		});


		function getBreakpointSize() {
			var bodyClassString = $('body').attr('class');
			var bodyClasses = bodyClassString.split(' ');
			for (var i = 0; i < bodyClasses.length; i++) {
				if (bodyClasses[i].indexOf('breakpoint') !== -1) {
					return bodyClasses[i].substr(11);
				}
			}
		}

		function setAccordionPresenter(openobject, accItem) {
			$('.accordionPresenter').unbind();
			$('.accordionPresenter').AccordionImageMenu({
				'border': 1,
				'openItem': null,
				'duration': 400,
				'openDim': parseInt(openobject.css('width')),
				'closeDim': parseInt(accItem.css('width')),
				'effect': 'easeOutQuint',
				'height': parseInt(openobject.css('height')),
				'position': 'horizontal',
				'fadeInTitle': null
			});
		}

		function resetAccordionWidth(openobject, accItem) {
			$(openobject).css('width', '');
			$(accItem).css('width', '');
		};

		function accordionCutText(maxlength, item, shorttext) {
			$(item).each(function () {
				var shorttext = '';
				if ($(this).find('.accordionpresenter_orgtext').length < 1) {
					$(this).append('<div class="accordionpresenter_orgtext">' + $(this).find('.contentpresenter_captionaddtext').text() + '</div>');
				}

				var desc_length = $(this).find('.accordionpresenter_orgtext').text().length;
				var descIsSet_length = $(this).find('.contentpresenter_captionaddtext').text().length;
				var length = $(this).find('.contentpresenter_caption').text().length - descIsSet_length + desc_length;

				if (length > maxlength) {
					var shorttext = $(this).find('.accordionpresenter_orgtext').text().slice(0, maxlength) + '...';
					$(this).find('.contentpresenter_captionaddtext').text(shorttext);
				}
			});
		};

		/**
		 * Disable Language Selection on News Detail Page if Translation is not available
		 */
		if ($('.news-single-item').length) {
			if (
				$('.service-nav-right').find('.language-select').length ||
				$('#service-nav').find('.language-select').length
			) {
				$('.service-nav-right, #service-nav').find('.language-select').each(function () {
					disableLanguageElement($(this));
				});
			}
		}

		if ($('.downloadlist').length > 0) {
			$('.downloadlist li a').each(function () {
				var newcontent = $(this).html().replace(/\|/g, '<br />');
				$(this).html(newcontent);
			});
		}



		// GRI-I
		$(document).ready(function () {
            $('.titel_tabelle').unbind('click');
			$('.titel_tabelle').click(function () {
				$(window).startSyncTheFourthLevelHeight();
				$('.titel_tabelle').removeClass('active');
				$('.gri-table').slideUp('normal');
				if ($(this).next().is(':hidden') == true) {
					$(this).addClass('active');
					$(this).next().slideDown('normal', function(){
                        $('html,body').animate({
                            scrollTop:$('.titel_tabelle.active').offset().top+'px'
                        }, 500)
                    });
				}
			});
			$('.gri-table').hide();
		});

	});

	/**
	 * Disable a language Link
	 *
	 * @param element
	 * @return void
	 */
	function disableLanguageElement(element) {
		$.ajax({
			dataType: "json",
			url: (element.find('a').attr('href')),
			data: {'type': 1938},
			success: function (translation) {
				if (!translation.available) {
					$('.language-select').each(function () {
						if (element.find('a').attr('href').match(/\d+/) == translation.newsid) {
							element.find('a').fadeTo('fast', 0.6).css('cursor', 'default').attr('title', 'No translation available').on('click', function (e) {
								e.preventDefault();
							});
						}
					})
				}
				;
			}
		});
	}
})(jQuery);

/*
	Breakpoints.js
	version 1.0
	
	Creates handy events for your responsive design breakpoints
	
	Copyright 2011 XOXCO, Inc
	http://xoxco.com/

	Documentation for this plugin lives here:
	http://xoxco.com/projects/code/breakpoints
	
	Licensed under the MIT license:
	http://www.opensource.org/licenses/mit-license.php

	Modified by Alexander Grein in2code GmbH
	Add general triggers for entering and exiting a breakpoint

*/
(function($) {

	var lastSize = 0;
	var lastSizeV = 0;
	var interval = null;

	$.fn.resetBreakpoints = function() {
		$(window).unbind('resize');
		if (interval) {
			clearInterval(interval);
		}
		lastSize = 0;
		lastSizeV = 0;
	};
	
	$.fn.setBreakpoints = function(settings) {
		var options = jQuery.extend({
							distinct: true,
							breakpoints: new Array(320,480,768,1024),
							breakpointsV: new Array(200,768)
				    	},settings);


		interval = setInterval(function() {
	
			var w = $(window).width();
			var h = $(window).height();
			var done = false;
			
			for (var bp in options.breakpoints.sort(function(a,b) { return (b-a) })) {
			
				// fire onEnter when a browser expands into a new breakpoint
				// if in distinct mode, remove all other breakpoints first.
				if (!done && w >= options.breakpoints[bp] && lastSize < options.breakpoints[bp]) {
					if (options.distinct) {
						for (var x in options.breakpoints.sort(function(a,b) { return (b-a) })) {
							if ($('body').hasClass('breakpoint-' + options.breakpoints[x])) {
								$('body').removeClass('breakpoint-' + options.breakpoints[x]);
								$(window).trigger('exitBreakpoint' + options.breakpoints[x]);
								$(window).trigger('exitBreakpoint');
							}
						}
						done = true;
					}
					$('body').addClass('breakpoint-' + options.breakpoints[bp]);
					$(window).trigger('enterBreakpoint' + options.breakpoints[bp]);
					$(window).trigger('enterBreakpoint');
				}				

				// fire onExit when browser contracts out of a larger breakpoint
				if (w < options.breakpoints[bp] && lastSize >= options.breakpoints[bp]) {
					$('body').removeClass('breakpoint-' + options.breakpoints[bp]);
					$(window).trigger('exitBreakpoint' + options.breakpoints[bp]);
					$(window).trigger('exitBreakpoint');
				}
				
				// if in distinct mode, fire onEnter when browser contracts into a smaller breakpoint
				if (
					options.distinct && // only one breakpoint at a time
					w >= options.breakpoints[bp] && // and we are in this one
					w < options.breakpoints[bp-1] && // and smaller than the bigger one
					lastSize > w && // and we contracted
					lastSize >0 &&  // and this is not the first time
					!$('body').hasClass('breakpoint-' + options.breakpoints[bp]) // and we aren't already in this breakpoint
					) {					
					$('body').addClass('breakpoint-' + options.breakpoints[bp]);
					$(window).trigger('enterBreakpoint' + options.breakpoints[bp]);
					$(window).trigger('enterBreakpoint');
				}

			}
			
			// vertical
			var done = false;
			
			for (var bp in options.breakpointsV.sort(function(a,b) { return (b-a) })) {
			
				// fire onEnter when a browser expands into a new breakpoint
				// if in distinct mode, remove all other breakpoints first.
				if (!done && h >= options.breakpointsV[bp] && lastSizeV < options.breakpointsV[bp]) {
					if (options.distinct) {
						for (var y in options.breakpointsV.sort(function(a,b) { return (b-a) })) {
							if ($('body').hasClass('breakpointV-' + options.breakpointsV[y])) {
								$('body').removeClass('breakpointV-' + options.breakpointsV[y]);
								$(window).trigger('exitBreakpointV' + options.breakpointsV[y]);
								$(window).trigger('exitBreakpointV');
							}
						}
						done = true;
					}
					$('body').addClass('breakpointV-' + options.breakpointsV[bp]);
					$(window).trigger('enterBreakpointV' + options.breakpointsV[bp]);
					$(window).trigger('enterBreakpointV');
				}				

				// fire onExit when browser contracts out of a larger breakpoint
				if (h < options.breakpointsV[bp] && lastSizeV >= options.breakpointsV[bp]) {
					$('body').removeClass('breakpointV-' + options.breakpointsV[bp]);
					$(window).trigger('exitBreakpointV' + options.breakpointsV[bp]);
					$(window).trigger('exitBreakpointV');
				}

				// vertical: if in distinct mode, fire onEnter when browser contracts into a smaller breakpoint
				if (options.distinct && h >= options.breakpointsV[bp] && h < options.breakpointsV[bp-1] && lastSizeV > h && 	lastSizeV >0 &&  !$('body').hasClass('breakpointV-' + options.breakpointsV[bp]) ) {					
					$('body').addClass('breakpointV-' + options.breakpointsV[bp]);
					$(window).trigger('enterBreakpointV' + options.breakpointsV[bp]);
					$(window).trigger('enterBreakpointV');
				}	

			}

			// set up for next call
			if (lastSize != w) {
				lastSize = w;
			}
			if (lastSizeV != h) {
				lastSizeV = h;
			}

		},250);
	};
	
})(jQuery);

/**
* hoverIntent is similar to jQuery's built-in "hover" function except that
* instead of firing the onMouseOver event immediately, hoverIntent checks
* to see if the user's mouse has slowed down (beneath the sensitivity
* threshold) before firing the onMouseOver event.
* 
* hoverIntent r6 // 2011.02.26 // jQuery 1.5.1+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* hoverIntent is currently available for use in all personal or commercial 
* projects under both MIT and GPL licenses. This means that you can choose 
* the license that best suits your project, and use it accordingly.
* 
* // basic usage (just like .hover) receives onMouseOver and onMouseOut functions
* $("ul li").hoverIntent( showNav , hideNav );
* 
* // advanced usage receives configuration object only
* $("ul li").hoverIntent({
*	sensitivity: 7, // number = sensitivity threshold (must be 1 or higher)
*	interval: 100,   // number = milliseconds of polling interval
*	over: showNav,  // function = onMouseOver callback (required)
*	timeout: 0,   // number = milliseconds delay before onMouseOut function call
*	out: hideNav    // function = onMouseOut callback (required)
* });
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne brian(at)cherne(dot)net
*/
(function($) {
	$.fn.hoverIntent = function(f,g) {
		// default configuration options
		var cfg = {
			sensitivity: 7,
			interval: 50,
			timeout: 0
		};
		// override configuration options with user supplied object
		cfg = $.extend(cfg, g ? { over: f, out: g } : f );

		// instantiate variables
		// cX, cY = current X and Y position of mouse, updated by mousemove event
		// pX, pY = previous X and Y position of mouse, set by mouseover and polling interval
		var cX, cY, pX, pY;

		// A private function for getting mouse position
		var track = function(ev) {
			cX = ev.pageX;
			cY = ev.pageY;
		};

		// A private function for comparing current and previous mouse position
		var compare = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			// compare mouse positions to see if they've crossed the threshold
			if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) {
				$(ob).unbind("mousemove",track);
				// set hoverIntent state to true (so mouseOut can be called)
				ob.hoverIntent_s = 1;
				return cfg.over.apply(ob,[ev]);
			} else {
				// set previous coordinates for next time
				pX = cX; pY = cY;
				// use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
				ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval );
			}
		};

		// A private function for delaying the mouseOut function
		var delay = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			ob.hoverIntent_s = 0;
			return cfg.out.apply(ob,[ev]);
		};

		// A private function for handling mouse 'hovering'
		var handleHover = function(e) {
			// copy objects to be passed into t (required for event object to be passed in IE)
			var ev = jQuery.extend({},e);
			var ob = this;

			// cancel hoverIntent timer if it exists
			if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }

			// if e.type == "mouseenter"
			if (e.type == "mouseenter") {
				// set "previous" X and Y position based on initial entry point
				pX = ev.pageX; pY = ev.pageY;
				// update "current" X and Y position based on mousemove
				$(ob).bind("mousemove",track);
				// start polling interval (self-calling timeout) to compare mouse coordinates over time
				if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );}

			// else e.type == "mouseleave"
			} else {
				// unbind expensive mousemove event
				$(ob).unbind("mousemove",track);
				// if hoverIntent state is true, then call the mouseOut function after the specified delay
				if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );}
			}
		};

		// bind the function to the two event listeners
		return this.bind('mouseenter',handleHover).bind('mouseleave',handleHover);
	};
})(jQuery);
/**
 * jQuery Masonry v2.1.05
 * A dynamic layout plugin for jQuery
 * The flip-side of CSS Floats
 * http://masonry.desandro.com
 *
 * Licensed under the MIT license.
 * Copyright 2012 David DeSandro
 */
(function(a,b,c){"use strict";var d=b.event,e;d.special.smartresize={setup:function(){b(this).bind("resize",d.special.smartresize.handler)},teardown:function(){b(this).unbind("resize",d.special.smartresize.handler)},handler:function(a,c){var d=this,f=arguments;a.type="smartresize",e&&clearTimeout(e),e=setTimeout(function(){b.event.handle.apply(d,f)},c==="execAsap"?0:100)}},b.fn.smartresize=function(a){return a?this.bind("smartresize",a):this.trigger("smartresize",["execAsap"])},b.Mason=function(a,c){this.element=b(c),this._create(a),this._init()},b.Mason.settings={isResizable:!0,isAnimated:!1,animationOptions:{queue:!1,duration:500},gutterWidth:0,isRTL:!1,isFitWidth:!1,containerStyle:{position:"relative"}},b.Mason.prototype={_filterFindBricks:function(a){var b=this.options.itemSelector;return b?a.filter(b).add(a.find(b)):a},_getBricks:function(a){var b=this._filterFindBricks(a).css({position:"absolute"}).addClass("masonry-brick");return b},_create:function(c){this.options=b.extend(!0,{},b.Mason.settings,c),this.styleQueue=[];var d=this.element[0].style;this.originalStyle={height:d.height||""};var e=this.options.containerStyle;for(var f in e)this.originalStyle[f]=d[f]||"";this.element.css(e),this.horizontalDirection=this.options.isRTL?"right":"left",this.offset={x:parseInt(this.element.css("padding-"+this.horizontalDirection),10),y:parseInt(this.element.css("padding-top"),10)},this.isFluid=this.options.columnWidth&&typeof this.options.columnWidth=="function";var g=this;setTimeout(function(){g.element.addClass("masonry")},0),this.options.isResizable&&b(a).bind("smartresize.masonry",function(){g.resize()}),this.reloadItems()},_init:function(a){this._getColumns(),this._reLayout(a)},option:function(a,c){b.isPlainObject(a)&&(this.options=b.extend(!0,this.options,a))},layout:function(a,b){for(var c=0,d=a.length;c<d;c++)this._placeBrick(a[c]);var e={};e.height=Math.max.apply(Math,this.colYs);if(this.options.isFitWidth){var f=0;c=this.cols;while(--c){if(this.colYs[c]!==0)break;f++}e.width=(this.cols-f)*this.columnWidth-this.options.gutterWidth}this.styleQueue.push({$el:this.element,style:e});var g=this.isLaidOut?this.options.isAnimated?"animate":"css":"css",h=this.options.animationOptions,i;for(c=0,d=this.styleQueue.length;c<d;c++)i=this.styleQueue[c],i.$el[g](i.style,h);this.styleQueue=[],b&&b.call(a),this.isLaidOut=!0},_getColumns:function(){var a=this.options.isFitWidth?this.element.parent():this.element,b=a.width();this.columnWidth=this.isFluid?this.options.columnWidth(b):this.options.columnWidth||this.$bricks.outerWidth(!0)||b,this.columnWidth+=this.options.gutterWidth,this.cols=Math.floor((b+this.options.gutterWidth)/this.columnWidth),this.cols=Math.max(this.cols,1)},_placeBrick:function(a){var c=b(a),d,e,f,g,h;d=Math.ceil(c.outerWidth(!0)/this.columnWidth),d=Math.min(d,this.cols);if(d===1)f=this.colYs;else{e=this.cols+1-d,f=[];for(h=0;h<e;h++)g=this.colYs.slice(h,h+d),f[h]=Math.max.apply(Math,g)}var i=Math.min.apply(Math,f),j=0;for(var k=0,l=f.length;k<l;k++)if(f[k]===i){j=k;break}var m={top:i+this.offset.y};m[this.horizontalDirection]=this.columnWidth*j+this.offset.x,this.styleQueue.push({$el:c,style:m});var n=i+c.outerHeight(!0),o=this.cols+1-l;for(k=0;k<o;k++)this.colYs[j+k]=n},resize:function(){var a=this.cols;this._getColumns(),(this.isFluid||this.cols!==a)&&this._reLayout()},_reLayout:function(a){var b=this.cols;this.colYs=[];while(b--)this.colYs.push(0);this.layout(this.$bricks,a)},reloadItems:function(){this.$bricks=this._getBricks(this.element.children())},reload:function(a){this.reloadItems(),this._init(a)},appended:function(a,b,c){if(b){this._filterFindBricks(a).css({top:this.element.height()});var d=this;setTimeout(function(){d._appended(a,c)},1)}else this._appended(a,c)},_appended:function(a,b){var c=this._getBricks(a);this.$bricks=this.$bricks.add(c),this.layout(c,b)},remove:function(a){this.$bricks=this.$bricks.not(a),a.remove()},destroy:function(){this.$bricks.removeClass("masonry-brick").each(function(){this.style.position="",this.style.top="",this.style.left=""});var c=this.element[0].style;for(var d in this.originalStyle)c[d]=this.originalStyle[d];this.element.unbind(".masonry").removeClass("masonry").removeData("masonry"),b(a).unbind(".masonry")}},b.fn.imagesLoaded=function(a){function h(){a.call(c,d)}function i(a){var c=a.target;c.src!==f&&b.inArray(c,g)===-1&&(g.push(c),--e<=0&&(setTimeout(h),d.unbind(".imagesLoaded",i)))}var c=this,d=c.find("img").add(c.filter("img")),e=d.length,f="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==",g=[];return e||h(),d.bind("load.imagesLoaded error.imagesLoaded",i).each(function(){var a=this.src;this.src=f,this.src=a}),c};var f=function(b){a.console&&a.console.error(b)};b.fn.masonry=function(a){if(typeof a=="string"){var c=Array.prototype.slice.call(arguments,1);this.each(function(){var d=b.data(this,"masonry");if(!d){f("cannot call methods on masonry prior to initialization; attempted to call method '"+a+"'");return}if(!b.isFunction(d[a])||a.charAt(0)==="_"){f("no such method '"+a+"' for masonry instance");return}d[a].apply(d,c)})}else this.each(function(){var c=b.data(this,"masonry");c?(c.option(a||{}),c._init()):b.data(this,"masonry",new b.Mason(a,this))});return this}})(window,jQuery);
(function ($) {

	/**
	 * Minimal Height in px of Main Menu (will be set if content is smaller than this)
	 *
	 * @type {String}
	 */
	initialHeight = '180';

	/**
	 * Set or Reset Navigation Height
	 *
	 * @param    int            Height (if 0 - reset)
	 * @return    void
	 */
	function setNavHeight(height) {
		element = $('.notouch .main-nav > ul > li > a').next();
		if (height && height > initialHeight) {
			element.css('min-height', height + 'px');
		} else {
			element.css('min-height', initialHeight + 'px');
		}
	}

	/**
	 * Remove Extra Content if a subpage is active
	 *
	 * @return    void
	 */
	function initialExtraContent() {
		$('ul.nl2 > li.isActive').each(function () {
			if ($(this).hasClass('hassub')) {
				$(this).parent().next().addClass('hideExtraContent');
			}
		});
	}

	/**
	 * Remove element with a defined class
	 *
	 * @param string	classname classname of elements to be cleaned
	 * @param string	outerElement the element in which the elements with "classname" are (must be with leading "." or "#" !)
	 * @return void
	 */
	function cleanClass(classname, outerElement) {
		if (classname == undefined) {
			return;
		} else if (!outerElement || outerElement == undefined) {
			$('.' + classname).removeClass(classname);
		} else {
			$(outerElement).find('.' + classname).removeClass(classname);
		}
	}

	/**
	 * get max height of subnavigation
	 *
	 * @param        object        DOM element
	 * @return        int            max length
	 */
	function maxHeightOfTree(element) {
		var height = element.outerHeight(true);
		element.children().each(function () {
			var curHeight = maxHeightOfTree($(this));
			if (curHeight > height) {
				height = curHeight;
			}
		});
		return height;
	}

	function navigation() {
		var speed = 250; // in ms
		var minWidthNavigation = 768;

		/**
		 * LEVEL 1
		 */
		function level1(element) {
			var $this = element;




			// this part is only for desktop / tablett view
			if ($(window).width() >= minWidthNavigation) {
				initialExtraContent();
				cleanClass('hover');
				cleanClass('activepage', '.main-nav');
				$('.main-nav > ul > li > a').removeClass('active'); // remove class "active" from all menu tags
				$this.addClass('active');

				$('.nav-primary').css('z-index', 2); // clean z-index
				$('.main-nav .act').removeClass('act');
				$this.next().addClass('act').css('z-index', '50').fadeIn(speed);

				$('.nav-primary').not('.act').children('.nav-primary-wrap').hide(); // first hide all content divs
				$('.nav-primary').not('.act').delay(speed).fadeOut(speed, function () { // fade out white background
					$(this).children('.nav-primary-wrap').show(); // show content divs again when ready with fadeout
				});

				$this.parent().parent().find('li.subIsActive2').addClass('subIsActive');

				// read height
				var height = $this.next().find('.extra-content').height(); // get height of extra content
				if ($this.next().find('.nl2 > .isActive').length) {
					var height = maxHeightOfTree($this.next().find('.isActive').find('.nl3'));
				}
				setNavHeight(height);

				// reactivate third level if needed
				$('ul.nl3 > li.subIsActive2').addClass('subIsActive');
			} else {
				// add class "active" to current - this is necessary for all menu types (smartphone, tablett, desktop)
				$this.addClass('active');
			}

		}

		// mouseover event with delay for desktop computers
		$('.notouch .main-nav > ul > li > a').hoverIntent(function () {
				level1($(this));
	  		}, function () {
	  	});

		// clickevent for pads
		$('.touch .main-nav > ul > li > a').click(function (e) {
			// not yet open
			if (!$(this).hasClass('active')) {
				e.preventDefault();
				level1($(this));
				// already open
			}
		});

		/**
		 * LEVEL 2
		 */
		$('.notouch ul.nl2 > li > span > a').hoverIntent({
			sensitivity:10,
			interval:50,
			over:function () {
				if ($(window).width() >= minWidthNavigation) {
					var $this = $(this).parent().parent();
					if ($this.hasClass('hassub')) {
						cleanClass('hover');
						cleanClass('hideExtraContent');
						cleanClass('subIsActive', '.main-nav');
						$this.addClass('hover');
						$this.parent().next().addClass('hideExtraContent');

						// get height
						var height = maxHeightOfTree($this.find('.nl3'));
						setNavHeight(height);
					} else {
						$this.siblings('.subIsActive').removeClass('subIsActive');
						cleanClass('hideExtraContent');
						cleanClass('hover');
						$this.addClass('hover');
					}
				}
			},
			out:function () {
			}
		});

		// Borderclasses
		$('.notouch ul.nl2 > li > span > a').mouseenter(function () {
			$(this).parent().parent().prev().addClass('noBorder');
		});
		$('.notouch ul.nl2 > li > span > a').mouseleave(function () {
			$(this).parent().parent().prev().removeClass('noBorder');
		});
		// workaround for old android browsers - set height of wrapping ul
		if (isOldAndroidTablet()) {
			$('.touch ul.nl2').each(function () {
				$(this).css('min-height', '800px');
			});
		}


		/**
		 * LEVEL 3
		 */
		$('.notouch ul.nl3 > li').hoverIntent({
			sensitivity:10,
			interval:50,
			over:function () {
				$('ul.nl3 > li').removeClass('subIsActive');
				$(this).addClass('subIsActive');
			},
			out:function () {
			}
		});

		$('.notouch ul.nl3 > li > span > a').hoverIntent(function (e) {
			if ($(window).width() >= minWidthNavigation) {
				if (!$.browser.msie || ($.browser.msie && parseInt($.browser.version) > 8)) {
					e.stopPropagation();
				}

				$(this).parent().parent().siblings().removeClass('hover');
				$(this).parent().parent().addClass('hover');
			}
		}, function () {
		});

		// ipad show level 4
		if (!$('.touch .nl3 li.hassub').find('.openlevel').length) { // if .openlevel is not yet there
			$('.touch .nl3 li.hassub').prepend('<span class="openlevel">*</span>'); // add openlevel span tag
		}
		$('.touch .nl3 .openlevel, .touch .nl3 .closelevel').click(function () {
			$(this).parent().toggleClass('level-active');
			$(this).toggleClass('closelevel');
		});

		/**
		 * CLOSE : fade out all menus on leave
		 */
		$('.main-nav').mouseleave(function () {
			if ($(window).width() >= minWidthNavigation) {
				cleanClass('hover');
				cleanClass('hide');
				cleanClass('active', '.main-nav');
				$(this).find('.nav-primary').fadeOut(speed);
				$(this).find('li.isActive').addClass('activepage');
				setNavHeight(0);
			}
		});

	}

	function smartPhoneNav(state, speed) {
		if (state == 'open') {
			$('.main-nav').slideDown(speed);
			$('.smartphone-breadcrumb').hide();
			$('#smartphone-header-wrap').removeClass('closed');
			$('#smartphone-header-wrap').addClass('open');
		} else {
			$('.main-nav').slideUp(speed);
			$('.smartphone-breadcrumb').show();
			if ($('body').is('.breakpoint-320')) {
				$('html, body').animate({
					scrollTop:$('#smartphone-header-wrap').offset().top
				}, speed);
			}
			$('#smartphone-header-wrap').removeClass('open');
			$('#smartphone-header-wrap').addClass('closed');
		}
	}


	// On DOM Ready
	$(function () {

		navigation();

		$(window).bind('enterBreakpoint exitBreakpoint', function () {
			if ($('body').is('.breakpoint-320, .breakpoint-480')) {
				// Show Mobile Navigation (width < 768px)
				var width320 = $('body').is('.breakpoint-320');
				$('#smartphone-header-wrap').show();
				$('.nav-primary').css({'min-height':'0'});
				$('.main-nav').show();

				if ($('#smartphone-header-wrap').is('.open')) {
					$('ul li.activepage').next().removeClass('noBorderTop');
					if (width320) {
						$('ul.nl2 li:last-child').removeClass('noBorderBottom');
					}
					smartPhoneNav('open', 0);
					$('.sph-right').toggle(function () {
						smartPhoneNav('close', 500);
					}, function () {
						smartPhoneNav('open', 500);
					});
				} else {
					smartPhoneNav('close', 0);
					$('ul li.activepage').next().addClass('noBorderTop');
					if (width320) {
						$('ul.nl2 li:last-child').addClass('noBorderBottom');
					}
					$('.sph-right').toggle(function () {
						smartPhoneNav('open', 500);
					}, function () {
						smartPhoneNav('close', 500);
					});
				}

			} else {
				// Show Standard Navigation (width >= 768px)
				$('#smartphone-header-wrap').hide();
				$('.main-nav').show();
			}

			navigation();

		});

	});




	/**************************************
	 * Alternative Navigation in P04 Column
	 **************************************/
	$('.related-content-icon').click(function(e) {
		e.preventDefault();
	});

	$('.alternative_navigation').hoverIntent({
		sensitivity: 10,
		interval: 0,
		timeout: 500,
		over: function() {
			$(this).data('width', 270);
			$(this).addClass('alternative_navigation_open');
		},
		out: function() {
			closeAlternativeNavigation();
		}
	});

	$('.alternative_navigation_menu li').hoverIntent({
		sensitivity: 10,
		interval: 50,
		timeout: 500,
		over: function() {
			var $this = $(this);
			cleanClass('alternative_navigation_mouseover');
			$this.parent().children('li').children('ul').hide();
			$this.children('a').addClass('alternative_navigation_mouseover');
			if ($this.children('ul').length > 0) { // if there is a submenu
				$('.alternative_navigation').data('width', $('.alternative_navigation').data('width') + 270);
				$this.closest('.related-content').animate({
					width: $('.alternative_navigation').data('width')
				}, function () {
					openSubmenuInAlternativeNavigation($this.children('ul'));
				});
			}
		},
		out: function() {
			var $this = $(this);
			if ($this.children('ul').length > 0) {
				$('.alternative_navigation').data('width', $('.alternative_navigation').data('width') - 270);
				$this.closest('.related-content').animate({
					width: $('.alternative_navigation').data('width')
				}, function () {
					$this.children('ul').find('ul').hide();
					$this.children('ul').hide();
				});
			}
		}
	});

	$('.related-content-close').click(function() {
		closeAlternativeNavigation();
	});

	/**
	 * Close Alternative Navigation
	 */
	function closeAlternativeNavigation () {
		$('.alternative_navigation_menu ul').hide();
		$('.related-content-open').css('width', 'auto');
		$('.related-content').css('height', 'auto');
		cleanClass('alternative_navigation_open');
		cleanClass('alternative_navigation_mouseover');
	}

	/**
	 * Show submenu in alternative Navigation
	 *
	 * @param element
	 * @return void
	 */
	function openSubmenuInAlternativeNavigation(element) {
		element.show();
		if ((element.outerHeight(true) + 10) > $('.related-content').outerHeight(true)) {
			$('.related-content').css('height', element.outerHeight(true) + 'px');
		}
	}

	/**
	 * AJAX Menu
	 */
	if ($('#ajaxmenu').length && $('#ajaxmenu').data('ajaxnavid').length > 0) {
		var currentPageUid = $('body').data('pid');

		$.ajax({
			url: $('#ajaxmenu').data('ajaxnavid'),
			beforeSend: function() {
				$('#main-start').fadeTo('fast', 0.5);
			},
			success: function(html) {
				$('#main-start')
					.html('')
					.append(html)
					.fadeTo('fast', 1);
				navigation();
				if (isMobileNavigationActive()) {
					smartPhoneNav('close', 0);
				}
				setTimeout(function() {
					$('#ajaxmenu a[data-pid="' + currentPageUid + '"]')
						.parent().closest('li').addClass('isActive subIsActive subIsActive2 activepage')
						.parent().closest('li').addClass('isActive subIsActive subIsActive2 activepage')
						.parent().closest('li').addClass('isActive subIsActive subIsActive2 activepage')
						.parent().closest('li').addClass('isActive subIsActive subIsActive2 activepage');
				}, 200);
			},
			error: function() {
				if (window.console) {
					console.log('Error loading Ajax Menu');
				}
			}
		});

		/**
		 * Is mobile nav (read breakpoint size)
		 *
		 * @return bool
		 */
		function isMobileNavigationActive() {
			var bodyClasses = $('body').attr('class').split(' ');
			for (var i = 0; i < bodyClasses.length; i++) {
				if (bodyClasses[i].indexOf('breakpoint-') !== -1) {
					var breakpointClassParts = bodyClasses[i].split('-');
					if (breakpointClassParts[1] > 767) {
						return false;
					}
				}
			}
			if ($('#main-content').width() < 600) {
				return true;
			}
			return false;
		}
	}
	
})(jQuery);
/**
 * @author Jason Roy for CompareNetworks Inc.
 * Thanks to mikejbond for suggested udaptes
 *
 * Version 1.1
 * Copyright (c) 2009 CompareNetworks Inc.
 *
 * Licensed under the MIT license:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
(function($)
{

    // Private variables
    
    var _options = {};
    var _container = {};
    var _breadCrumbElements = {};
    var _autoIntervalArray = [];
	var _easingEquation;
    
    // Public functions
    
    jQuery.fn.jBreadCrumb = function(options)
    {
        _options = $.extend({}, $.fn.jBreadCrumb.defaults, options);
        
        return this.each(function()
        {
            _container = $(this);
            setupBreadCrumb();
        });
        
    };
    
    // Private functions
    
    function setupBreadCrumb()
    {
		//Check if easing plugin exists. If it doesn't, use "swing"
		if(typeof(jQuery.easing) == 'object')
		{
			_easingEquation = 'easeOutQuad'
		}
		else
		{
			_easingEquation = 'swing'
		}
    
        //The reference object containing all of the breadcrumb elements
        _breadCrumbElements = jQuery(_container).find('li');
        
        //Keep it from overflowing in ie6 & 7
        jQuery(_container).find('ul').wrap('<div style="overflow:hidden; position:relative;  width: ' + jQuery(_container).css("width") + ';"><div>');
        //Set an arbitrary width width to avoid float drop on the animation
        jQuery(_container).find('ul').width(5000);
        
        //If the breadcrumb contains nothing, don't do anything
        if (_breadCrumbElements.length > 0) 
        {
            jQuery(_breadCrumbElements[_breadCrumbElements.length - 1]).addClass('last');
            jQuery(_breadCrumbElements[0]).addClass('first');
            
            //If the breadcrumb object length is long enough, compress.
            
            if (_breadCrumbElements.length > _options.minimumCompressionElements) 
            {
                compressBreadCrumb();
            };
                    };
            };
    
    function compressBreadCrumb()
    {
    
        // Factor to determine if we should compress the element at all
        var finalElement = jQuery(_breadCrumbElements[_breadCrumbElements.length - 1]);
        
        
        // If the final element is really long, compress more elements
        if (jQuery(finalElement).width() > _options.maxFinalElementLength) 
        {
            if (_options.beginingElementsToLeaveOpen > 0) 
            {
                _options.beginingElementsToLeaveOpen--;
                
            }
            if (_options.endElementsToLeaveOpen > 0) 
            {
                _options.endElementsToLeaveOpen--;
            }
        }
        // If the final element is within the short and long range, compress to the default end elements and 1 less beginning elements
        if (jQuery(finalElement).width() < _options.maxFinalElementLength && jQuery(finalElement).width() > _options.minFinalElementLength) 
        {
            if (_options.beginingElementsToLeaveOpen > 0) 
            {
                _options.beginingElementsToLeaveOpen--;
                
            }
        }
        
        var itemsToRemove = _breadCrumbElements.length - 1 - _options.endElementsToLeaveOpen;
        
        // We compress only elements determined by the formula setting below
        
        //TODO : Make this smarter, it's only checking the final elements length.  It could also check the amount of elements.
        jQuery(_breadCrumbElements[_breadCrumbElements.length - 1]).css(
        {
            background: 'none'
        });
        
        $(_breadCrumbElements).each(function(i, listElement)
        {
            if (i > _options.beginingElementsToLeaveOpen && i < itemsToRemove) 
            {
            
                jQuery(listElement).find('a').wrap('<span></span>').width(jQuery(listElement).find('a').width() + 10);
                
                // Add the overlay png.
                jQuery(listElement).append(jQuery('<div class="' + _options.overlayClass + '"></div>').css(
                {
                    display: 'block'
                })).css(
                {
                    background: 'none'
                });
                if (isIE6OrLess()) 
                {
                    fixPNG(jQuery(listElement).find('.' + _options.overlayClass).css(
                    {
                        width: '20px',
                        right: "-1px"
                    }));
                }
                var options = 
                {
                    id: i,
                    width: jQuery(listElement).width(),
                    listElement: jQuery(listElement).find('span'),
                    isAnimating: false,
                    element: jQuery(listElement).find('span')
                
                };
                jQuery(listElement).bind('mouseover', options, expandBreadCrumb).bind('mouseout', options, shrinkBreadCrumb);
                jQuery(listElement).find('a').unbind('mouseover', expandBreadCrumb).unbind('mouseout', shrinkBreadCrumb);
                listElement.autoInterval = setInterval(function()
                {
                    clearInterval(listElement.autoInterval);
                    jQuery(listElement).find('span').animate(
                    {
                        width: _options.previewWidth
                    }, _options.timeInitialCollapse, _options.easing);
                }, (150 * (i - 2)));
                
            }
        });
        
    };
    
    function expandBreadCrumb(e)
    {
        var elementID = e.data.id;
        var originalWidth = e.data.width;
        jQuery(e.data.element).stop();
        jQuery(e.data.element).animate(
        {
            width: originalWidth
        }, 
        {
            duration: _options.timeExpansionAnimation,
            easing: _options.easing,
            queue: false
        });
        return false;
        
    };
    
    function shrinkBreadCrumb(e)
    {
        var elementID = e.data.id;
        jQuery(e.data.element).stop();
        jQuery(e.data.element).animate(
        {
            width: _options.previewWidth
        }, 
        {
            duration: _options.timeCompressionAnimation,
            easing: _options.easing,
            queue: false
        });
        return false;
    };
    
    function isIE6OrLess()
    {
        var isIE6 = $.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent);
        return isIE6;
    };
    // Fix The Overlay for IE6
    function fixPNG(element)
    {
        var image;
        if (jQuery(element).is('img')) 
        {
            image = jQuery(element).attr('src');
        }
        else 
        {
            image = $(element).css('backgroundImage');
            image.match(/^url\(["']?(.*\.png)["']?\)$/i);
            image = RegExp.$1;
            ;
        }
        $(element).css(
        {
            'backgroundImage': 'none',
            'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=scale, src='" + image + "')"
        });
    };
    
    // Public global variables
    
    jQuery.fn.jBreadCrumb.defaults = 
    {
        maxFinalElementLength: 400,
        minFinalElementLength: 200,
        minimumCompressionElements: 4,
        endElementsToLeaveOpen: 1,
        beginingElementsToLeaveOpen: 0,
        timeExpansionAnimation: 800,
        timeCompressionAnimation: 500,
        timeInitialCollapse: 600,
        easing: _easingEquation,
        overlayClass: 'chevronOverlay',
        previewWidth: 20
    };
    
})(jQuery);
(function ($) {
    var wasScrolled = 0;
    $(function () {
        if ($('#banner').length > 0 && typeof FullscreenrOptions != 'undefined') {
            $.fn.fullscreenr(FullscreenrOptions);
        }
    });
})(jQuery);

/**
 * modified Fullscreenr  - original  By Jan Schneiders www.nanotux.com
 */


(function ($) {

    jQuery.fn.trackScroll = function (pageid) {
        jQuery.fn.buehneScrolledIds +='+' + parseInt(pageid);
        $.cookie('buehneCookie', jQuery.fn.buehneScrolledIds, { expires: 7, path: '/' });
    }

    $.fn.goToByScroll= function (id, diff) {
        diff = diff ? diff : 0;
        jQuery.wasScrolled++;
        if (id == 'magazin-start') {id = 'main-start'; diff = -327;}
        if (!$("#" + id).length) {id = 'top';}
        if (id == 'top') {id = 'main-start'; diff = -187;}
        $("html,body").animate({
            scrollTop:($("#" + id).offset().top + parseInt(diff))
        }, "slow");

        // if($('body').hasClass('rebranded')){
        //     $(".metanavigation").animate({
        //         top:($("#" + id).offset().top + parseInt(diff)),
        //         right: 0
        //     }, "slow");
        // }
        return false;
    }


    $.fn.setupBuehne = function (options) {

        // ticket #6262 cookie check
        jQuery.fn.buehneScrolledIds = $.cookie('buehneCookie');
        if (jQuery.fn.buehneScrolledIds == null) { // cookie neu setzen
            jQuery.fn.buehneScrolledIds=0; 	$.cookie('buehneCookie', jQuery.fn.buehneScrolledIds, { expires: 7, path: '/' });
        }
        else {
            ids=jQuery.fn.buehneScrolledIds; ids=ids.split('+');
            if (jQuery.inArray(options.pageid+'',ids)>-1) { // prüfen ob aktuelle id im cookie war

                if ( ($('#header-stage').hasClass('headerformat-4') || $('#header-stage').hasClass('headerformat-7') || $('#header-stage').hasClass('headerformat-11') ) && $('#header-stage').height() >= 200) {
                    diff = $('#header-stage').hasClass('layout-110') ? 327 : 187;
                    $(window).scrollTop(buehneHeight - diff);
                    // if($('body').hasClass('rebranded')){
                    //     $('.metanavigation').css({top:(buehneHeight - diff),right:0});
                    // }
                }
            }
        }

        $('#logo-wrap').css('position', 'fixed');
        jQuery.fn.fixLogo(options, 1);

        // bühne scrollToNav Button
        $('#scrolltonav').click(function (event) {
            event.preventDefault();
            console.log(event);
            diff=-190;

            if ($(this).hasClass('layout-110')) {diff=-330;}
            jQuery.fn.goToByScroll('main-start', diff);
            jQuery.fn.trackScroll(options.pageid);
        });

        // bei ankerlink in Bühne-Button scrollen
        $("#header-stage .scrollDown").each(function () {
            $(this).click(function (event) {
                event.preventDefault();
                elmId = 'top';
                if ($(this).attr('href') && $(this).attr('href').indexOf('#') >= 0) {
                    elmId = $(this).attr('href').split('#')[1];
                }
                jQuery.fn.goToByScroll(elmId, 0)
            });
        });
        // scrollToTop links im Text finden
        $("#content-wrap a[href*='#top'],#content-wrap a[href*='#page-wrap'], .scrollToTop").each(function () {
            $(this).click(function (event) {
                event.preventDefault();
                jQuery.fn.goToByScroll('page-wrap', 0)
            });
        });

    }
    $.fn.positionLogo = function (init) {
        h = $('#header-stage').height() - 110;

        //$('.headerBody').append('<br>'+h+';  '+$(window).height() + '-' + 66 +'-'+ 110 + '='+ end);
        if (init) {
            $('#logo-wrap').css('top', h);
        }
        else {
            $('#logo-wrap').animate({top:h}, 'slow');
        }

    }

    $.fn.fixLogo = function (options, init) {
        buehneHeight = $('#header-stage').height(); //$(window).height() - options.navHeight;
        scrl = $(window).scrollTop();
        limit = buehneHeight - (options.logoHeight + options.navHeight) * 2;
        if ((scrl >= limit && $('#logo-wrap').css('position') == 'fixed' ) || init) {
            start = parseInt(options.logoTop) + scrl;
            end = buehneHeight - options.logoHeight;

            if (scrl) {
                $('#logo-wrap').css('position', 'absolute');
                $('#logo-wrap').css('top', start);
                jQuery.fn.positionLogo(init);
            }
        }
    }

    $.fn.fullscreenr = function (options) {
        if (options.height === undefined) alert('Please supply the background image height, default values will now be used. These may be very inaccurate.');
        if (options.width === undefined) alert('Please supply the background image width, default values will now be used. These may be very inaccurate.');
        if (options.bgID === undefined) alert('Please supply the background image ID, default #bgimg will now be used.');
        var defaults = { width:1280, height:330, bgID:'bgimg' };
        var options = $.extend({}, defaults, options);

        $(document).ready(function () {
            // Header rotation
            if ($('.headerElm').length > 1)jQuery('#banner').cycle({
                fx:'fade'
            });

            options.navHeight = 66 // $('.main-nav li').height();
            options.logoHeight = 110;// $('#main-logo').height();
            options.logoTop = $('#logo-wrap').css('top');
            navHeight = $('.main-nav li').height();
            buehneHeight = $(window).height() - navHeight;


            if (options.buehne) {
                $('#header-stage.buehne').css('height', buehneHeight);
                $('#header-stage.buehne .headerC').css('height', buehneHeight);

                if ($('#header-stage').height() >= 200) {
                    if ($('#header-stage').hasClass('headerformat-6') || $('#header-stage').hasClass('headerformat-8')) { // herunterscrollen bei "versteckter bühne" ausser wenn pad oder kleiner -  da keine bühne mehr...
                        $(window).scrollTop(buehneHeight - 187);
                    }
                    if (location.hash.replace('#', '') == 'magazin-start') {$(window).scrollTop(buehneHeight - 330);}
                }
                jQuery.fn.setupBuehne(options);
                $(window).bind("scroll", function () {
                    jQuery.fn.fixLogo(options, 0);
                    jQuery.wasScrolled++;
                });

            }


            for (c = 1; c <= options.count; c++) {
                id = options.bgID + c;
                $(id).fullscreenrResizer(options, c);
            }
        });

        $(window).bind("resize", function () {
            for (c = 1; c <= options.count; c++) {
                id = options.bgID + c;
                $(id).fullscreenrResizer(options, c);
            }
        });

        return this;
    };
    $.fn.fullscreenrResizer = function (options, c) {

        //multi img - load real size from imginfo
        height = options.imgInfo[c]['h'];
        width = options.imgInfo[c]['w'];

        options.minHeight = $('#header-stage').height();
        options.setHeight = options.minHeight < 330 ? 0 : options.setHeight;  //keine bühne bei verkleinerten headern

        // Set bg size
        var ratio = height / width;

        // Get browser window size
        var browserwidth = $(window).width();
        var browserheight = $(window).height();

        buehneHeight = browserheight - options.navHeight;

        if (options.buehne && $('#logo-wrap').css('position') == 'absolute') {
            $('#logo-wrap').css('top', buehneHeight - options.logoHeight);
        }
        // Scale the image
        $('#header-stage.buehne').css('height', buehneHeight);
        $('#header-stage.buehne .headerC').css('height', buehneHeight);


        if ((browserheight / browserwidth) > ratio && options.setHeight > 0) {
            $(this).height(browserheight);
            newImgWidth = (browserheight / ratio);
            $(this).width(newImgWidth);
        } else {
            if (options.minHeight > 0) {
                if (browserwidth * ratio >= options.minHeight) {
                    newHeight = browserwidth * ratio;
                    newImgWidth=browserwidth;
                    $(this).width(newImgWidth);
                    $(this).height(newHeight);
                    $(this).css('margin-top', (newHeight - options.minHeight) / -2);
                }
                else {
                    mRatio = options.minHeight / height;
                    $(this).height(options.minHeight);
                    newImgWidth=(mRatio * width);
                    $(this).width(newImgWidth);
                    $(this).css('margin-top', 0);
                }
            }
            else {
                newImgWidth=browserwidth;
                $(this).width(newImgWidth);
                $(this).height(browserwidth * ratio);
            }
        }
        // Center the image
        // wg http://code.in2code.de/issues/5523#note-9 - nur wenn nicht Instanz internet, oder eine bühne vorliegt
        if ($('#header-stage').hasClass('buehne') || !$('#header-stage').hasClass('internet')) {

            ml =  (browserwidth - newImgWidth) / 2;
            (this).css('margin-left', ml);

        }

        //$(this).css('top', (browserheight - $(this).height())/2);
        return this;
    };
})(jQuery);

/*!
 * jQuery Cookie Plugin v1.3
 * https://github.com/carhartl/jquery-cookie
 *
 * Copyright 2011, Klaus Hartl
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.opensource.org/licenses/GPL-2.0
 */
(function ($, document, undefined) {

    var pluses = /\+/g;

    function raw(s) {
        return s;
    }

    function decoded(s) {
        return decodeURIComponent(s.replace(pluses, ' '));
    }

    var config = $.cookie = function (key, value, options) {

        // write
        if (value !== undefined) {
            options = $.extend({}, config.defaults, options);

            if (value === null) {
                options.expires = -1;
            }

            if (typeof options.expires === 'number') {
                var days = options.expires, t = options.expires = new Date();
                t.setDate(t.getDate() + days);
            }

            value = config.json ? JSON.stringify(value) : String(value);

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

        // read
        var decode = config.raw ? raw : decoded;
        var cookies = document.cookie.split('; ');
        for (var i = 0, l = cookies.length; i < l; i++) {
            var parts = cookies[i].split('=');
            if (decode(parts.shift()) === key) {
                var cookie = decode(parts.join('='));
                return config.json ? JSON.parse(cookie) : cookie;
            }
        }

        return null;
    };

    config.defaults = {};

    $.removeCookie = function (key, options) {
        if ($.cookie(key) !== null) {
            $.cookie(key, null, options);
            return true;
        }
        return false;
    };

})(jQuery, document);
/*!
 * jQuery Cycle Plugin (with Transition Definitions)
 * Examples and documentation at: http://jquery.malsup.com/cycle/
 * Copyright (c) 2007-2013 M. Alsup
 * Version: 3.0.2 (19-APR-2013)
 * Dual licensed under the MIT and GPL licenses.
 * http://jquery.malsup.com/license.html
 * Requires: jQuery v1.7.1 or later
 */
;
(function ($, undefined) {
	"use strict";

	var ver = '3.0.2';

	function debug(s) {
		if ($.fn.cycle.debug)
			log(s);
	}

	function log() {
		if (window.console && console.log)
			console.log('[cycle] ' + Array.prototype.join.call(arguments, ' '));
	}

	$.expr[':'].paused = function (el) {
		return el.cyclePause;
	};


	// the options arg can be...
	//   a number  - indicates an immediate transition should occur to the given slide index
	//   a string  - 'pause', 'resume', 'toggle', 'next', 'prev', 'stop', 'destroy' or the name of a transition effect (ie, 'fade', 'zoom', etc)
	//   an object - properties to control the slideshow
	//
	// the arg2 arg can be...
	//   the name of an fx (only used in conjunction with a numeric value for 'options')
	//   the value true (only used in first arg == 'resume') and indicates
	//	 that the resume should occur immediately (not wait for next timeout)

	$.fn.cycle = function (options, arg2) {
		var o = { s: this.selector, c: this.context };

		// in 1.3+ we can fix mistakes with the ready state
		if (this.length === 0 && options != 'stop') {
			if (!$.isReady && o.s) {
				log('DOM not ready, queuing slideshow');
				$(function () {
					$(o.s, o.c).cycle(options, arg2);
				});
				return this;
			}
			// is your DOM ready?  http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
			log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)'));
			return this;
		}

		// iterate the matched nodeset
		return this.each(function () {
			var opts = handleArguments(this, options, arg2);
			if (opts === false)
				return;

			opts.updateActivePagerLink = opts.updateActivePagerLink || $.fn.cycle.updateActivePagerLink;

			// stop existing slideshow for this container (if there is one)
			if (this.cycleTimeout)
				clearTimeout(this.cycleTimeout);
			this.cycleTimeout = this.cyclePause = 0;
			this.cycleStop = 0; // issue #108

			var $cont = $(this);
			var $slides = opts.slideExpr ? $(opts.slideExpr, this) : $cont.children();
			var els = $slides.get();

			if (els.length < 2) {
				log('terminating; too few slides: ' + els.length);
				return;
			}

			var opts2 = buildOptions($cont, $slides, els, opts, o);
			if (opts2 === false)
				return;

			var startTime = opts2.continuous ? 10 : getTimeout(els[opts2.currSlide], els[opts2.nextSlide], opts2, !opts2.backwards);

			// if it's an auto slideshow, kick it off
			if (startTime) {
				startTime += (opts2.delay || 0);
				if (startTime < 10)
					startTime = 10;
				debug('first timeout: ' + startTime);
				this.cycleTimeout = setTimeout(function () {
					go(els, opts2, 0, !opts.backwards);
				}, startTime);
			}
		});
	};

	function triggerPause(cont, byHover, onPager) {
		var opts = $(cont).data('cycle.opts');
		if (!opts)
			return;
		var paused = !!cont.cyclePause;
		if (paused && opts.paused)
			opts.paused(cont, opts, byHover, onPager);
		else
			if (!paused && opts.resumed)
				opts.resumed(cont, opts, byHover, onPager);
	}

	// process the args that were passed to the plugin fn
	function handleArguments(cont, options, arg2) {
		if (cont.cycleStop === undefined)
			cont.cycleStop = 0;
		if (options === undefined || options === null)
			options = {};
		if (options.constructor == String) {
			switch (options) {
				case 'destroy':
				case 'stop':
					var opts = $(cont).data('cycle.opts');
					if (!opts)
						return false;
					cont.cycleStop++; // callbacks look for change
					if (cont.cycleTimeout)
						clearTimeout(cont.cycleTimeout);
					cont.cycleTimeout = 0;
					if (opts.elements)
						$(opts.elements).stop();
					$(cont).removeData('cycle.opts');
					if (options == 'destroy')
						destroy(cont, opts);
					return false;
				case 'toggle':
					cont.cyclePause = (cont.cyclePause === 1) ? 0 : 1;
					checkInstantResume(cont.cyclePause, arg2, cont);
					triggerPause(cont);
					return false;
				case 'pause':
					cont.cyclePause = 1;
					triggerPause(cont);
					return false;
				case 'resume':
					cont.cyclePause = 0;
					checkInstantResume(false, arg2, cont);
					triggerPause(cont);
					return false;
				case 'prev':
				case 'next':
					opts = $(cont).data('cycle.opts');
					if (!opts) {
						log('options not found, "prev/next" ignored');
						return false;
					}
					if (typeof arg2 == 'string')
						opts.oneTimeFx = arg2;
					$.fn.cycle[options](opts);
					return false;
				default:
					options = { fx: options };
			}
			return options;
		}
		else
			if (options.constructor == Number) {
				// go to the requested slide
				var num = options;
				options = $(cont).data('cycle.opts');
				if (!options) {
					log('options not found, can not advance slide');
					return false;
				}
				if (num < 0 || num >= options.elements.length) {
					log('invalid slide index: ' + num);
					return false;
				}
				options.nextSlide = num;
				if (cont.cycleTimeout) {
					clearTimeout(cont.cycleTimeout);
					cont.cycleTimeout = 0;
				}
				if (typeof arg2 == 'string')
					options.oneTimeFx = arg2;
				go(options.elements, options, 1, num >= options.currSlide);
				return false;
			}
		return options;

		function checkInstantResume(isPaused, arg2, cont) {
			if (!isPaused && arg2 === true) { // resume now!
				var options = $(cont).data('cycle.opts');
				if (!options) {
					log('options not found, can not resume');
					return false;
				}
				if (cont.cycleTimeout) {
					clearTimeout(cont.cycleTimeout);
					cont.cycleTimeout = 0;
				}
				go(options.elements, options, 1, !options.backwards);
			}
		}
	}

	function removeFilter(el, opts) {
		if (!$.support.opacity && opts.cleartype && el.style.filter) {
			try {
				el.style.removeAttribute('filter');
			}
			catch (smother) {
			} // handle old opera versions
		}
	}

	// unbind event handlers
	function destroy(cont, opts) {
		if (opts.next)
			$(opts.next).unbind(opts.prevNextEvent);
		if (opts.prev)
			$(opts.prev).unbind(opts.prevNextEvent);

		if (opts.pager || opts.pagerAnchorBuilder)
			$.each(opts.pagerAnchors || [], function () {
				this.unbind().remove();
			});
		opts.pagerAnchors = null;
		$(cont).unbind('mouseenter.cycle mouseleave.cycle');
		if (opts.destroy) // callback
			opts.destroy(opts);
	}

	// one-time initialization
	function buildOptions($cont, $slides, els, options, o) {
		var startingSlideSpecified;
		// support metadata plugin (v1.0 and v2.0)
		var opts = $.extend({}, $.fn.cycle.defaults, options || {}, $.metadata ? $cont.metadata() : $.meta ? $cont.data() : {});
		var meta = $.isFunction($cont.data) ? $cont.data(opts.metaAttr) : null;
		if (meta)
			opts = $.extend(opts, meta);
		if (opts.autostop)
			opts.countdown = opts.autostopCount || els.length;

		var cont = $cont[0];
		$cont.data('cycle.opts', opts);
		opts.$cont = $cont;
		opts.stopCount = cont.cycleStop;
		opts.elements = els;
		opts.before = opts.before ? [opts.before] : [];
		opts.after = opts.after ? [opts.after] : [];

		// push some after callbacks
		if (!$.support.opacity && opts.cleartype)
			opts.after.push(function () {
				removeFilter(this, opts);
			});
		if (opts.continuous)
			opts.after.push(function () {
				go(els, opts, 0, !opts.backwards);
			});

		saveOriginalOpts(opts);

		// clearType corrections
		if (!$.support.opacity && opts.cleartype && !opts.cleartypeNoBg)
			clearTypeFix($slides);

		// container requires non-static position so that slides can be position within
		if ($cont.css('position') == 'static')
			$cont.css('position', 'relative');
		if (opts.width)
			$cont.width(opts.width);
		if (opts.height && opts.height != 'auto')
			$cont.height(opts.height);

		if (opts.startingSlide !== undefined) {
			opts.startingSlide = parseInt(opts.startingSlide, 10);
			if (opts.startingSlide >= els.length || opts.startSlide < 0)
				opts.startingSlide = 0; // catch bogus input
			else
				startingSlideSpecified = true;
		}
		else
			if (opts.backwards)
				opts.startingSlide = els.length - 1;
			else
				opts.startingSlide = 0;

		// if random, mix up the slide array
		if (opts.random) {
			opts.randomMap = [];
			for (var i = 0; i < els.length; i++)
				opts.randomMap.push(i);
			opts.randomMap.sort(function (a, b) {
				return Math.random() - 0.5;
			});
			if (startingSlideSpecified) {
				// try to find the specified starting slide and if found set start slide index in the map accordingly
				for (var cnt = 0; cnt < els.length; cnt++) {
					if (opts.startingSlide == opts.randomMap[cnt]) {
						opts.randomIndex = cnt;
					}
				}
			}
			else {
				opts.randomIndex = 1;
				opts.startingSlide = opts.randomMap[1];
			}
		}
		else
			if (opts.startingSlide >= els.length)
				opts.startingSlide = 0; // catch bogus input
		opts.currSlide = opts.startingSlide || 0;
		var first = opts.startingSlide;

		// set position and zIndex on all the slides
		$slides.css({position: 'absolute', top: 0, left: 0}).hide().each(function (i) {
			var z;
			if (opts.backwards)
				z = first ? i <= first ? els.length + (i - first) : first - i : els.length - i;
			else
				z = first ? i >= first ? els.length - (i - first) : first - i : els.length - i;
			$(this).css('z-index', z);
		});

		// make sure first slide is visible
		$(els[first]).css('opacity', 1).show(); // opacity bit needed to handle restart use case
		removeFilter(els[first], opts);

		// stretch slides
		if (opts.fit) {
			if (!opts.aspect) {
				if (opts.width)
					$slides.width(opts.width);
				if (opts.height && opts.height != 'auto')
					$slides.height(opts.height);
			} else {
				$slides.each(function () {
					var $slide = $(this);
					var ratio = (opts.aspect === true) ? $slide.width() / $slide.height() : opts.aspect;
					if (opts.width && $slide.width() != opts.width) {
						$slide.width(opts.width);
						$slide.height(opts.width / ratio);
					}

					if (opts.height && $slide.height() < opts.height) {
						$slide.height(opts.height);
						$slide.width(opts.height * ratio);
					}
				});
			}
		}

		if (opts.center && ((!opts.fit) || opts.aspect)) {
			$slides.each(function () {
				var $slide = $(this);
				$slide.css({
							   "margin-left": opts.width ?
								   ((opts.width - $slide.width()) / 2) + "px" :
								   0,
							   "margin-top":  opts.height ?
								   ((opts.height - $slide.height()) / 2) + "px" :
								   0
						   });
			});
		}

		if (opts.center && !opts.fit && !opts.slideResize) {
			$slides.each(function () {
				var $slide = $(this);
				$slide.css({
							   "margin-left": opts.width ? ((opts.width - $slide.width()) / 2) + "px" : 0,
							   "margin-top":  opts.height ? ((opts.height - $slide.height()) / 2) + "px" : 0
						   });
			});
		}

		// stretch container
		var reshape = (opts.containerResize || opts.containerResizeHeight) && $cont.innerHeight() < 1;
		if (reshape) { // do this only if container has no size http://tinyurl.com/da2oa9
			var maxw = 0, maxh = 0;
			for (var j = 0; j < els.length; j++) {
				var $e = $(els[j]), e = $e[0], w = $e.outerWidth(), h = $e.outerHeight();
				if (!w) w = e.offsetWidth || e.width || $e.attr('width');
				if (!h) h = e.offsetHeight || e.height || $e.attr('height');
				maxw = w > maxw ? w : maxw;
				maxh = h > maxh ? h : maxh;
			}
			if (opts.containerResize && maxw > 0 && maxh > 0)
				$cont.css({width: maxw + 'px', height: maxh + 'px'});
			if (opts.containerResizeHeight && maxh > 0)
				$cont.css({height: maxh + 'px'});
		}

		var pauseFlag = false;  // https://github.com/malsup/cycle/issues/44
		if (opts.pause)
			$cont.bind('mouseenter.cycle',function () {
				pauseFlag = true;
				this.cyclePause++;
				triggerPause(cont, true);
			}).bind('mouseleave.cycle', function () {
						if (pauseFlag)
							this.cyclePause--;
						triggerPause(cont, true);
					});

		if (supportMultiTransitions(opts) === false)
			return false;

		// apparently a lot of people use image slideshows without height/width attributes on the images.
		// Cycle 2.50+ requires the sizing info for every slide; this block tries to deal with that.
		var requeue = false;
		options.requeueAttempts = options.requeueAttempts || 0;
		$slides.each(function () {
			// try to get height/width of each slide
			var $el = $(this);
			this.cycleH = (opts.fit && opts.height) ? opts.height : ($el.height() || this.offsetHeight || this.height || $el.attr('height') || 0);
			this.cycleW = (opts.fit && opts.width) ? opts.width : ($el.width() || this.offsetWidth || this.width || $el.attr('width') || 0);

			if ($el.is('img')) {
				var loading = (this.cycleH === 0 && this.cycleW === 0 && !this.complete);
				// don't requeue for images that are still loading but have a valid size
				if (loading) {
					if (o.s && opts.requeueOnImageNotLoaded && ++options.requeueAttempts < 100) { // track retry count so we don't loop forever
						log(options.requeueAttempts, ' - img slide not loaded, requeuing slideshow: ', this.src, this.cycleW, this.cycleH);
						setTimeout(function () {
							$(o.s, o.c).cycle(options);
						}, opts.requeueTimeout);
						requeue = true;
						return false; // break each loop
					}
					else {
						log('could not determine size of image: ' + this.src, this.cycleW, this.cycleH);
					}
				}
			}
			return true;
		});

		if (requeue)
			return false;

		opts.cssBefore = opts.cssBefore || {};
		opts.cssAfter = opts.cssAfter || {};
		opts.cssFirst = opts.cssFirst || {};
		opts.animIn = opts.animIn || {};
		opts.animOut = opts.animOut || {};

		$slides.not(':eq(' + first + ')').css(opts.cssBefore);
		$($slides[first]).css(opts.cssFirst);

		if (opts.timeout) {
			opts.timeout = parseInt(opts.timeout, 10);
			// ensure that timeout and speed settings are sane
			if (opts.speed.constructor == String)
				opts.speed = $.fx.speeds[opts.speed] || parseInt(opts.speed, 10);
			if (!opts.sync)
				opts.speed = opts.speed / 2;

			var buffer = opts.fx == 'none' ? 0 : opts.fx == 'shuffle' ? 500 : 250;
			while ((opts.timeout - opts.speed) < buffer) // sanitize timeout
				opts.timeout += opts.speed;
		}
		if (opts.easing)
			opts.easeIn = opts.easeOut = opts.easing;
		if (!opts.speedIn)
			opts.speedIn = opts.speed;
		if (!opts.speedOut)
			opts.speedOut = opts.speed;

		opts.slideCount = els.length;
		opts.currSlide = opts.lastSlide = first;
		if (opts.random) {
			if (++opts.randomIndex == els.length)
				opts.randomIndex = 0;
			opts.nextSlide = opts.randomMap[opts.randomIndex];
		}
		else
			if (opts.backwards)
				opts.nextSlide = opts.startingSlide === 0 ? (els.length - 1) : opts.startingSlide - 1;
			else
				opts.nextSlide = opts.startingSlide >= (els.length - 1) ? 0 : opts.startingSlide + 1;

		// run transition init fn
		if (!opts.multiFx) {
			var init = $.fn.cycle.transitions[opts.fx];
			if ($.isFunction(init))
				init($cont, $slides, opts);
			else
				if (opts.fx != 'custom' && !opts.multiFx) {
					log('unknown transition: ' + opts.fx, '; slideshow terminating');
					return false;
				}
		}

		// fire artificial events
		var e0 = $slides[first];
		if (!opts.skipInitializationCallbacks) {
			if (opts.before.length)
				opts.before[0].apply(e0, [e0, e0, opts, true]);
			if (opts.after.length)
				opts.after[0].apply(e0, [e0, e0, opts, true]);
		}
		if (opts.next)
			$(opts.next).bind(opts.prevNextEvent, function () {
				return advance(opts, 1);
			});
		if (opts.prev)
			$(opts.prev).bind(opts.prevNextEvent, function () {
				return advance(opts, 0);
			});
		if (opts.pager || opts.pagerAnchorBuilder)
			buildPager(els, opts);

		exposeAddSlide(opts, els);

		return opts;
	}

	// save off original opts so we can restore after clearing state
	function saveOriginalOpts(opts) {
		opts.original = { before: [], after: [] };
		opts.original.cssBefore = $.extend({}, opts.cssBefore);
		opts.original.cssAfter = $.extend({}, opts.cssAfter);
		opts.original.animIn = $.extend({}, opts.animIn);
		opts.original.animOut = $.extend({}, opts.animOut);
		$.each(opts.before, function () {
			opts.original.before.push(this);
		});
		$.each(opts.after, function () {
			opts.original.after.push(this);
		});
	}

	function supportMultiTransitions(opts) {
		var i, tx, txs = $.fn.cycle.transitions;
		// look for multiple effects
		if (opts.fx.indexOf(',') > 0) {
			opts.multiFx = true;
			opts.fxs = opts.fx.replace(/\s*/g, '').split(',');
			// discard any bogus effect names
			for (i = 0; i < opts.fxs.length; i++) {
				var fx = opts.fxs[i];
				tx = txs[fx];
				if (!tx || !txs.hasOwnProperty(fx) || !$.isFunction(tx)) {
					log('discarding unknown transition: ', fx);
					opts.fxs.splice(i, 1);
					i--;
				}
			}
			// if we have an empty list then we threw everything away!
			if (!opts.fxs.length) {
				log('No valid transitions named; slideshow terminating.');
				return false;
			}
		}
		else
			if (opts.fx == 'all') {  // auto-gen the list of transitions
				opts.multiFx = true;
				opts.fxs = [];
				for (var p in txs) {
					if (txs.hasOwnProperty(p)) {
						tx = txs[p];
						if (txs.hasOwnProperty(p) && $.isFunction(tx))
							opts.fxs.push(p);
					}
				}
			}
		if (opts.multiFx && opts.randomizeEffects) {
			// munge the fxs array to make effect selection random
			var r1 = Math.floor(Math.random() * 20) + 30;
			for (i = 0; i < r1; i++) {
				var r2 = Math.floor(Math.random() * opts.fxs.length);
				opts.fxs.push(opts.fxs.splice(r2, 1)[0]);
			}
			debug('randomized fx sequence: ', opts.fxs);
		}
		return true;
	}

	// provide a mechanism for adding slides after the slideshow has started
	function exposeAddSlide(opts, els) {
		opts.addSlide = function (newSlide, prepend) {
			var $s = $(newSlide), s = $s[0];
			if (!opts.autostopCount)
				opts.countdown++;
			els[prepend ? 'unshift' : 'push'](s);
			if (opts.els)
				opts.els[prepend ? 'unshift' : 'push'](s); // shuffle needs this
			opts.slideCount = els.length;

			// add the slide to the random map and resort
			if (opts.random) {
				opts.randomMap.push(opts.slideCount - 1);
				opts.randomMap.sort(function (a, b) {
					return Math.random() - 0.5;
				});
			}

			$s.css('position', 'absolute');
			$s[prepend ? 'prependTo' : 'appendTo'](opts.$cont);

			if (prepend) {
				opts.currSlide++;
				opts.nextSlide++;
			}

			if (!$.support.opacity && opts.cleartype && !opts.cleartypeNoBg)
				clearTypeFix($s);

			if (opts.fit && opts.width)
				$s.width(opts.width);
			if (opts.fit && opts.height && opts.height != 'auto')
				$s.height(opts.height);
			s.cycleH = (opts.fit && opts.height) ? opts.height : $s.height();
			s.cycleW = (opts.fit && opts.width) ? opts.width : $s.width();

			$s.css(opts.cssBefore);

			if (opts.pager || opts.pagerAnchorBuilder)
				$.fn.cycle.createPagerAnchor(els.length - 1, s, $(opts.pager), els, opts);

			if ($.isFunction(opts.onAddSlide))
				opts.onAddSlide($s);
			else
				$s.hide(); // default behavior
		};
	}

	// reset internal state; we do this on every pass in order to support multiple effects
	$.fn.cycle.resetState = function (opts, fx) {
		fx = fx || opts.fx;
		opts.before = [];
		opts.after = [];
		opts.cssBefore = $.extend({}, opts.original.cssBefore);
		opts.cssAfter = $.extend({}, opts.original.cssAfter);
		opts.animIn = $.extend({}, opts.original.animIn);
		opts.animOut = $.extend({}, opts.original.animOut);
		opts.fxFn = null;
		$.each(opts.original.before, function () {
			opts.before.push(this);
		});
		$.each(opts.original.after, function () {
			opts.after.push(this);
		});

		// re-init
		var init = $.fn.cycle.transitions[fx];
		if ($.isFunction(init))
			init(opts.$cont, $(opts.elements), opts);
	};

	// this is the main engine fn, it handles the timeouts, callbacks and slide index mgmt
	function go(els, opts, manual, fwd) {
		var p = opts.$cont[0], curr = els[opts.currSlide], next = els[opts.nextSlide];

		// opts.busy is true if we're in the middle of an animation
		if (manual && opts.busy && opts.manualTrump) {
			// let manual transitions requests trump active ones
			debug('manualTrump in go(), stopping active transition');
			$(els).stop(true, true);
			opts.busy = 0;
			clearTimeout(p.cycleTimeout);
		}

		// don't begin another timeout-based transition if there is one active
		if (opts.busy) {
			debug('transition active, ignoring new tx request');
			return;
		}


		// stop cycling if we have an outstanding stop request
		if (p.cycleStop != opts.stopCount || p.cycleTimeout === 0 && !manual)
			return;

		// check to see if we should stop cycling based on autostop options
		if (!manual && !p.cyclePause && !opts.bounce &&
			((opts.autostop && (--opts.countdown <= 0)) ||
			 (opts.nowrap && !opts.random && opts.nextSlide < opts.currSlide))) {
			if (opts.end)
				opts.end(opts);
			return;
		}

		// if slideshow is paused, only transition on a manual trigger
		var changed = false;
		if ((manual || !p.cyclePause) && (opts.nextSlide != opts.currSlide)) {
			changed = true;
			var fx = opts.fx;
			// keep trying to get the slide size if we don't have it yet
			curr.cycleH = curr.cycleH || $(curr).height();
			curr.cycleW = curr.cycleW || $(curr).width();
			next.cycleH = next.cycleH || $(next).height();
			next.cycleW = next.cycleW || $(next).width();

			// support multiple transition types
			if (opts.multiFx) {
				if (fwd && (opts.lastFx === undefined || ++opts.lastFx >= opts.fxs.length))
					opts.lastFx = 0;
				else
					if (!fwd && (opts.lastFx === undefined || --opts.lastFx < 0))
						opts.lastFx = opts.fxs.length - 1;
				fx = opts.fxs[opts.lastFx];
			}

			// one-time fx overrides apply to:  $('div').cycle(3,'zoom');
			if (opts.oneTimeFx) {
				fx = opts.oneTimeFx;
				opts.oneTimeFx = null;
			}

			$.fn.cycle.resetState(opts, fx);

			// run the before callbacks
			if (opts.before.length)
				$.each(opts.before, function (i, o) {
					if (p.cycleStop != opts.stopCount) return;
					o.apply(next, [curr, next, opts, fwd]);
				});

			// stage the after callacks
			var after = function () {
				opts.busy = 0;
				$.each(opts.after, function (i, o) {
					if (p.cycleStop != opts.stopCount) return;
					o.apply(next, [curr, next, opts, fwd]);
				});
				if (!p.cycleStop) {
					// queue next transition
					queueNext();
				}
			};

			debug('tx firing(' + fx + '); currSlide: ' + opts.currSlide + '; nextSlide: ' + opts.nextSlide);

			// get ready to perform the transition
			opts.busy = 1;
			if (opts.fxFn) // fx function provided?
				opts.fxFn(curr, next, opts, after, fwd, manual && opts.fastOnEvent);
			else
				if ($.isFunction($.fn.cycle[opts.fx])) // fx plugin ?
					$.fn.cycle[opts.fx](curr, next, opts, after, fwd, manual && opts.fastOnEvent);
				else
					$.fn.cycle.custom(curr, next, opts, after, fwd, manual && opts.fastOnEvent);
		}
		else {
			queueNext();
		}

		if (changed || opts.nextSlide == opts.currSlide) {
			// calculate the next slide
			var roll;
			opts.lastSlide = opts.currSlide;
			if (opts.random) {
				opts.currSlide = opts.nextSlide;
				if (++opts.randomIndex == els.length) {
					opts.randomIndex = 0;
					opts.randomMap.sort(function (a, b) {
						return Math.random() - 0.5;
					});
				}
				opts.nextSlide = opts.randomMap[opts.randomIndex];
				if (opts.nextSlide == opts.currSlide)
					opts.nextSlide = (opts.currSlide == opts.slideCount - 1) ? 0 : opts.currSlide + 1;
			}
			else
				if (opts.backwards) {
					roll = (opts.nextSlide - 1) < 0;
					if (roll && opts.bounce) {
						opts.backwards = !opts.backwards;
						opts.nextSlide = 1;
						opts.currSlide = 0;
					}
					else {
						opts.nextSlide = roll ? (els.length - 1) : opts.nextSlide - 1;
						opts.currSlide = roll ? 0 : opts.nextSlide + 1;
					}
				}
				else { // sequence
					roll = (opts.nextSlide + 1) == els.length;
					if (roll && opts.bounce) {
						opts.backwards = !opts.backwards;
						opts.nextSlide = els.length - 2;
						opts.currSlide = els.length - 1;
					}
					else {
						opts.nextSlide = roll ? 0 : opts.nextSlide + 1;
						opts.currSlide = roll ? els.length - 1 : opts.nextSlide - 1;
					}
				}
		}
		if (changed && opts.pager)
			opts.updateActivePagerLink(opts.pager, opts.currSlide, opts.activePagerClass);

		function queueNext() {
			// stage the next transition
			var ms = 0, timeout = opts.timeout;
			if (opts.timeout && !opts.continuous) {
				ms = getTimeout(els[opts.currSlide], els[opts.nextSlide], opts, fwd);
				if (opts.fx == 'shuffle')
					ms -= opts.speedOut;
			}
			else
				if (opts.continuous && p.cyclePause) // continuous shows work off an after callback, not this timer logic
					ms = 10;
			if (ms > 0)
				p.cycleTimeout = setTimeout(function () {
					go(els, opts, 0, !opts.backwards);
				}, ms);
		}
	}

	// invoked after transition
	$.fn.cycle.updateActivePagerLink = function (pager, currSlide, clsName) {
		$(pager).each(function () {
			$(this).children().removeClass(clsName).eq(currSlide).addClass(clsName);
		});
	};

	// calculate timeout value for current transition
	function getTimeout(curr, next, opts, fwd) {
		if (opts.timeoutFn) {
			// call user provided calc fn
			var t = opts.timeoutFn.call(curr, curr, next, opts, fwd);
			while (opts.fx != 'none' && (t - opts.speed) < 250) // sanitize timeout
				t += opts.speed;
			debug('calculated timeout: ' + t + '; speed: ' + opts.speed);
			if (t !== false)
				return t;
		}
		return opts.timeout;
	}

	// expose next/prev function, caller must pass in state
	$.fn.cycle.next = function (opts) {
		advance(opts, 1);
	};
	$.fn.cycle.prev = function (opts) {
		advance(opts, 0);
	};

	// advance slide forward or back
	function advance(opts, moveForward) {
		var val = moveForward ? 1 : -1;
		var els = opts.elements;
		var p = opts.$cont[0], timeout = p.cycleTimeout;
		if (timeout) {
			clearTimeout(timeout);
			p.cycleTimeout = 0;
		}
		if (opts.random && val < 0) {
			// move back to the previously display slide
			opts.randomIndex--;
			if (--opts.randomIndex == -2)
				opts.randomIndex = els.length - 2;
			else
				if (opts.randomIndex == -1)
					opts.randomIndex = els.length - 1;
			opts.nextSlide = opts.randomMap[opts.randomIndex];
		}
		else
			if (opts.random) {
				opts.nextSlide = opts.randomMap[opts.randomIndex];
			}
			else {
				opts.nextSlide = opts.currSlide + val;
				if (opts.nextSlide < 0) {
					if (opts.nowrap) return false;
					opts.nextSlide = els.length - 1;
				}
				else
					if (opts.nextSlide >= els.length) {
						if (opts.nowrap) return false;
						opts.nextSlide = 0;
					}
			}

		var cb = opts.onPrevNextEvent || opts.prevNextClick; // prevNextClick is deprecated
		if ($.isFunction(cb))
			cb(val > 0, opts.nextSlide, els[opts.nextSlide]);
		go(els, opts, 1, moveForward);
		return false;
	}

	function buildPager(els, opts) {
		var $p = $(opts.pager);
		$.each(els, function (i, o) {
			$.fn.cycle.createPagerAnchor(i, o, $p, els, opts);
		});
		opts.updateActivePagerLink(opts.pager, opts.startingSlide, opts.activePagerClass);
	}

	$.fn.cycle.createPagerAnchor = function (i, el, $p, els, opts) {
		var a;
		if ($.isFunction(opts.pagerAnchorBuilder)) {
			a = opts.pagerAnchorBuilder(i, el);
			debug('pagerAnchorBuilder(' + i + ', el) returned: ' + a);
		}
		else
			a = '<a href="#">' + (i + 1) + '</a>';

		if (!a)
			return;
		var $a = $(a);
		// don't reparent if anchor is in the dom
		if ($a.parents('body').length === 0) {
			var arr = [];
			if ($p.length > 1) {
				$p.each(function () {
					var $clone = $a.clone(true);
					$(this).append($clone);
					arr.push($clone[0]);
				});
				$a = $(arr);
			}
			else {
				$a.appendTo($p);
			}
		}

		opts.pagerAnchors = opts.pagerAnchors || [];
		opts.pagerAnchors.push($a);

		var pagerFn = function (e) {
			e.preventDefault();
			opts.nextSlide = i;
			var p = opts.$cont[0], timeout = p.cycleTimeout;
			if (timeout) {
				clearTimeout(timeout);
				p.cycleTimeout = 0;
			}
			var cb = opts.onPagerEvent || opts.pagerClick; // pagerClick is deprecated
			if ($.isFunction(cb))
				cb(opts.nextSlide, els[opts.nextSlide]);
			go(els, opts, 1, opts.currSlide < i); // trigger the trans
			//		return false; // <== allow bubble
		};

		if (/mouseenter|mouseover/i.test(opts.pagerEvent)) {
			$a.hover(pagerFn, function () {/* no-op */
			});
		}
		else {
			$a.bind(opts.pagerEvent, pagerFn);
		}

		if (!/^click/.test(opts.pagerEvent) && !opts.allowPagerClickBubble)
			$a.bind('click.cycle', function () {
				return false;
			}); // suppress click

		var cont = opts.$cont[0];
		var pauseFlag = false; // https://github.com/malsup/cycle/issues/44
		if (opts.pauseOnPagerHover) {
			$a.hover(
				function () {
					pauseFlag = true;
					cont.cyclePause++;
					triggerPause(cont, true, true);
				}, function () {
					if (pauseFlag)
						cont.cyclePause--;
					triggerPause(cont, true, true);
				}
			);
		}
	};

	// helper fn to calculate the number of slides between the current and the next
	$.fn.cycle.hopsFromLast = function (opts, fwd) {
		var hops, l = opts.lastSlide, c = opts.currSlide;
		if (fwd)
			hops = c > l ? c - l : opts.slideCount - l;
		else
			hops = c < l ? l - c : l + opts.slideCount - c;
		return hops;
	};

	// fix clearType problems in ie6 by setting an explicit bg color
	// (otherwise text slides look horrible during a fade transition)
	function clearTypeFix($slides) {
		debug('applying clearType background-color hack');
		function hex(s) {
			s = parseInt(s, 10).toString(16);
			return s.length < 2 ? '0' + s : s;
		}

		function getBg(e) {
			for (; e && e.nodeName.toLowerCase() != 'html'; e = e.parentNode) {
				var v = $.css(e, 'background-color');
				if (v && v.indexOf('rgb') >= 0) {
					var rgb = v.match(/\d+/g);
					return '#' + hex(rgb[0]) + hex(rgb[1]) + hex(rgb[2]);
				}
				if (v && v != 'transparent')
					return v;
			}
			return '#ffffff';
		}

		$slides.each(function () {
			$(this).css('background-color', getBg(this));
		});
	}

	// reset common props before the next transition
	$.fn.cycle.commonReset = function (curr, next, opts, w, h, rev) {
		$(opts.elements).not(curr).hide();
		if (typeof opts.cssBefore.opacity == 'undefined')
			opts.cssBefore.opacity = 1;
		opts.cssBefore.display = 'block';
		if (opts.slideResize && w !== false && next.cycleW > 0)
			opts.cssBefore.width = next.cycleW;
		if (opts.slideResize && h !== false && next.cycleH > 0)
			opts.cssBefore.height = next.cycleH;
		opts.cssAfter = opts.cssAfter || {};
		opts.cssAfter.display = 'none';
		$(curr).css('zIndex', opts.slideCount + (rev === true ? 1 : 0));
		$(next).css('zIndex', opts.slideCount + (rev === true ? 0 : 1));
	};

	// the actual fn for effecting a transition
	$.fn.cycle.custom = function (curr, next, opts, cb, fwd, speedOverride) {
		var $l = $(curr), $n = $(next);
		var speedIn = opts.speedIn, speedOut = opts.speedOut, easeIn = opts.easeIn, easeOut = opts.easeOut;
		$n.css(opts.cssBefore);
		if (speedOverride) {
			if (typeof speedOverride == 'number')
				speedIn = speedOut = speedOverride;
			else
				speedIn = speedOut = 1;
			easeIn = easeOut = null;
		}
		var fn = function () {
			$n.animate(opts.animIn, speedIn, easeIn, function () {
				cb();
			});
		};
		$l.animate(opts.animOut, speedOut, easeOut, function () {
			$l.css(opts.cssAfter);
			if (!opts.sync)
				fn();
		});
		if (opts.sync) fn();
	};

	// transition definitions - only fade is defined here, transition pack defines the rest
	$.fn.cycle.transitions = {
		fade: function ($cont, $slides, opts) {
			$slides.not(':eq(' + opts.currSlide + ')').css('opacity', 0);
			opts.before.push(function (curr, next, opts) {
				$.fn.cycle.commonReset(curr, next, opts);
				opts.cssBefore.opacity = 0;
			});
			opts.animIn = { opacity: 1 };
			opts.animOut = { opacity: 0 };
			opts.cssBefore = { top: 0, left: 0 };
		}
	};

	$.fn.cycle.ver = function () {
		return ver;
	};

	// override these globally if you like (they are all optional)
	$.fn.cycle.defaults = {
		activePagerClass:            'activeSlide', // class name used for the active pager link
		after:                       null,     // transition callback (scope set to element that was shown):  function(currSlideElement, nextSlideElement, options, forwardFlag)
		allowPagerClickBubble:       false, // allows or prevents click event on pager anchors from bubbling
		animIn:                      null,     // properties that define how the slide animates in
		animOut:                     null,     // properties that define how the slide animates out
		aspect:                      false,    // preserve aspect ratio during fit resizing, cropping if necessary (must be used with fit option)
		autostop:                    0,        // true to end slideshow after X transitions (where X == slide count)
		autostopCount:               0,        // number of transitions (optionally used with autostop to define X)
		backwards:                   false,    // true to start slideshow at last slide and move backwards through the stack
		before:                      null,     // transition callback (scope set to element to be shown):     function(currSlideElement, nextSlideElement, options, forwardFlag)
		center:                      null,     // set to true to have cycle add top/left margin to each slide (use with width and height options)
		cleartype:                   !$.support.opacity,  // true if clearType corrections should be applied (for IE)
		cleartypeNoBg:               false,    // set to true to disable extra cleartype fixing (leave false to force background color setting on slides)
		containerResize:             1,        // resize container to fit largest slide
		containerResizeHeight:       0,  // resize containers height to fit the largest slide but leave the width dynamic
		continuous:                  0,        // true to start next transition immediately after current one completes
		cssAfter:                    null,     // properties that defined the state of the slide after transitioning out
		cssBefore:                   null,     // properties that define the initial state of the slide before transitioning in
		delay:                       0,        // additional delay (in ms) for first transition (hint: can be negative)
		easeIn:                      null,     // easing for "in" transition
		easeOut:                     null,     // easing for "out" transition
		easing:                      null,     // easing method for both in and out transitions
		end:                         null,     // callback invoked when the slideshow terminates (use with autostop or nowrap options): function(options)
		fastOnEvent:                 0,        // force fast transitions when triggered manually (via pager or prev/next); value == time in ms
		fit:                         0,        // force slides to fit container
		fx:                          'fade',   // name of transition effect (or comma separated names, ex: 'fade,scrollUp,shuffle')
		fxFn:                        null,     // function used to control the transition: function(currSlideElement, nextSlideElement, options, afterCalback, forwardFlag)
		height:                      'auto',   // container height (if the 'fit' option is true, the slides will be set to this height as well)
		manualTrump:                 true,     // causes manual transition to stop an active transition instead of being ignored
		metaAttr:                    'cycle',  // data- attribute that holds the option data for the slideshow
		next:                        null,     // element, jQuery object, or jQuery selector string for the element to use as event trigger for next slide
		nowrap:                      0,        // true to prevent slideshow from wrapping
		onPagerEvent:                null,     // callback fn for pager events: function(zeroBasedSlideIndex, slideElement)
		onPrevNextEvent:             null,     // callback fn for prev/next events: function(isNext, zeroBasedSlideIndex, slideElement)
		pager:                       null,     // element, jQuery object, or jQuery selector string for the element to use as pager container
		pagerAnchorBuilder:          null,   // callback fn for building anchor links:  function(index, DOMelement)
		pagerEvent:                  'click.cycle', // name of event which drives the pager navigation
		pause:                       0,        // true to enable "pause on hover"
		pauseOnPagerHover:           0,       // true to pause when hovering over pager link
		prev:                        null,     // element, jQuery object, or jQuery selector string for the element to use as event trigger for previous slide
		prevNextEvent:               'click.cycle',// event which drives the manual transition to the previous or next slide
		random:                      0,        // true for random, false for sequence (not applicable to shuffle fx)
		randomizeEffects:            1,        // valid when multiple effects are used; true to make the effect sequence random
		requeueOnImageNotLoaded:     true, // requeue the slideshow if any image slides are not yet loaded
		requeueTimeout:              250,      // ms delay for requeue
		rev:                         0,        // causes animations to transition in reverse (for effects that support it such as scrollHorz/scrollVert/shuffle)
		shuffle:                     null,     // coords for shuffle animation, ex: { top:15, left: 200 }
		skipInitializationCallbacks: false, // set to true to disable the first before/after callback that occurs prior to any transition
		slideExpr:                   null,     // expression for selecting slides (if something other than all children is required)
		slideResize:                 1,        // force slide width/height to fixed size before every transition
		speed:                       1000,     // speed of the transition (any valid fx speed value)
		speedIn:                     null,     // speed of the 'in' transition
		speedOut:                    null,     // speed of the 'out' transition
		startingSlide:               undefined,// zero-based index of the first slide to be displayed
		sync:                        1,        // true if in/out transitions should occur simultaneously
		timeout:                     4000,     // milliseconds between slide transitions (0 to disable auto advance)
		timeoutFn:                   null,     // callback for determining per-slide timeout value:  function(currSlideElement, nextSlideElement, options, forwardFlag)
		updateActivePagerLink:       null,// callback fn invoked to update the active pager link (adds/removes activePagerClass style)
		width:                       null      // container width (if the 'fit' option is true, the slides will be set to this width as well)
	};

})(jQuery);


/*!
 * jQuery Cycle Plugin Transition Definitions
 * This script is a plugin for the jQuery Cycle Plugin
 * Examples and documentation at: http://malsup.com/jquery/cycle/
 * Copyright (c) 2007-2010 M. Alsup
 * Version:	 2.73
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 */
(function ($) {
	"use strict";

	//
	// These functions define slide initialization and properties for the named
	// transitions. To save file size feel free to remove any of these that you
	// don't need.
	//
	$.fn.cycle.transitions.none = function ($cont, $slides, opts) {
		opts.fxFn = function (curr, next, opts, after) {
			$(next).show();
			$(curr).hide();
			after();
		};
	};

	// not a cross-fade, fadeout only fades out the top slide
	$.fn.cycle.transitions.fadeout = function ($cont, $slides, opts) {
		$slides.not(':eq(' + opts.currSlide + ')').css({ display: 'block', 'opacity': 1 });
		opts.before.push(function (curr, next, opts, w, h, rev) {
			$(curr).css('zIndex', opts.slideCount + (rev !== true ? 1 : 0));
			$(next).css('zIndex', opts.slideCount + (rev !== true ? 0 : 1));
		});
		opts.animIn.opacity = 1;
		opts.animOut.opacity = 0;
		opts.cssBefore.opacity = 1;
		opts.cssBefore.display = 'block';
		opts.cssAfter.zIndex = 0;
	};

	// scrollUp/Down/Left/Right
	$.fn.cycle.transitions.scrollUp = function ($cont, $slides, opts) {
		$cont.css('overflow', 'hidden');
		opts.before.push($.fn.cycle.commonReset);
		var h = $cont.height();
		opts.cssBefore.top = h;
		opts.cssBefore.left = 0;
		opts.cssFirst.top = 0;
		opts.animIn.top = 0;
		opts.animOut.top = -h;
	};
	$.fn.cycle.transitions.scrollDown = function ($cont, $slides, opts) {
		$cont.css('overflow', 'hidden');
		opts.before.push($.fn.cycle.commonReset);
		var h = $cont.height();
		opts.cssFirst.top = 0;
		opts.cssBefore.top = -h;
		opts.cssBefore.left = 0;
		opts.animIn.top = 0;
		opts.animOut.top = h;
	};
	$.fn.cycle.transitions.scrollLeft = function ($cont, $slides, opts) {
		$cont.css('overflow', 'hidden');
		opts.before.push($.fn.cycle.commonReset);
		var w = $cont.width();
		opts.cssFirst.left = 0;
		opts.cssBefore.left = w;
		opts.cssBefore.top = 0;
		opts.animIn.left = 0;
		opts.animOut.left = 0 - w;
	};
	$.fn.cycle.transitions.scrollRight = function ($cont, $slides, opts) {
		$cont.css('overflow', 'hidden');
		opts.before.push($.fn.cycle.commonReset);
		var w = $cont.width();
		opts.cssFirst.left = 0;
		opts.cssBefore.left = -w;
		opts.cssBefore.top = 0;
		opts.animIn.left = 0;
		opts.animOut.left = w;
	};
	$.fn.cycle.transitions.scrollHorz = function ($cont, $slides, opts) {
		$cont.css('overflow', 'hidden').width();
		opts.before.push(function (curr, next, opts, fwd) {
			if (opts.rev)
				fwd = !fwd;
			$.fn.cycle.commonReset(curr, next, opts);
			opts.cssBefore.left = fwd ? (next.cycleW - 1) : (1 - next.cycleW);
			opts.animOut.left = fwd ? -curr.cycleW : curr.cycleW;
		});
		opts.cssFirst.left = 0;
		opts.cssBefore.top = 0;
		opts.animIn.left = 0;
		opts.animOut.top = 0;
	};
	$.fn.cycle.transitions.scrollVert = function ($cont, $slides, opts) {
		$cont.css('overflow', 'hidden');
		opts.before.push(function (curr, next, opts, fwd) {
			if (opts.rev)
				fwd = !fwd;
			$.fn.cycle.commonReset(curr, next, opts);
			opts.cssBefore.top = fwd ? (1 - next.cycleH) : (next.cycleH - 1);
			opts.animOut.top = fwd ? curr.cycleH : -curr.cycleH;
		});
		opts.cssFirst.top = 0;
		opts.cssBefore.left = 0;
		opts.animIn.top = 0;
		opts.animOut.left = 0;
	};

	// slideX/slideY
	$.fn.cycle.transitions.slideX = function ($cont, $slides, opts) {
		opts.before.push(function (curr, next, opts) {
			$(opts.elements).not(curr).hide();
			$.fn.cycle.commonReset(curr, next, opts, false, true);
			opts.animIn.width = next.cycleW;
		});
		opts.cssBefore.left = 0;
		opts.cssBefore.top = 0;
		opts.cssBefore.width = 0;
		opts.animIn.width = 'show';
		opts.animOut.width = 0;
	};
	$.fn.cycle.transitions.slideY = function ($cont, $slides, opts) {
		opts.before.push(function (curr, next, opts) {
			$(opts.elements).not(curr).hide();
			$.fn.cycle.commonReset(curr, next, opts, true, false);
			opts.animIn.height = next.cycleH;
		});
		opts.cssBefore.left = 0;
		opts.cssBefore.top = 0;
		opts.cssBefore.height = 0;
		opts.animIn.height = 'show';
		opts.animOut.height = 0;
	};

	// shuffle
	$.fn.cycle.transitions.shuffle = function ($cont, $slides, opts) {
		var i, w = $cont.css('overflow', 'visible').width();
		$slides.css({left: 0, top: 0});
		opts.before.push(function (curr, next, opts) {
			$.fn.cycle.commonReset(curr, next, opts, true, true, true);
		});
		// only adjust speed once!
		if (!opts.speedAdjusted) {
			opts.speed = opts.speed / 2; // shuffle has 2 transitions
			opts.speedAdjusted = true;
		}
		opts.random = 0;
		opts.shuffle = opts.shuffle || {left: -w, top: 15};
		opts.els = [];
		for (i = 0; i < $slides.length; i++)
			opts.els.push($slides[i]);

		for (i = 0; i < opts.currSlide; i++)
			opts.els.push(opts.els.shift());

		// custom transition fn (hat tip to Benjamin Sterling for this bit of sweetness!)
		opts.fxFn = function (curr, next, opts, cb, fwd) {
			if (opts.rev)
				fwd = !fwd;
			var $el = fwd ? $(curr) : $(next);
			$(next).css(opts.cssBefore);
			var count = opts.slideCount;
			$el.animate(opts.shuffle, opts.speedIn, opts.easeIn, function () {
				var hops = $.fn.cycle.hopsFromLast(opts, fwd);
				for (var k = 0; k < hops; k++) {
					if (fwd)
						opts.els.push(opts.els.shift());
					else
						opts.els.unshift(opts.els.pop());
				}
				if (fwd) {
					for (var i = 0, len = opts.els.length; i < len; i++)
						$(opts.els[i]).css('z-index', len - i + count);
				}
				else {
					var z = $(curr).css('z-index');
					$el.css('z-index', parseInt(z, 10) + 1 + count);
				}
				$el.animate({left: 0, top: 0}, opts.speedOut, opts.easeOut, function () {
					$(fwd ? this : curr).hide();
					if (cb) cb();
				});
			});
		};
		$.extend(opts.cssBefore, { display: 'block', opacity: 1, top: 0, left: 0 });
	};

	// turnUp/Down/Left/Right
	$.fn.cycle.transitions.turnUp = function ($cont, $slides, opts) {
		opts.before.push(function (curr, next, opts) {
			$.fn.cycle.commonReset(curr, next, opts, true, false);
			opts.cssBefore.top = next.cycleH;
			opts.animIn.height = next.cycleH;
			opts.animOut.width = next.cycleW;
		});
		opts.cssFirst.top = 0;
		opts.cssBefore.left = 0;
		opts.cssBefore.height = 0;
		opts.animIn.top = 0;
		opts.animOut.height = 0;
	};
	$.fn.cycle.transitions.turnDown = function ($cont, $slides, opts) {
		opts.before.push(function (curr, next, opts) {
			$.fn.cycle.commonReset(curr, next, opts, true, false);
			opts.animIn.height = next.cycleH;
			opts.animOut.top = curr.cycleH;
		});
		opts.cssFirst.top = 0;
		opts.cssBefore.left = 0;
		opts.cssBefore.top = 0;
		opts.cssBefore.height = 0;
		opts.animOut.height = 0;
	};
	$.fn.cycle.transitions.turnLeft = function ($cont, $slides, opts) {
		opts.before.push(function (curr, next, opts) {
			$.fn.cycle.commonReset(curr, next, opts, false, true);
			opts.cssBefore.left = next.cycleW;
			opts.animIn.width = next.cycleW;
		});
		opts.cssBefore.top = 0;
		opts.cssBefore.width = 0;
		opts.animIn.left = 0;
		opts.animOut.width = 0;
	};
	$.fn.cycle.transitions.turnRight = function ($cont, $slides, opts) {
		opts.before.push(function (curr, next, opts) {
			$.fn.cycle.commonReset(curr, next, opts, false, true);
			opts.animIn.width = next.cycleW;
			opts.animOut.left = curr.cycleW;
		});
		$.extend(opts.cssBefore, { top: 0, left: 0, width: 0 });
		opts.animIn.left = 0;
		opts.animOut.width = 0;
	};

	// zoom
	$.fn.cycle.transitions.zoom = function ($cont, $slides, opts) {
		opts.before.push(function (curr, next, opts) {
			$.fn.cycle.commonReset(curr, next, opts, false, false, true);
			opts.cssBefore.top = next.cycleH / 2;
			opts.cssBefore.left = next.cycleW / 2;
			$.extend(opts.animIn, { top: 0, left: 0, width: next.cycleW, height: next.cycleH });
			$.extend(opts.animOut, { width: 0, height: 0, top: curr.cycleH / 2, left: curr.cycleW / 2 });
		});
		opts.cssFirst.top = 0;
		opts.cssFirst.left = 0;
		opts.cssBefore.width = 0;
		opts.cssBefore.height = 0;
	};

	// fadeZoom
	$.fn.cycle.transitions.fadeZoom = function ($cont, $slides, opts) {
		opts.before.push(function (curr, next, opts) {
			$.fn.cycle.commonReset(curr, next, opts, false, false);
			opts.cssBefore.left = next.cycleW / 2;
			opts.cssBefore.top = next.cycleH / 2;
			$.extend(opts.animIn, { top: 0, left: 0, width: next.cycleW, height: next.cycleH });
		});
		opts.cssBefore.width = 0;
		opts.cssBefore.height = 0;
		opts.animOut.opacity = 0;
	};

	// blindX
	$.fn.cycle.transitions.blindX = function ($cont, $slides, opts) {
		var w = $cont.css('overflow', 'hidden').width();
		opts.before.push(function (curr, next, opts) {
			$.fn.cycle.commonReset(curr, next, opts);
			opts.animIn.width = next.cycleW;
			opts.animOut.left = curr.cycleW;
		});
		opts.cssBefore.left = w;
		opts.cssBefore.top = 0;
		opts.animIn.left = 0;
		opts.animOut.left = w;
	};
	// blindY
	$.fn.cycle.transitions.blindY = function ($cont, $slides, opts) {
		var h = $cont.css('overflow', 'hidden').height();
		opts.before.push(function (curr, next, opts) {
			$.fn.cycle.commonReset(curr, next, opts);
			opts.animIn.height = next.cycleH;
			opts.animOut.top = curr.cycleH;
		});
		opts.cssBefore.top = h;
		opts.cssBefore.left = 0;
		opts.animIn.top = 0;
		opts.animOut.top = h;
	};
	// blindZ
	$.fn.cycle.transitions.blindZ = function ($cont, $slides, opts) {
		var h = $cont.css('overflow', 'hidden').height();
		var w = $cont.width();
		opts.before.push(function (curr, next, opts) {
			$.fn.cycle.commonReset(curr, next, opts);
			opts.animIn.height = next.cycleH;
			opts.animOut.top = curr.cycleH;
		});
		opts.cssBefore.top = h;
		opts.cssBefore.left = w;
		opts.animIn.top = 0;
		opts.animIn.left = 0;
		opts.animOut.top = h;
		opts.animOut.left = w;
	};

	// growX - grow horizontally from centered 0 width
	$.fn.cycle.transitions.growX = function ($cont, $slides, opts) {
		opts.before.push(function (curr, next, opts) {
			$.fn.cycle.commonReset(curr, next, opts, false, true);
			opts.cssBefore.left = this.cycleW / 2;
			opts.animIn.left = 0;
			opts.animIn.width = this.cycleW;
			opts.animOut.left = 0;
		});
		opts.cssBefore.top = 0;
		opts.cssBefore.width = 0;
	};
	// growY - grow vertically from centered 0 height
	$.fn.cycle.transitions.growY = function ($cont, $slides, opts) {
		opts.before.push(function (curr, next, opts) {
			$.fn.cycle.commonReset(curr, next, opts, true, false);
			opts.cssBefore.top = this.cycleH / 2;
			opts.animIn.top = 0;
			opts.animIn.height = this.cycleH;
			opts.animOut.top = 0;
		});
		opts.cssBefore.height = 0;
		opts.cssBefore.left = 0;
	};

	// curtainX - squeeze in both edges horizontally
	$.fn.cycle.transitions.curtainX = function ($cont, $slides, opts) {
		opts.before.push(function (curr, next, opts) {
			$.fn.cycle.commonReset(curr, next, opts, false, true, true);
			opts.cssBefore.left = next.cycleW / 2;
			opts.animIn.left = 0;
			opts.animIn.width = this.cycleW;
			opts.animOut.left = curr.cycleW / 2;
			opts.animOut.width = 0;
		});
		opts.cssBefore.top = 0;
		opts.cssBefore.width = 0;
	};
	// curtainY - squeeze in both edges vertically
	$.fn.cycle.transitions.curtainY = function ($cont, $slides, opts) {
		opts.before.push(function (curr, next, opts) {
			$.fn.cycle.commonReset(curr, next, opts, true, false, true);
			opts.cssBefore.top = next.cycleH / 2;
			opts.animIn.top = 0;
			opts.animIn.height = next.cycleH;
			opts.animOut.top = curr.cycleH / 2;
			opts.animOut.height = 0;
		});
		opts.cssBefore.height = 0;
		opts.cssBefore.left = 0;
	};

	// cover - curr slide covered by next slide
	$.fn.cycle.transitions.cover = function ($cont, $slides, opts) {
		var d = opts.direction || 'left';
		var w = $cont.css('overflow', 'hidden').width();
		var h = $cont.height();
		opts.before.push(function (curr, next, opts) {
			$.fn.cycle.commonReset(curr, next, opts);
			opts.cssAfter.display = '';
			if (d == 'right')
				opts.cssBefore.left = -w;
			else
				if (d == 'up')
					opts.cssBefore.top = h;
				else
					if (d == 'down')
						opts.cssBefore.top = -h;
					else
						opts.cssBefore.left = w;
		});
		opts.animIn.left = 0;
		opts.animIn.top = 0;
		opts.cssBefore.top = 0;
		opts.cssBefore.left = 0;
	};

	// uncover - curr slide moves off next slide
	$.fn.cycle.transitions.uncover = function ($cont, $slides, opts) {
		var d = opts.direction || 'left';
		var w = $cont.css('overflow', 'hidden').width();
		var h = $cont.height();
		opts.before.push(function (curr, next, opts) {
			$.fn.cycle.commonReset(curr, next, opts, true, true, true);
			if (d == 'right')
				opts.animOut.left = w;
			else
				if (d == 'up')
					opts.animOut.top = -h;
				else
					if (d == 'down')
						opts.animOut.top = h;
					else
						opts.animOut.left = -w;
		});
		opts.animIn.left = 0;
		opts.animIn.top = 0;
		opts.cssBefore.top = 0;
		opts.cssBefore.left = 0;
	};

	// toss - move top slide and fade away
	$.fn.cycle.transitions.toss = function ($cont, $slides, opts) {
		var w = $cont.css('overflow', 'visible').width();
		var h = $cont.height();
		opts.before.push(function (curr, next, opts) {
			$.fn.cycle.commonReset(curr, next, opts, true, true, true);
			// provide default toss settings if animOut not provided
			if (!opts.animOut.left && !opts.animOut.top)
				$.extend(opts.animOut, { left: w * 2, top: -h / 2, opacity: 0 });
			else
				opts.animOut.opacity = 0;
		});
		opts.cssBefore.left = 0;
		opts.cssBefore.top = 0;
		opts.animIn.left = 0;
	};

	// wipe - clip animation
	$.fn.cycle.transitions.wipe = function ($cont, $slides, opts) {
		var w = $cont.css('overflow', 'hidden').width();
		var h = $cont.height();
		opts.cssBefore = opts.cssBefore || {};
		var clip;
		if (opts.clip) {
			if (/l2r/.test(opts.clip))
				clip = 'rect(0px 0px ' + h + 'px 0px)';
			else
				if (/r2l/.test(opts.clip))
					clip = 'rect(0px ' + w + 'px ' + h + 'px ' + w + 'px)';
				else
					if (/t2b/.test(opts.clip))
						clip = 'rect(0px ' + w + 'px 0px 0px)';
					else
						if (/b2t/.test(opts.clip))
							clip = 'rect(' + h + 'px ' + w + 'px ' + h + 'px 0px)';
						else
							if (/zoom/.test(opts.clip)) {
								var top = parseInt(h / 2, 10);
								var left = parseInt(w / 2, 10);
								clip = 'rect(' + top + 'px ' + left + 'px ' + top + 'px ' + left + 'px)';
							}
		}

		opts.cssBefore.clip = opts.cssBefore.clip || clip || 'rect(0px 0px 0px 0px)';

		var d = opts.cssBefore.clip.match(/(\d+)/g);
		var t = parseInt(d[0], 10), r = parseInt(d[1], 10), b = parseInt(d[2], 10), l = parseInt(d[3], 10);

		opts.before.push(function (curr, next, opts) {
			if (curr == next) return;
			var $curr = $(curr), $next = $(next);
			$.fn.cycle.commonReset(curr, next, opts, true, true, false);
			opts.cssAfter.display = 'block';

			var step = 1, count = parseInt((opts.speedIn / 13), 10) - 1;
			(function f() {
				var tt = t ? t - parseInt(step * (t / count), 10) : 0;
				var ll = l ? l - parseInt(step * (l / count), 10) : 0;
				var bb = b < h ? b + parseInt(step * ((h - b) / count || 1), 10) : h;
				var rr = r < w ? r + parseInt(step * ((w - r) / count || 1), 10) : w;
				$next.css({ clip: 'rect(' + tt + 'px ' + rr + 'px ' + bb + 'px ' + ll + 'px)' });
				(step++ <= count) ? setTimeout(f, 13) : $curr.css('display', 'none');
			})();
		});
		$.extend(opts.cssBefore, { display: 'block', opacity: 1, top: 0, left: 0 });
		opts.animIn = { left: 0 };
		opts.animOut = { left: 0 };
	};

})(jQuery);
/*
 * Jquery AccordionImageMenu Plugin 0.4.
 * Examples and documentation at: http://web-argument.com/jquery-accordion-image-menu-plugin
 * By Alain Gonzalez (http://web-argument.com)
 * Copyright (c) 2011 Alain Gonzalez 
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
 */

(function( $ ){

	function accordionMenuSetting(obj,settings) {

		this.menuSettings = settings;
		this.menuAnimate = animate;
		var _this = this;

		function animate(obj,i){

			$.each(obj, function(j) {

				var otherDim = Math.round(  (  (_this.menuSettings.closeDim*obj.length)-(_this.menuSettings.openDim)  )/(obj.length-1)  );
				var itemDim = otherDim;
				if ( j == i ) {
					itemDim = _this.menuSettings.openDim;
				}
				if (typeof i == 'undefined') {
					if (_this.menuSettings.openItem == null) itemDim = _this.menuSettings.closeDim;
					else if (_this.menuSettings.openItem == j) itemDim = _this.menuSettings.openDim;
					else itemDim = otherDim;
				}

				if (_this.menuSettings.position == 'vertical')
					$(this).animate({'height':itemDim},_this.menuSettings.duration,_this.menuSettings.effect);
				else
					$(this).animate({'width':itemDim},_this.menuSettings.duration,_this.menuSettings.effect);

				var title = $('span',this);

				title.stop(true,false);

				if (_this.menuSettings.fadeInTitle != null && title.length > 0) {
					if (itemDim == _this.menuSettings.openDim) {
						if (_this.menuSettings.fadeInTitle) title.animate({'opacity':0.7});
						else title.animate({'opacity':0});
					} else {
						if (_this.menuSettings.fadeInTitle) title.animate({'opacity':0});
						else title.animate({'opacity':0.7});
					}
				}
			});

		}

		var $this = $('.accordion_item',obj);


		_this.menuAnimate($this);

		var maxDim = _this.menuSettings.closeDim*$this.length + _this.menuSettings.border*$this.length + 10;

		if (_this.menuSettings.position == 'vertical')
			$(obj).css({'width':_this.menuSettings.width+'px','height':maxDim+'px'});
		else
			$(obj).css({'height':_this.menuSettings.height+'px','width':maxDim+'px'});


		$.each($this, function(i) {

			ImgSrc = $('img',this).attr('src');
			//$('img',this).hide();

			var borderBottomValue = 0;
			var borderRightValue = 'solid '+_this.menuSettings.border+'px '+_this.menuSettings.color;
			var aWidth = 'auto';
			var aHeight = _this.menuSettings.height+'px';

			if (_this.menuSettings.position == 'vertical') {

				borderBottomValue = 'solid '+_this.menuSettings.border+'px '+_this.menuSettings.color;
				borderRightValue = 0;
				aWidth = _this.menuSettings.width+'px';
				aHeight = 'auto';
			}


			if ( i == ($this.length-1)) {
				borderBottomValue = 0;
				borderRightValue = 0;
			}

			$(this).css({
				'width': aWidth,
				'height': aHeight
			}).mouseenter(function() {
					$this.stop(true,false);
					_this.menuAnimate($this,i);
				});

		});

		$(obj).mouseleave(function() {
			_this.menuAnimate($this);
		});


	}

	$.fn.AccordionImageMenu = function( options ) {

		var settings = {
			'closeDim': 100,
			'openDim': 200,
			'width':200,
			'height':200,
			'effect': 'swing',
			'duration': 400,
			'openItem': null,
			'border': 2,
			'color':'#000000',
			'position':'horizontal',
			'fadeInTitle': true
		};

		return this.each(function() {
			$(this).addClass("aim");
			$('br',this).remove();
			if ( options ) $.extend( settings, options );
			var menu = new accordionMenuSetting(this,settings);
		});
	};

})( jQuery );
/*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */
/*! NOTE: If you're already including a window.matchMedia polyfill via Modernizr or otherwise, you don't need this part */
window.matchMedia=window.matchMedia||function(a){"use strict";var c,d=a.documentElement,e=d.firstElementChild||d.firstChild,f=a.createElement("body"),g=a.createElement("div");return g.id="mq-test-1",g.style.cssText="position:absolute;top:-100em",f.style.background="none",f.appendChild(g),function(a){return g.innerHTML='&shy;<style media="'+a+'"> #mq-test-1 { width: 42px; }</style>',d.insertBefore(f,e),c=42===g.offsetWidth,d.removeChild(f),{matches:c,media:a}}}(document);

/*! Respond.js v1.1.0: min/max-width media query polyfill. (c) Scott Jehl. MIT/GPLv2 Lic. j.mp/respondjs */
(function(a){"use strict";function x(){u(!0)}var b={};if(a.respond=b,b.update=function(){},b.mediaQueriesSupported=a.matchMedia&&a.matchMedia("only all").matches,!b.mediaQueriesSupported){var q,r,t,c=a.document,d=c.documentElement,e=[],f=[],g=[],h={},i=30,j=c.getElementsByTagName("head")[0]||d,k=c.getElementsByTagName("base")[0],l=j.getElementsByTagName("link"),m=[],n=function(){for(var b=0;l.length>b;b++){var c=l[b],d=c.href,e=c.media,f=c.rel&&"stylesheet"===c.rel.toLowerCase();d&&f&&!h[d]&&(c.styleSheet&&c.styleSheet.rawCssText?(p(c.styleSheet.rawCssText,d,e),h[d]=!0):(!/^([a-zA-Z:]*\/\/)/.test(d)&&!k||d.replace(RegExp.$1,"").split("/")[0]===a.location.host)&&m.push({href:d,media:e}))}o()},o=function(){if(m.length){var b=m.shift();v(b.href,function(c){p(c,b.href,b.media),h[b.href]=!0,a.setTimeout(function(){o()},0)})}},p=function(a,b,c){var d=a.match(/@media[^\{]+\{([^\{\}]*\{[^\}\{]*\})+/gi),g=d&&d.length||0;b=b.substring(0,b.lastIndexOf("/"));var h=function(a){return a.replace(/(url\()['"]?([^\/\)'"][^:\)'"]+)['"]?(\))/g,"$1"+b+"$2$3")},i=!g&&c;b.length&&(b+="/"),i&&(g=1);for(var j=0;g>j;j++){var k,l,m,n;i?(k=c,f.push(h(a))):(k=d[j].match(/@media *([^\{]+)\{([\S\s]+?)$/)&&RegExp.$1,f.push(RegExp.$2&&h(RegExp.$2))),m=k.split(","),n=m.length;for(var o=0;n>o;o++)l=m[o],e.push({media:l.split("(")[0].match(/(only\s+)?([a-zA-Z]+)\s?/)&&RegExp.$2||"all",rules:f.length-1,hasquery:l.indexOf("(")>-1,minw:l.match(/\(\s*min\-width\s*:\s*(\s*[0-9\.]+)(px|em)\s*\)/)&&parseFloat(RegExp.$1)+(RegExp.$2||""),maxw:l.match(/\(\s*max\-width\s*:\s*(\s*[0-9\.]+)(px|em)\s*\)/)&&parseFloat(RegExp.$1)+(RegExp.$2||"")})}u()},s=function(){var a,b=c.createElement("div"),e=c.body,f=!1;return b.style.cssText="position:absolute;font-size:1em;width:1em",e||(e=f=c.createElement("body"),e.style.background="none"),e.appendChild(b),d.insertBefore(e,d.firstChild),a=b.offsetWidth,f?d.removeChild(e):e.removeChild(b),a=t=parseFloat(a)},u=function(b){var h="clientWidth",k=d[h],m="CSS1Compat"===c.compatMode&&k||c.body[h]||k,n={},o=l[l.length-1],p=(new Date).getTime();if(b&&q&&i>p-q)return a.clearTimeout(r),r=a.setTimeout(u,i),void 0;q=p;for(var v in e)if(e.hasOwnProperty(v)){var w=e[v],x=w.minw,y=w.maxw,z=null===x,A=null===y,B="em";x&&(x=parseFloat(x)*(x.indexOf(B)>-1?t||s():1)),y&&(y=parseFloat(y)*(y.indexOf(B)>-1?t||s():1)),w.hasquery&&(z&&A||!(z||m>=x)||!(A||y>=m))||(n[w.media]||(n[w.media]=[]),n[w.media].push(f[w.rules]))}for(var C in g)g.hasOwnProperty(C)&&g[C]&&g[C].parentNode===j&&j.removeChild(g[C]);for(var D in n)if(n.hasOwnProperty(D)){var E=c.createElement("style"),F=n[D].join("\n");E.type="text/css",E.media=D,j.insertBefore(E,o.nextSibling),E.styleSheet?E.styleSheet.cssText=F:E.appendChild(c.createTextNode(F)),g.push(E)}},v=function(a,b){var c=w();c&&(c.open("GET",a,!0),c.onreadystatechange=function(){4!==c.readyState||200!==c.status&&304!==c.status||b(c.responseText)},4!==c.readyState&&c.send(null))},w=function(){var b=!1;try{b=new a.XMLHttpRequest}catch(c){b=new a.ActiveXObject("Microsoft.XMLHTTP")}return function(){return b}}();n(),b.update=n,a.addEventListener?a.addEventListener("resize",x,!1):a.attachEvent&&a.attachEvent("onresize",x)}})(this);
(function(a){a.uniform={options:{selectClass:"selector",radioClass:"radio",checkboxClass:"checker",fileClass:"uploader",filenameClass:"filename",fileBtnClass:"action",fileDefaultText:"No file selected",fileBtnText:"Choose File",checkedClass:"checked",focusClass:"focus",disabledClass:"disabled",buttonClass:"button",activeClass:"active",hoverClass:"hover",useID:true,idPrefix:"uniform",resetSelector:false,autoHide:true},elements:[]};if(a.browser.msie&&a.browser.version<7){a.support.selectOpacity=false}else{a.support.selectOpacity=true}a.fn.uniform=function(k){k=a.extend(a.uniform.options,k);var d=this;if(k.resetSelector!=false){a(k.resetSelector).mouseup(function(){function l(){a.uniform.update(d)}setTimeout(l,10)})}function j(l){$el=a(l);$el.addClass($el.attr("type"));b(l)}function g(l){a(l).addClass("uniform");b(l)}function i(o){var m=a(o);var p=a("<div>"),l=a("<span>");p.addClass(k.buttonClass);if(k.useID&&m.attr("id")!=""){p.attr("id",k.idPrefix+"-"+m.attr("id"))}var n;if(m.is("a")||m.is("button")){n=m.text()}else{if(m.is(":submit")||m.is(":reset")||m.is("input[type=button]")){n=m.attr("value")}}n=n==""?m.is(":reset")?"Reset":"Submit":n;l.html(n);m.css("opacity",0);m.wrap(p);m.wrap(l);p=m.closest("div");l=m.closest("span");if(m.is(":disabled")){p.addClass(k.disabledClass)}p.bind({"mouseenter.uniform":function(){p.addClass(k.hoverClass)},"mouseleave.uniform":function(){p.removeClass(k.hoverClass);p.removeClass(k.activeClass)},"mousedown.uniform touchbegin.uniform":function(){p.addClass(k.activeClass)},"mouseup.uniform touchend.uniform":function(){p.removeClass(k.activeClass)},"click.uniform touchend.uniform":function(r){if(a(r.target).is("span")||a(r.target).is("div")){if(o[0].dispatchEvent){var q=document.createEvent("MouseEvents");q.initEvent("click",true,true);o[0].dispatchEvent(q)}else{o[0].click()}}}});o.bind({"focus.uniform":function(){p.addClass(k.focusClass)},"blur.uniform":function(){p.removeClass(k.focusClass)}});a.uniform.noSelect(p);b(o)}function e(o){var m=a(o);var p=a("<div />"),l=a("<span />");if(!m.css("display")=="none"&&k.autoHide){p.hide()}p.addClass(k.selectClass);if(k.useID&&o.attr("id")!=""){p.attr("id",k.idPrefix+"-"+o.attr("id"))}var n=o.find(":selected:first");if(n.length==0){n=o.find("option:first")}l.html(n.html());o.css("opacity",0);o.wrap(p);o.before(l);p=o.parent("div");l=o.siblings("span");o.bind({"change.uniform":function(){l.text(o.find(":selected").html());p.removeClass(k.activeClass)},"focus.uniform":function(){p.addClass(k.focusClass)},"blur.uniform":function(){p.removeClass(k.focusClass);p.removeClass(k.activeClass)},"mousedown.uniform touchbegin.uniform":function(){p.addClass(k.activeClass)},"mouseup.uniform touchend.uniform":function(){p.removeClass(k.activeClass)},"click.uniform touchend.uniform":function(){p.removeClass(k.activeClass)},"mouseenter.uniform":function(){p.addClass(k.hoverClass)},"mouseleave.uniform":function(){p.removeClass(k.hoverClass);p.removeClass(k.activeClass)},"keyup.uniform":function(){l.text(o.find(":selected").html())}});if(a(o).attr("disabled")){p.addClass(k.disabledClass)}a.uniform.noSelect(l);b(o)}function f(n){var m=a(n);var o=a("<div />"),l=a("<span />");if(!m.css("display")=="none"&&k.autoHide){o.hide()}o.addClass(k.checkboxClass);if(k.useID&&n.attr("id")!=""){o.attr("id",k.idPrefix+"-"+n.attr("id"))}a(n).wrap(o);a(n).wrap(l);l=n.parent();o=l.parent();a(n).css("opacity",0).bind({"focus.uniform":function(){o.addClass(k.focusClass)},"blur.uniform":function(){o.removeClass(k.focusClass)},"click.uniform touchend.uniform":function(){if(!a(n).attr("checked")){l.removeClass(k.checkedClass)}else{l.addClass(k.checkedClass)}},"mousedown.uniform touchbegin.uniform":function(){o.addClass(k.activeClass)},"mouseup.uniform touchend.uniform":function(){o.removeClass(k.activeClass)},"mouseenter.uniform":function(){o.addClass(k.hoverClass)},"mouseleave.uniform":function(){o.removeClass(k.hoverClass);o.removeClass(k.activeClass)}});if(a(n).attr("checked")){l.addClass(k.checkedClass)}if(a(n).attr("disabled")){o.addClass(k.disabledClass)}b(n)}function c(n){var m=a(n);var o=a("<div />"),l=a("<span />");if(!m.css("display")=="none"&&k.autoHide){o.hide()}o.addClass(k.radioClass);if(k.useID&&n.attr("id")!=""){o.attr("id",k.idPrefix+"-"+n.attr("id"))}a(n).wrap(o);a(n).wrap(l);l=n.parent();o=l.parent();a(n).css("opacity",0).bind({"focus.uniform":function(){o.addClass(k.focusClass)},"blur.uniform":function(){o.removeClass(k.focusClass)},"click.uniform touchend.uniform":function(){if(!a(n).attr("checked")){l.removeClass(k.checkedClass)}else{var p=k.radioClass.split(" ")[0];a("."+p+" span."+k.checkedClass+":has([name='"+a(n).attr("name")+"'])").removeClass(k.checkedClass);l.addClass(k.checkedClass)}},"mousedown.uniform touchend.uniform":function(){if(!a(n).is(":disabled")){o.addClass(k.activeClass)}},"mouseup.uniform touchbegin.uniform":function(){o.removeClass(k.activeClass)},"mouseenter.uniform touchend.uniform":function(){o.addClass(k.hoverClass)},"mouseleave.uniform":function(){o.removeClass(k.hoverClass);o.removeClass(k.activeClass)}});if(a(n).attr("checked")){l.addClass(k.checkedClass)}if(a(n).attr("disabled")){o.addClass(k.disabledClass)}b(n)}function h(q){var o=a(q);var r=a("<div />"),p=a("<span>"+k.fileDefaultText+"</span>"),m=a("<span>"+k.fileBtnText+"</span>");if(!o.css("display")=="none"&&k.autoHide){r.hide()}r.addClass(k.fileClass);p.addClass(k.filenameClass);m.addClass(k.fileBtnClass);if(k.useID&&o.attr("id")!=""){r.attr("id",k.idPrefix+"-"+o.attr("id"))}o.wrap(r);o.after(m);o.after(p);r=o.closest("div");p=o.siblings("."+k.filenameClass);m=o.siblings("."+k.fileBtnClass);if(!o.attr("size")){var l=r.width();o.attr("size",l/10)}var n=function(){var s=o.val();if(s===""){s=k.fileDefaultText}else{s=s.split(/[\/\\]+/);s=s[(s.length-1)]}p.text(s)};n();o.css("opacity",0).bind({"focus.uniform":function(){r.addClass(k.focusClass)},"blur.uniform":function(){r.removeClass(k.focusClass)},"mousedown.uniform":function(){if(!a(q).is(":disabled")){r.addClass(k.activeClass)}},"mouseup.uniform":function(){r.removeClass(k.activeClass)},"mouseenter.uniform":function(){r.addClass(k.hoverClass)},"mouseleave.uniform":function(){r.removeClass(k.hoverClass);r.removeClass(k.activeClass)}});if(a.browser.msie){o.bind("click.uniform.ie7",function(){setTimeout(n,0)})}else{o.bind("change.uniform",n)}if(o.attr("disabled")){r.addClass(k.disabledClass)}a.uniform.noSelect(p);a.uniform.noSelect(m);b(q)}a.uniform.restore=function(l){if(l==undefined){l=a(a.uniform.elements)}a(l).each(function(){if(a(this).is(":checkbox")){a(this).unwrap().unwrap()}else{if(a(this).is("select")){a(this).siblings("span").remove();a(this).unwrap()}else{if(a(this).is(":radio")){a(this).unwrap().unwrap()}else{if(a(this).is(":file")){a(this).siblings("span").remove();a(this).unwrap()}else{if(a(this).is("button, :submit, :reset, a, input[type='button']")){a(this).unwrap().unwrap()}}}}}a(this).unbind(".uniform");a(this).css("opacity","1");var m=a.inArray(a(l),a.uniform.elements);a.uniform.elements.splice(m,1)})};function b(l){l=a(l).get();if(l.length>1){a.each(l,function(m,n){a.uniform.elements.push(n)})}else{a.uniform.elements.push(l)}}a.uniform.noSelect=function(l){function m(){return false}a(l).each(function(){this.onselectstart=this.ondragstart=m;a(this).mousedown(m).css({MozUserSelect:"none"})})};a.uniform.update=function(l){if(l==undefined){l=a(a.uniform.elements)}l=a(l);l.each(function(){var n=a(this);if(n.is("select")){var m=n.siblings("span");var p=n.parent("div");p.removeClass(k.hoverClass+" "+k.focusClass+" "+k.activeClass);m.html(n.find(":selected").html());if(n.is(":disabled")){p.addClass(k.disabledClass)}else{p.removeClass(k.disabledClass)}}else{if(n.is(":checkbox")){var m=n.closest("span");var p=n.closest("div");p.removeClass(k.hoverClass+" "+k.focusClass+" "+k.activeClass);m.removeClass(k.checkedClass);if(n.is(":checked")){m.addClass(k.checkedClass)}if(n.is(":disabled")){p.addClass(k.disabledClass)}else{p.removeClass(k.disabledClass)}}else{if(n.is(":radio")){var m=n.closest("span");var p=n.closest("div");p.removeClass(k.hoverClass+" "+k.focusClass+" "+k.activeClass);m.removeClass(k.checkedClass);if(n.is(":checked")){m.addClass(k.checkedClass)}if(n.is(":disabled")){p.addClass(k.disabledClass)}else{p.removeClass(k.disabledClass)}}else{if(n.is(":file")){var p=n.parent("div");var o=n.siblings(k.filenameClass);btnTag=n.siblings(k.fileBtnClass);p.removeClass(k.hoverClass+" "+k.focusClass+" "+k.activeClass);o.text(n.val());if(n.is(":disabled")){p.addClass(k.disabledClass)}else{p.removeClass(k.disabledClass)}}else{if(n.is(":submit")||n.is(":reset")||n.is("button")||n.is("a")||l.is("input[type=button]")){var p=n.closest("div");p.removeClass(k.hoverClass+" "+k.focusClass+" "+k.activeClass);if(n.is(":disabled")){p.addClass(k.disabledClass)}else{p.removeClass(k.disabledClass)}}}}}}})};return this.each(function(){if(a.support.selectOpacity){var l=a(this);if(l.is("select")){if(l.attr("multiple")!=true){if(l.attr("size")==undefined||l.attr("size")<=1){e(l)}}}else{if(l.is(":checkbox")){f(l)}else{if(l.is(":radio")){c(l)}else{if(l.is(":file")){h(l)}else{if(l.is(":text, :password, input[type='email']")){j(l)}else{if(l.is("textarea")){g(l)}else{if(l.is("a")||l.is(":submit")||l.is(":reset")||l.is("button")||l.is("input[type=button]")){i(l)}}}}}}}}})}})(jQuery);
(function ($) {
	$.fn.setTheFourthLevelHeight = function () {
		var minHeight = '500px';

		$('#widescreen-wrap, #thefourthlevel, #main-col, #right-col, #one-col-template-wrap').css({
			'min-height': minHeight
		});
		if ($('#thefourthlevel').is(':visible')) {
			if ($('#widescreen-wrap').length > 0) {
				minHeight = Math.max($('#widescreen-wrap').height(), $('#thefourthlevel').height());
				$('#widescreen-wrap, #thefourthlevel').css({
					'min-height': minHeight
				});
			} else if ($('#one-col-template-wrap').length > 0) {
				minHeight = Math.max($('#one-col-template-wrap').height(), $('#thefourthlevel').height());
				$('#one-col-template-wrap, #thefourthlevel').css({
					'min-height': minHeight
				});
			} else {
				minHeight = Math.max($('#main-col').height(), $('#thefourthlevel').height(), $('#right-col').height());
				$('#main-col, #right-col, #thefourthlevel').css({
					'min-height': minHeight
				});
			}
		} else {
			$('#widescreen-wrap, #main-col, #right-col').css({
				'min-height': minHeight
			});
		}
	}

	// Breakpoint settings
	$(window).setBreakpoints({
		distinct: true,
		breakpoints: [
			320,
			480,
			768,
			990,
			992,
			1000,
			1024,
			1280,
			1323,
			1330
		]
	});

	// helper to find current innerWidth
	/*
	 $(window).on('resize', function() {
	 console.log($(window).innerWidth());
	 console.log(document.documentElement.clientWidth);

	 });
	 */

	$(function () {
		// On Dom Ready
		// add or remove touch/notouch class for bodytag
		if (isMobile()) {
			$('body, html').removeClass('notouch').addClass('touch');
		} else {
			$('body, html').removeClass('touch').addClass('notouch');
		}

		// Breadcrumb
		//$('#breadcrumb').jBreadCrumb();

		// Newsletter
		$('.newsletter select').uniform();

		// Listing make div clickable
		makeclickable('.listing-item')

		// Listing element hover
		$('.listing-wrapper .listing-item, .news-list-container .listing-item').hover(function () {
			$(this).addClass('hover');
		}, function () {
			$(this).removeClass('hover');
		});

		// News latest last child no border - frontpage intranet/internet
		$('.news-latest-container div:last-child').prev().addClass('last');
		$('.clips-latest-container div:last-child').prev().addClass('last');
		$('.dates-latest-container div:last-child').prev().addClass('last');
		$('.updates-latest-container div:last-child').prev().addClass('last');

		$('.listing-item:last-child').addClass('last');
		$('.news-list-item:first-child').addClass('first-item');

		$('.clips-latest-container .news-latest-item a').attr('target', '_blank');

		// Contactbox powermail no border bottom

		$('.email2powermail').parent().parent().parent().css('borderBottom', 'none');


		// Tabellen Abstand nach unten bei Fussnote
		$('.fussnote').prev().addClass('tableNoMargin');
		$('.fussnote').addClass('marginBottom30');

		// Add class hover service-header for Linkstyling
		$('#service-header-wrap').hover(function () {
			$(this).addClass('hover');
		}, function () {
			$(this).removeClass('hover');
		});

		// Portlet 1-col template portlets footer
		$('.portlet-content').masonry({
			itemSelector: '.portlet-content > .csc-default',
			columnWidth: 260,
			gutterWidth: 20,
			isResizable: true,
			isAnimated: true
		});

		// Share show additional info
		$('.showAdditional').mouseenter(function () {
			$('.additional-share').show();
		});

		$('.additional-share').mouseleave(function () {
			$(this).hide()
		});

		$('.share-wrapper').mouseleave(function () {
			$('.additional-share').hide()
		});

		$('.share-wrapper .share-right a').mouseenter(function () {
			$('.additional-share').hide();
			$('.showAdditional').removeClass('active');
		});

		$('.additional-share').hover(function () {
			$('.showAdditional').addClass('active');
		}, function () {
			$('.showAdditional').removeClass('active');
		});

		// Check if sidebar/portlet has content - show background
		if ($('.right-col-content > div').hasClass('csc-default')) {
		}
		else {
			$('.right-col-content').addClass('noBackground');
		}

		$('.prinzip04-menu-icon').each(function () {
			_this = $(this);
			if ($(this).parent('map').attr('title') != undefined) {
				_this.append('<div class="prinzip04-menu-icon-title">' + $(this).parent('map').attr('title') + '</div>');
			}
		});

		$('.prinzip04-menu dt').not('.top, .bottom').attr('data-menu-point-state', 'inactive').attr('data-menu-content-state', 'inactive');
		$('.prinzip04-menu dt').not('.top, .bottom').hoverIntent(function () {
			var menuPoint = $(this);
			var menuContent = menuPoint.nextAll('dd').first();
			menuPoint.attr('data-menu-point-state', 'active');

			if (menuContent.text() != '') {
				menuPoint.prepend('<div class="active-frame"></div>').find('a').addClass('hover');
				$('.active-frame').css({height: menuPoint.height()});

				var contentWrapOffset = $('#content-wrap').offset().top;
				var menuContentOffset = $(this).offset().top;

				menuContent.css('top', menuContentOffset - contentWrapOffset - 10).show();
				//menuContent.css('top', $(this).position().top - 10).show();
				menuContent.hover(function () {
					menuPoint.attr('data-menu-content-state', 'active');
				}, function () {
					menuPoint.attr('data-menu-content-state', 'inactive');
					if (menuPoint.attr('data-menu-point-state') == 'inactive') {
						menuContent.hide();
						$('.active-frame').remove();
						menuPoint.find('a').removeClass('hover');
					}
				})
			}
		}, function () {
			$(this).attr('data-menu-point-state', 'inactive');
			if ($(this).attr('data-menu-content-state') == 'inactive') {
				$('.active-frame').remove();
				$(this).find('a').removeClass('hover');
				$(this).nextAll('dd').first().hide();
			}
		});

		$('.prinzip04-menu dt').not('.top, .bottom').each(function () {

			var isRootPage = document.location.pathname == '' || document.location.pathname == '/';
			var href = $(this).find('a').attr('href');
            var path_href = href.replace(document.location.origin,'');
            var path_current = '/'+document.location.pathname.split('/')[1]+'/';
			var baseHref = $('base').attr('href');
			if (isRootPage && (href == baseHref || href + '/' == baseHref)) {
				$(this).find('a').css({'color': '#008ad9'});
			}
            if($(this).parent().hasClass('with-active-states') && (href == document.location.href || (path_href.indexOf(path_current) != -1))) {
                    $(this).find('a').css({'color': '#008ad9'});
            }
		});

		$('.related-content-container').not('.alternative_navigation').each(function () {
			var addClass = 'x';
			if ($(this).parent().parent().attr('id') == 'thefourthlevel' || $(this).parent().parent().parent().attr('id') == 'thefourthlevel') {
				addClass = 'relative';
			}
			var topcontent = $('#content-wrap').offset().top;
			var top = $(this).offset().top;
			$(this).appendTo('#thefourthlevel').css({
				'top': top - topcontent
			}).addClass(addClass);
		});

		$(window).setTheFourthLevelHeight();
		window.setTimeout('$(window).setTheFourthLevelHeight()', 2000);

		// setTheFourthLevelHeight
		$(window).bind('enterBreakpoint1330 exitBreakpoint1330 enterBreakpoint1323 exitBreakpoint1323 enterBreakpoint1024 exitBreakpoint1024 enterBreakpoint990 exitBreakpoint990 enterBreakpoint768 exitBreakpoint768', function () {
			$(window).setTheFourthLevelHeight();
		});

		$('.berichterstattung .navi-bericht .year-selector .single-year').on('click', function () {
			$(window).setTheFourthLevelHeight();
		});

		// Desktop
		$(window).bind('enterBreakpoint1024', function () {
//			$('.csc-default:nth-child(4)').addClass('noMarginRight');
			$('.portlet-content').masonry({
				itemSelector: '.csc-default',
				columnWidth: 260,
				gutterWidth: 20,
				isResizable: true,
				isAnimated: true
			});
		});


		// iPad portrait
		$(window).bind('enterBreakpoint768', function () {
			$('.right-col-content > div:odd').addClass('odd');
			$('.right-col-content > div:last-child').prev('div').andSelf().addClass('last-element');

			$('.portlet-content').masonry({
				itemSelector: '.csc-default',
				columnWidth: 330,
				gutterWidth: 20,
				isResizable: true,
				isAnimated: true
			});

			$('#smartphone-header-wrap').hide();
		});


		// iPhone landscape
		$(window).bind('enterBreakpoint480', function () {
			$('.portlet-content').masonry({
				itemSelector: '.csc-default',
				columnWidth: 220,
				isResizable: true,
				isAnimated: true
			});
		});

		// iPhone portrait
		$(window).bind('enterBreakpoint320', function () {
			$('.portlet-content').masonry('destroy');
		});

		// if ($('.tx-powermail').closest('.csc-default').hasClass('powermailWithoutRequired')) {
		// 	$('.powermail_submit').prop('disabled', false);
		// 	$('.powermail_submit').addClass('buttonActive');
		// 	$('.powermail_submit').removeClass('buttonInActive');
		// } else {
		// 	// powermail send button
		// 	$('.tx-powermail form').addClass('validation');
		// 	$('.powermail_submit').prop('disabled', true);
		// 	$('.powermail_submit').addClass('buttonInActive');
		// }
	});


	// Vertical breakpoints
	$(window).bind('enterBreakpointV200', function () {
		if ( $('#header-stage').hasClass('headerformat-1') && $(window).scrollTop() < 140 ) {
			// jQuery.fn.goToByScroll('main-start', -190)
 			 $(window).scrollTop(140);
		}
	});
	$(window).bind('exitBreakpointV200', function () {
		if ( $('#header-stage').hasClass('headerformat-1') && $(window).scrollTop() == 140 ) {
			// jQuery.fn.goToByScroll('page-wrap', 0)
			$(window).scrollTop(0);
		}
	});




	$(window).on('load', function () {
		$('.related-content-campaign .related-content-helper').each(function () {
			var backgroundImage = $(this).parent().find('.related-content-background img').attr('src');
			$(this).css({
				backgroundImage: 'url(' + backgroundImage + ')'
			});
			$(this).parent().parent().find('.related-content-container').hover(function () {
				$(this).find('.related-content-icon').css({
					backgroundImage: 'url(' + backgroundImage + ')'
				})
			}, function () {
				$(this).find('.related-content-icon').css({
					backgroundImage: 'none'
				})
			});
		});
		$('.related-content-bodytext').each(function () {
			$(this).css({
				height: $(this).parent().height() - 40
			});
		});
		$(window).setTheFourthLevelHeight();

		/*$('.content-dropdown-title').attr('title',  $('.content-dropdown-title').text());
		 $('.content-dropdown-title').attr('rel', $('.content-dropdown-container').find('li.active').last().children('a').text());
		 $('.content-dropdown-title').text($('.content-dropdown-title').attr('rel'));*/
		$('.content-dropdown-container').find('li.active').last().addClass('current');
	});

	$('.content-dropdown-title').click(function () {
		if ($(this).parent().hasClass('content-dropdown-close')) { // open
			$(this).siblings('.content-dropdown-container').slideDown('fast').parent().removeClass('content-dropdown-close');

			/*$('.content-dropdown-title').text($('.content-dropdown-title').attr('title'));*/
			if ($('.content-dropdown-container').find('li.active').length > 0) {
				if ($('.content-dropdown-container').scrollTop() == 0) {
					$('.content-dropdown-container').scrollTop(function () {
						return $('.content-dropdown-container').find('li.active').last().offset().top - $('.content-dropdown-container').offset().top;
					});
				}
			}
		} else { // close
			$(this).siblings('.content-dropdown-container').slideUp('fast').parent().addClass('content-dropdown-close');
			/*$('.content-dropdown-title').text($('.content-dropdown-title').attr('rel'));*/
		}
	});

	$('area.txwimagemap_cbox_area').mouseover(function (e) {
		$('.txmwimagemap_cbox').hide();
		var id = $(this).attr('rel');
		$('#txmwimagemap_cbox_' + id).show();
	});


	// Newsticker
	$('.ticker-wrap').wrapInner('<div class="ticker-inner-wrap" />');

	tickerslider('.wrap-newsticker', 'newsticker-nav', '.newsticker');
	tickerslider('.wrap-ceticker', 'ceticker-nav', '.ceticker', 0, 232);


	// Newsletter Lightbox-Link
	$(".fancybox-link-newsletter").fancybox({
		'hideOnContentClick': true,
		'width': 300,
		'height': 300
	});

	// nl2br (e.g. talentpool)
	if ($('.jQueryNl2Br').length > 0) {
		$('.jQueryNl2Br').each(function () {
			var content = $(this).html();
			content = nl2br(content);
			$(this).html(content);
		});
	}

	$(function () {
		var austDay = new Date($('.equitiesTickerCountdownDate').val());
		$('#defaultCountdown').countdown({
			until: austDay,
			layout: '<span class="countdown_row countdown_show4">' +
				'<span class="countdown_section"><span class="countdown_amount">{dnn}</span><br />Tage</span>' +
				'<span class="countdown_section"><span class="countdown_amount">{hnn}</span><br />Stunden</span>' +
				'<span class="countdown_section"><span class="countdown_amount">{mnn}</span><br />Minuten</span>' +
				'<span class="countdown_section"><span class="countdown_amount">{snn}</span><br />Sekunden</span>' +
				'</span>'
		});
	});

	// Projectlisting check if has image or teasertext
	$('.projectlisting-item').not(':has(.project-image)').addClass('noimage');
	$('.projectlisting-item .project-text').not(':has(.teaser)').addClass('noteaser');

	// Smartphone redirect
	if ($('.smartphone_redirect').length > 0) {
		var url = '';
		var on_get_param = $('#on_get_param').val();
		if (isIPhone()) {
			url = $('#ios_target').val();
		}
		if (isAndroid()) {
			url = $('#android_target').val();
		}
		if (isMobileButNotIPhoneAndNotAndroid()) {
			url = $('#other_target').val();
		}
		if (url != undefined && url != '') {
			if (on_get_param == '' || (on_get_param != '' && usedGetParameter(on_get_param))) {
				location.href = url;
			}
		}
	}


})(jQuery);

/** form validation ** /
 *
 *
 *
 */
var validate = {
	conf: {
		forms: null,
		email: new RegExp(/^((([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)
	},
	is_valid: false,
	valid: function (e) {
		validate.validate(e.target);
		var $submit = $('.powermail_submit');
		if (validate.is_valid === true) {
			$submit.prop('disabled', false);
			$submit.addClass('buttonActive');
			$submit.removeClass('buttonInActive');
		} else {
			$submit.prop('disabled', true);
			$submit.addClass('buttonInActive');
			$submit.removeClass('buttonActive');
		}
	},
	set_fields: function(){
		$.each(validate.conf.forms.find('[class*="validate"]'), function(){
			if($(this).is(':visible')){
				var tag = $(this).prop('tagName').toLowerCase();
				var type = $(this).attr('type');

				if ((tag == 'input' && type == 'text') || tag == 'textarea') {
					if($(this).attr('class').indexOf('required') != -1 && $(this).is(':visible')) {
						$(this).bind('keyup', validate.valid);
					}
				} else {
					if ((tag == 'input' && (type == 'checkbox' || type == 'radio')) || tag == 'select') {
						$(this).bind('change', validate.valid);
					}
				}

			}
		});
	},
	valid_field : new Array(),
	validate: function (obj) {
		$(obj).closest('form').find('[class*="validate"]').each(function(index,el){
			tag = $(el).prop('tagName').toLowerCase();
			type = $(el).attr('type');

			if(!$(el).is(':visible')) return;

			if(tag == 'input' && type == 'text') {
				validate.valid_field[index] = $(el).val().length > 0;

				if(validate.valid_field[index] == true && $(el).attr('class').indexOf('[email]') != -1 && validate.conf.email.test($(el).val()) === false) {
					validate.valid_field[index] = false;
				}
			}else if(tag == 'input' && (type == 'checkbox' || type=='radio')) {
				validate.valid_field[index] = $('[class="'+$(el).attr('class')+'"]').is(':checked');
			}else if(tag == 'textarea') {
				validate.valid_field[index] = $(el).val().length > 0;
			}else if(tag == 'select') {
				validate.valid_field[index] = $(el).val().length > 0;
			}
		}).promise().done(function(){
			var set_true = true;
			for(var i = 0; i < validate.valid_field.length; i++) {
				if(validate.valid_field[i] == false) {
					set_true = false;
				}
			}
			validate.is_valid = set_true;
		});
	},
	init: function () {
		validate.conf.forms = $('.tx-powermail form.validation');
		validate.set_fields();
	}
};
// $(document).ready(validate.init);

var realestate = realestate || {
		classes: {},
		init: function() {
			if($('.tx-powermail form.realestate_rollenmodell').length > 0){
				realestate.classes.rolle = $('.rolleeingeben input').attr('class');
				realestate.classes.betreff = $('.betreffeingeben input').attr('class');
				$('.rolleeingeben input').attr('class', '').prop('required', false);
				$('.betreffeingeben input').attr('class', '').prop('required', false);

				$('#powermail_field_rolle').bind('change', function(e){
					if($('#powermail_field_rolle').val() == "other"){
						$('.rolleeingeben input').show().addClass(realestate.classes.rolle).prop('required', true);
						$('.rolleeingeben').slideDown('fast', function(){
							$(this).find('[class*="validate"]').bind('keyup', validate.valid).keyup();
						});

					}else {
						$('.rolleeingeben').slideUp('fast', function(){
							$(this).find('[class*="validate"]').unbind('keyup', validate.valid);
							$('.rolleeingeben input').hide().attr('class', '').prop('required', false);
							$('form.realestate_rollenmodell input[class*="validate"]:visible').keyup();

						});

					}
				});
				$('#powermail_field_betreff').bind('change', function(e){
					if($('#powermail_field_betreff').val() == "other"){
						$('.betreffeingeben input').show().addClass(realestate.classes.betreff).prop('required', true);
						$('.betreffeingeben').slideDown('fast', function(){
							$(this).find('input[class*="validate"]').bind('keyup', validate.valid).keyup();
						});
					}else {
						$('.betreffeingeben').slideUp('fast', function(){
							$(this).find('input[class*="validate"]').unbind('keyup', validate.valid);
							$('.betreffeingeben input').hide().attr('class', '').prop('required', false);
							$('form.realestate_rollenmodell input[class*="validate"]:visible').keyup();
						});
					}
				});
			}
		}
	};
$(document).ready(realestate.init);


/**
 * Check if user device is mobile or not
 *
 * @return    bool
 */
function isMobile() {
	var ua = navigator.userAgent;
	var checker = {
		iphone: ua.match(/(iPhone|iPod|iPad)/),
		blackberry: ua.match(/BlackBerry/),
		android: ua.match(/Android/)
	}

	if (checker.iphone || checker.blackberry || checker.android) {
		return true;
	}
	return false;
}

/**
 * Check if user device is iPhone
 *
 * @return    bool
 */
function isIPhone() {
	var ua = navigator.userAgent;
	var checker = {
		iphone: ua.match(/(iPhone|iPod|iPad)/)
	}

	if (checker.iphone) {
		return true;
	}
	return false;
}

/**
 * Check if user device is Android OS
 *
 * @return    bool
 */
function isAndroid() {
	var ua = navigator.userAgent;
	var checker = {
		android: ua.match(/Android/)
	}

	if (checker.android) {
		return true;
	}
	return false;
}

/**
 * Check if user device is Android OS
 *
 * @return    bool
 */
function isMobileButNotIPhoneAndNotAndroid() {
	var UserAgent = navigator.userAgent.toLowerCase();
	if (UserAgent.search(/(opera mini|fennec|palm|blackberry|symbian|series60)/) > -1) {
		return true;
	}
	return false;
}

/**
 * Check if it's an old Android Tablet (Version 2 or 3)
 */
function isOldAndroidTablet() {
	var ua = navigator.userAgent;
	if (ua.match(/(Android 2|Android 3)/)) {
		return true;
	}
	return false;
}

function nl2br(str, is_xhtml) {
	var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br ' + '/>' : '<br>'; // Adjust comment to avoid issue on phpjs.org display
	return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}

/**
 * Checks if a given getParam is used
 *
 * @param getParam
 * @return bool
 */
function usedGetParameter(getParam) {
	var currentUrl = window.location.href;
	if (currentUrl.indexOf('?' + getParam + '=') !== -1 || currentUrl.indexOf('&' + getParam + '=') !== -1) {
		return true;
	}
	return false;
}

function makeclickable(element) {
	$(element).click(function () {
		if ($(this).find('a').attr('target') == '_blank') {
			window.open($(this).find('a').attr('href'));
		} else {
			window.location = $(this).find('a').attr('href');
		}
		return false;
	});
}

/**
 *
 * Start the jQuery Cycle Plugin
 *
 * @param string wrapper
 * @param string afterwrapperclass
 * @param string cycler
 * @param int speed
 * @param int height
 */
function tickerslider(wrapper, afterwrapperclass, cycler, speed, height) {

	if ($(wrapper).length > 0) {

		if (!speed || speed == 0) {
			speed = 1500;
		}

		if (!height) {
			height = 'auto';
		}

		$(wrapper).each(function (i) {
			var tickerid = 'slideticker' + i;
			$(this).parent().after('<div id="' + tickerid + '" class="' + afterwrapperclass + '">');
			$(this).children(cycler).cycle({
				fx: 'scrollLeft',
				speed: speed,
				pause: '1',
				pager: '#' + tickerid,
				height: height,

				pagerAnchorBuilder: function (idx, slide) {
					var number = idx + 1;
					number = number.toString()
					number = '0' + number;

					return '<a href="#">' + number + '</a>';
				}
			});
		});

	}

}

var bilf_home_nl = {
    init: function(){
        $('.powermail_homepage_box select').bind('change', function(){
            $(this).prev('label').text($(this).find('option:selected').text());
        });
    }
};
$(document).ready(bilf_home_nl.init);


var bilf_ga_adsense = {
	init: function(){
		if(typeof goog_report_conversion == "function" && typeof goog_snippet_vars == "function"){
			var mailaddress = $('.mailaddress a');
			if (mailaddress.length > 0){
				mailaddress.unbind('click').bind('click', function(e){
					goog_report_conversion();
				});
			}
		}
	}
};
$(document).ready(bilf_ga_adsense.init);
(function ($) {
	if($('.ticker-third-fourth').length > 0) {
		$('.ticker-third-fourth .ceticker.group > div').each(function() {
			$this = $(this);
			if(getLinkUrl($this).length > 0) {
				$this.addClass('ticker-third-fourth-link');
			}
		}).click(function() {
			if (isLinkInNewWindow($(this))) {
				window.open(getLinkUrl($(this)), '_blank');
			} else {
				window.location = getLinkUrl($(this));
			}
		});
	}

	/**
	 * Set height for border bottom
	 *
	 * @param string tyoe			type small or large
	 * @return void
	 */
	function setHeight(type) {
		$('.homece').each(function() {
			var $this = $(this);
            //+RED18234
            if($this.find('.s111.group.small').length > 0) return;
            //+RED18234

            if ($this.find('.csc-header').find('a').html() == '-') {
                $this.find('.csc-header').hide();
            }


			if (getLinkUrl($this)) { // is with link

				$this.addClass('homecelink'); // blue line
				if (isLinkInNewWindow($this)) {
					$this.addClass('homecelinkblank'); // blue line
				}
				$this.append($('<div/>').addClass('homece_link_arrow')); // add arrow

				// width3 with image
				if ($this.hasClass('width3') && $this.find('.csc-textpic-imagewrap').length) {

					$this.addClass('homece_noborder');

					if (type == 'small') {
						var imageheight = $this.find('.csc-textpic-imagewrap').height(); // small
					} else {
						var imageheight = $this.find('.csc-textpic-imagewrap').find('img').attr('height'); // large
					}
					$this.find('.csc-textpic-text').height((imageheight - 2));
				}
			}
		});

		$('.homece > .homecelink').parent('.homece').addClass('noBorderReference'); // remove additional borders
	}


	/**
	 * Get Link URL
	 *
	 * @param element
	 * @return string URL
	 */
	function getLinkUrl(element) {
		// stop on slideshow
		if (element.hasClass('ticker-third-fourth')) {
			return '';
		}

		url = element.find('.csc-header').find('a').attr('href');
		if (!url || url == undefined) {
			url = element.find('.csc-textpic-image').children('a').attr('href');
		}
		if (url && url != undefined) {
			return url;
		}
		return '';
	}

	/**
	 * Check if there is a _blank in the link
	 *
	 * @param element
	 * @return bool
	 */
	function isLinkInNewWindow(element) {
		var isBlank = false;

		if (element.find('.csc-header').find('a').length > 0) {
			if (element.find('.csc-header').find('a').attr('target') == '_blank') {
				isBlank = true;
			}
		} else if (element.find('.csc-textpic-image').children('a').attr('target') == '_blank') {
			isBlank = true;
		}

		return isBlank;
	}



	$(function () {
		setHeight('large');

		// breakpoint calls
		$(window).bind('exitBreakpoint768', function () {
			setHeight('large');
		});
		$(window).bind('enterBreakpoint768', function () {
			setHeight('small');
		});

		// on click
		$(document).on('click', '.homece', function(e) {
			e.stopPropagation();
			var $this = $(this);
			if (getLinkUrl($this)) {
				if ($this.hasClass('homecelinkblank')) {
					window.open(getLinkUrl($this));
				} else {
					window.location = getLinkUrl($this);
				}
			}
		});
		// on click homecelink
		$(document).on('click', '.homecelink', function (e) {
			if ($(this).children('.news-latest-container').length == 0) {
				e.preventDefault();
			}
		});


		// set videoheight in startboxes
		if($('.homece .tx_socialembedding').length > 0) {
			$('.tx_socialembedding').each(function(){
				setEmbeddingVideoSize($(this));

				// Timeout IE8
				if($(this).children().hasClass('tx_socialembedding_intranetvideo')) {
					setTimeout(function() {
						setEmbeddingVideoSize($(this));
					}, 5000);
				}
			});
		}

		$(window).bind('enterBreakpoint1330 exitBreakpoint1330 enterBreakpoint1323 exitBreakpoint1323 enterBreakpoint1024 exitBreakpoint1024 enterBreakpoint990 exitBreakpoint990 enterBreakpoint768 exitBreakpoint768', function () {
			if($('.homece .tx_socialembedding').length > 0) {
				$('.tx_socialembedding').each(function(){
					setEmbeddingVideoSize($(this));
				});
			}


		});

		// count elements in col three
		$('.content-3').children('.csc-default').each(function(i) {
			$(this).addClass('ce-counter' + (++i));
		});

		/**
		 * Set the videoheight und -width for embedded videos on pages with home layout
		 * @param element
		 */
		function setEmbeddingVideoSize(element) {
			if (element.closest('.homece').length > 0) {
				element.removeClass('video');
			}
			var boxh = element.parent().height();
			var boxw = element.parent().width();
			var titleh = element.parent().find('.csc-header').children().outerHeight(true);

			// Youtube (Internet + Intranet)
			element.children().attr('width', boxw);
			element.children().attr('height', (boxh - titleh));

			// ASX videos (Intranet)
			if(element.children().hasClass('tx_socialembedding_intranetvideo')) {
				element.children().css('width', boxw);
				element.children().css('height', (boxh - titleh) + 'px');
			}


		}


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

	$(function () {
		$(document).on('click', '.tx-felogin-pi1 a', function(e){
			e.preventDefault();

			var href = $(this).attr('href');

			hrefTemp = href.split('?');

			if(hrefTemp.length > 1){
				href = '?' + hrefTemp[1] + '&type=77&id=628';
			}

			$.ajax({
				url : href,
				beforeSend: function(){
					var height = $('#c90Elements').height();
					$('#c90Elements').css({height : height}).html('').addClass('ajax-loader');
				},
				success: function(data){
					$('#c90Elements').removeClass('ajax-loader').html(data);
				}
			});
		});

		$(document).on('click', '#c90Elements input[type="submit"]', function(e){
			if($('#tx_felogin_pi1-forgot-email').length < 1){
				return;
			}

			e.preventDefault();

			var form = $('#c90Elements form');
			var formValues = form.serialize();
			var url = form.attr('action');

			$.ajax({
				type:'POST', // type
				url:url, // send to this url
				data:formValues, // add params
				beforeSend:function () {
					var height = $('#c90Elements').height();
					$('#c90Elements').css({height:height}).html('').addClass('ajax-loader');
				},
				success:function (data) { // return values
					$('#c90Elements').removeClass('ajax-loader').html(data);
				}
			});
		});
	});
});

(function ($) {
	if($('select.fancyselect').length > 0) {
		$('select.fancyselect').each(function(){
			addFancyselectElement($(this));
		});
	}

	/**
	 *
	 * generate the fancyselectelements
	 *
	 * @param element string
	 */
	function addFancyselectElement(element) {
		element.hide();
		var elName = element.attr('name');

		var outer = $('<div>').addClass('fancyselect').attr('id', 'fsb_' + elName);

		// create selected div
		var selected = $('<div>').addClass('fsb_selected').addClass('defaultValue').text(element.children(':selected').text()).on('click', function() {
			openFancyselect($(this));
		});

		// create inner div
		var inner = $('<div>').addClass('fsb_inner fsb_closed');

		// create outer elements
		outer.html(inner);
		selected.prependTo(outer);

		$(element).children('option').each(function(i, option){
			$('<div/>', {
				'data-value': option.value,
				'text': option.text
			  }).appendTo(inner).on('click', function() {
				changeFancyselectAttr($(this), element);
			});
		});

		// create outerelement before selectfields
		$(element).before(outer);

		checkIfSelectedIsDefault(element);
	}

	/**
	 *
	 * clicked the option
	 *
	 * @param element string
	 */
	function changeFancyselectAttr(element, parentElement) {
		var selectedText = element.text(),
			value = element.data('value');
		element.siblings('.fsb_option_selected').removeClass('fsb_option_selected');
		element.addClass('fsb_option_selected');
		parentElement.find('option').attr('selected', false);
		parentElement.find('option[value="' + value + '"]').attr('selected', true);
		element.closest('.fsb_inner').hide().addClass('fsb_closed').removeClass('fsb_open');
		element.closest('.fsb_inner').siblings('.fsb_selected').text(selectedText);

		// submit if set onchange
		if(element.closest('.fancyselect').next('.fancyselect:first').attr('onchange')) {
			element.closest('form').submit();
		}
		parentElement.val(value).change();
		checkIfSelectedIsDefault(element);
	}

	/**
	 *
	 * open the selectbox
	 *
	 * @param element string
	 */
	function openFancyselect(element) {
		$('.fsb_inner').hide().addClass('fsb_closed').removeClass('fsb_open');
		element.next('.fsb_inner').show().addClass('fsb_open').removeClass('fsb_closed');
	}

	/**
	 * check if selected value has id 0 (default)
	 *
	 * @param element string
	 */
	function checkIfSelectedIsDefault(element) {
		var parentElement = element.closest('.tx-in2realestate-field');

		if (parentElement.find('.fsb_inner').children().first().hasClass('fsb_option_selected')) {
			if (!parentElement.find('.fsb_selected').hasClass('defaultValue')) {
				parentElement.find('.fsb_selected').addClass('defaultValue');
			}
		} else {
			parentElement.find('.fsb_selected').removeClass('defaultValue');
		}
	}

})(jQuery);
/**
 * Build responsive tables
 *
 * @module ResponsiveTables
 */
(function ResponsiveTables() {
	'use strict';
	/**
	 * Handles the responsive tables
	 *
	 * @class ResponsiveTablesConfiguration
	 * @constructor
	 */
	function ResponsiveTablesConfiguration() {
		var that = this;

		/**
		 * The css name from the original table wrapper
		 *
		 * @type {string}
		 */
		this.originalTableWrap = 'responsivetable_fixedleftcolumn';

		/**
		 * The original table wrap
		 *
		 * @type {object}
		 */
		this.originalTable = $('.' + that.originalTableWrap + ' > table');

		/**
		 * The css name from the original table
		 *
		 * @type {string}
		 */
		this.tablenameOriginal = 'responsivetable--hide';

		/**
		 * The css name from the table top left
		 *
		 * @type {string}
		 */
		this.tablenameTopLeft = 'responsivetable--topleft';

		/**
		 * The css name from the table top right
		 *
		 * @type {string}
		 */
		this.tablenameTopRight = 'responsivetable--topright';

		/**
		 * The css name from the table left
		 *
		 * @type {string}
		 */
		this.tablenameLeft = 'responsivetable--left';

		/**
		 * The css name from the table right
		 *
		 * @type {string}
		 */
		this.tablenameRight = 'responsivetable--right';

		/**
		 * The css name from the originalWrap
		 *
		 * @type {string}
		 */
		this.originalWrapClassname = 'table-wrapper';

		/**
		 * The css name from the tr hover class
		 *
		 * @type {string}
		 */
		this.hoverClassname = 'hoverresponsivetr';

		/**
		 * The css selector from the originalWrap
		 *
		 * @type {string}
		 */
		this.originalWrapClass = '.' + that.originalWrapClassname;

		/**
		 * The wrap from the original Table
		 *
		 * @type {string}
		 */
		this.originalWrap = '<div class="' + that.originalWrapClassname + '" />';

		/**
		 * Update Tables after resize
		 */
		this.resizewindow = function() {
			that.updateTable();
		};

		/**
		 * Update tables
		 */
		this.updateTable = function() {
			if (this.originalTable.is(':visible')) {
				// build new Table in Mobile
				that.originalTable.each(function(i, element) {
					that.splitTable($(element));
				});
				that.addResponiveTableWraps();
				that.scaleTables();
				that.addScroll();
			} else {
				that.compareBreakpointSize();
			}
		};

		/**
		 * set the class to the tablewrapper
		 *
		 * @object breakpointclass
		 */
		this.setBreakpointToWrapper = function(breakpointclass) {
			var $tablewrapper = $(that.originalWrapClass);
			$tablewrapper.attr('data-initialsize', breakpointclass);
		};

		/**
		 * check if the breakpoint the same or a new one
		 * if new one, scale the tables new
		 */
		this.compareBreakpointSize = function() {
			var bodyclasses = $('body').attr('class');
			var breakpointclass = bodyclasses.match(/breakpoint-\d+/);
			var $tablewrapper = $(that.originalWrapClass);

			$tablewrapper.each(function() {
				if ( typeof $(this).data('initialsize') !== 'undefined' && $(this).data('initialsize')) {
					if (breakpointclass === $(this).attr('data-initialsize')) {
						return false;
					} else {
						that.scaleTables();
						that.setBreakpointToWrapper(breakpointclass);
					}
				} else {
					that.scaleTables();
					that.setBreakpointToWrapper(breakpointclass);
				}
			});
		};

		/**
		 * Clone the original table, add classes, hide rows and theads, add this in the dom
		 *
		 * @returns {void}
		 */
		this.splitTable = function($original) {
			$original.wrap(that.originalWrap);
			var $container = $original.closest(that.originalWrapClass);

			// set the rows and cols new
			var $copytable = $original.clone();
			that.fixRowspan($copytable);
			that.fixColspan($copytable);

			// clone all tables and replace the ID with the id incl. table position
			var tableID			= $original.attr('id');
			var $tableTopLeft	= $copytable.clone().attr('id', tableID + '__topleft');
			var $tableTopRight	= $copytable.clone().attr('id', tableID + '__topright');
			var $tableLeft		= $copytable.clone().attr('id', tableID + '__left');
			var $tableRight		= $copytable.clone().attr('id', tableID + '__right');

			// add classes of tables
			$original.addClass(that.tablenameOriginal);
			$tableTopLeft.addClass(that.tablenameTopLeft);
			$tableTopRight.addClass(that.tablenameTopRight);
			$tableLeft.addClass(that.tablenameLeft);
			$tableRight.addClass(that.tablenameRight);

			// hide rows and theads from tables
			$tableTopLeft.find('td:not(:first-child), th:not(:first-child), tbody').css('display', 'none');
			$tableTopRight.find('td:first-child, th:first-child, tbody').css('display', 'none');
			$tableLeft.find('td:not(:first-child), th:not(:first-child), thead').css('display', 'none');
			$tableLeft.find('td:not(:first-child), th:not(:first-child)').css('display', 'none');
			$tableRight.find('td:first-child, th:first-child, thead').css('display', 'none');

			// add tables into wrapper
			$container.append($tableRight).append($tableLeft).append($tableTopRight).append($tableTopLeft);

			that.initHoverEffect($tableTopLeft, $tableTopRight, $tableLeft, $tableRight);
			that.initRemoveHoverEffect($tableTopLeft, $tableTopRight, $tableLeft, $tableRight);
		};

		/**
		 * init the hovereffect to all tables
		 *
		 * @object $tableTopLeft
		 * @object $tableTopRight
		 * @object $tableLeft
		 * @object $tableRight
		 */
		this.initHoverEffect = function($tableTopLeft, $tableTopRight, $tableLeft, $tableRight) {
			that.addHoverEffect($tableTopLeft, $tableTopRight);
			that.addHoverEffect($tableTopRight, $tableTopLeft);
			that.addHoverEffect($tableLeft, $tableRight);
			that.addHoverEffect($tableRight, $tableLeft);
		};

		/**
		 * init the remove hovereffect from all tables
		 *
		 * @object $tableTopLeft
		 * @object $tableTopRight
		 * @object $tableLeft
		 * @object $tableRight
		 */
		this.initRemoveHoverEffect = function($tableTopLeft, $tableTopRight, $tableLeft, $tableRight) {
			that.removeHoverEffect($tableTopLeft, $tableTopRight);
			that.removeHoverEffect($tableTopRight, $tableTopLeft);
			that.removeHoverEffect($tableLeft, $tableRight);
			that.removeHoverEffect($tableRight, $tableLeft);
		};

		/**
		 * add class to source tr if hover over the source tr
		 *
		 * @object $sourceTable
		 * @object $targetTable
		 */
		this.addHoverEffect = function($sourceTable, $targetTable) {
			$sourceTable.find('tr').on('hover', function() {
				var trIndex = $sourceTable.find('tr').index($(this).closest('tr'));
				var $targetTr = $targetTable.find(' tr').eq(trIndex);
				$targetTr.addClass(that.hoverClassname);
			});
		};

		this.removeHoverEffect = function($sourceTable, $targetTable) {
			$sourceTable.find('tr').on('mouseleave', function() {
				var trIndex = $sourceTable.find('tr').index($(this).closest('tr'));
				var $targetTr = $targetTable.find(' tr').eq(trIndex);
				$targetTr.removeClass(that.hoverClassname);
			});
		};

		/**
		 * add the responsive wraps around the mobile tables
		 *
		 * @returns {void}
		 */
		this.addResponiveTableWraps = function() {
			$('.' + this.tablenameTopRight).wrap('<div class="scrollable-top responsive-table" />');
			$('.' + this.tablenameLeft).wrap('<div class="scrollable-left responsive-table" />');
			$('.' + this.tablenameRight).wrap('<div class="scrollable" />');
			$('.' + this.tablenameTopLeft).addClass('responsive-table');
		};

		/**
		 * get all responsive tables and start the scaling of row height and width
		 *
		 * @returns {void}
		 */
		this.scaleTables = function() {
			var $tableWrapper = $('.' + this.originalWrapClassname);

			var $tableTopLeft = $tableWrapper.find('.' + that.tablenameTopLeft);
			var $tableTopRight = $tableWrapper.find('.' + that.tablenameTopRight);
			var $tableLeft = $tableWrapper.find('.' + that.tablenameLeft);
			var $tableRight = $tableWrapper.find('.' + that.tablenameRight);

			// reset height from tables
			that.resetRowHeight($tableTopLeft);
			that.resetRowHeight($tableTopRight);
			that.resetRowHeight($tableLeft);
			that.resetRowHeight($tableRight);

			// Set row height from topleft to topright and reverse
			that.setTopRowHeights($tableTopLeft, $tableTopRight);
			that.setTopRowHeights($tableTopRight, $tableTopLeft);

			// reset height from tables
			that.resetCellWidth($tableTopLeft);
			that.resetCellWidth($tableTopRight);
			that.resetCellWidth($tableRight);
			that.resetCellWidth($tableLeft);

			// set cellwidth vom topleft to left and revert
			that.setCellWidths($tableTopLeft, $tableLeft);
			that.setCellWidths($tableTopRight, $tableRight);

			that.setRowHeights($tableRight, $tableLeft);

			// position the left and the right table
			that.positionTables($tableWrapper);
		};

		/**
		 * remove rowspan from tr and add the missing td into the following tr
		 *
		 * @returns {void}
		 */
		this.fixRowspan = function($element) {
			$element.find('td').each(function() {
				if ($(this).attr('rowspan') > 1) {
					var rowspansize = $(this).attr('rowspan');
					var $td = $(this);
					var $emptyTd = $td.clone().removeAttr('rowspan').empty();
					var tdPosition = $td.index();

					// find next tr and add a empty td on the right place
					var x = 1;
					while (x < rowspansize) {
						x = x + 1;
						var $nextSibling = $element.find('tr:eq( ' + x + ' )');
						var $siblingTd = $nextSibling.find('td:eq( ' + tdPosition + ' )');
						$siblingTd.before($emptyTd.clone());
					}

					$td.removeAttr('rowspan');
				}
			});
		};

		/**
		 * remove colspan from td and add behind the missing empty td
		 *
		 * @returns {void}
		 */
		this.fixColspan = function($element) {
			$element.find('td[colspan]').not('[colspan=1]').each(function() {
				var $this = $(this);
				var colspanCount = $this.attr('colspan');
				$this.removeAttr('colspan');
				var $clone = $this.clone().empty();
				var absColspanCount = Math.abs(colspanCount);
				var counter = absColspanCount - 1;
				for (var i = 0; i < counter; i++) {
					$this.after($clone.clone());
				}
			});
		};

		/**
		 * Set the Row height from the toptablesource to the target
		 *
		 * @object $source
		 * @object $target
		 */
		this.setTopRowHeights = function($source, $target) {
			var $tr = $source.find('tr');
			var $trCopy = $target.find('tr');
			var heights = [];

			$tr.each(function(index) {
				var self = $(this);
				var tx = self.find('th, td');

				tx.each(function() {
					var height = $(this).outerHeight(true);
					heights[index] = heights[index] || 0;
					if (height > heights[index]) {
						heights[index] = height;
					}
				});
			});

			$trCopy.each(function(index) {
				$(this).height(heights[index]);
			});
		};

		/**
		 * Set the Row height from the source to the target
		 *
		 * @object $source
		 * @object $target
		 */
		this.setRowHeights = function($source, $target) {
			var $tr = $source.find('tr');
			$tr.each(function(index) {
				var $sourceTrIndexElement = $source.find('tr:eq(' + index + ')');
				var $targetTrIndexElement = $target.find('tr:eq(' + index + ')');

				var sourceTrIndexElementHeight = $sourceTrIndexElement.outerHeight(true);
				var targetTrIndexElementHeight = $targetTrIndexElement.outerHeight(true);

				if (sourceTrIndexElementHeight > targetTrIndexElementHeight) {
					$sourceTrIndexElement.height(sourceTrIndexElementHeight);
					$targetTrIndexElement.height(sourceTrIndexElementHeight);
				} else if (sourceTrIndexElementHeight < targetTrIndexElementHeight) {
					$sourceTrIndexElement.height(targetTrIndexElementHeight);
					$targetTrIndexElement.height(targetTrIndexElementHeight);
				} else {
					$sourceTrIndexElement.height(sourceTrIndexElementHeight);
					$targetTrIndexElement.height(sourceTrIndexElementHeight);
				}
			});
		};

		/**
		 * Set the cell height from the source to the target and reverse
		 *
		 * @object $source
		 * @object $target
		 */
		this.setCellWidths = function($source, $target) {
			var $tdFromSourceFirstTr = $source.find('thead tr:first-child td');
			var $tdFromTargetFirstTr = $target.find('tbody tr:first-child td');
			var widths = [];

			// copy source (thead > td) width to target (tbody > td)
			$tdFromSourceFirstTr.each(function(index) {
				var sourceTdWidth = $(this).width();

				widths[index] = widths[index] || 0;
				if (sourceTdWidth > widths[index]) {
					widths[index] = sourceTdWidth;
				}
			});

			$tdFromTargetFirstTr.each(function(index) {
				$(this).width(widths[index]);
			});
		};

		/**
		 * Remove height from all tr in source
		 *
		 * @object $source
		 */
		this.resetRowHeight = function($source) {
			var $trFromSource = $source.find('tr');
			$trFromSource.css('height', '');
		};

		/**
		 * Remove width from all td in source
		 *
		 * @object $source
		 */
		this.resetCellWidth = function($source) {
			var $trFromSource = $source.find('td');
			$trFromSource.css('width', 'auto');
		};

		/**
		 * Set position for the tables
		 *
		 * @object $source
		 * @object $target
		 */
		this.positionTables = function($tableWrapper) {
			$tableWrapper.each(function() {
				var $tableTopLeft = $(this).find('.' + that.tablenameTopLeft);
				var $tableTopRightWrap = $(this).find('.' + that.tablenameTopRight).closest('div');
				var $tableLeftWrap = $(this).find('.' + that.tablenameLeft).closest('div');
				var $tableRightWrap = $(this).find('.' + that.tablenameRight).closest('div');
				var topMargin = $tableTopLeft.outerHeight();
				var leftMargin = $tableTopLeft.outerWidth();

				$tableLeftWrap.css('margin-top', topMargin - 1);
				$tableRightWrap.css('margin-top', topMargin - 1).css('margin-left', leftMargin).css('height', 525 - topMargin);
				$tableTopRightWrap.css('margin-left', leftMargin);
			});
		};

		/**
		 * add the scroolfunction to the tables
		 */
		this.addScroll = function() {
			var $tableWrapper = $('.' + this.originalWrapClassname);
			$tableWrapper.each(function() {
				var $wrapTopLeft = $(this).find('.scrollable-top');
				var $wrapRight = $(this).find('.scrollable-left');

				$(this).find('.scrollable').scroll(function() {
					var distance = $(this).scrollLeft();
					$wrapTopLeft.css('left', (-Math.abs(distance)) + 'px');
				});

				$(this).find('.scrollable').scroll(function() {
					var distance = $(this).scrollTop();
					$wrapRight.css('top', (-Math.abs(distance)) + 'px');
				});
			});
		};
	}

	$(document).ready(function() {
		var startResize;
		var ResponsiveTablesConfig = new ResponsiveTablesConfiguration();

		// Update Table | onload | on redraw | on resize
		$(window).load(ResponsiveTablesConfig.updateTable());
		$(window).on('redraw', function() {
			ResponsiveTablesConfig.updateTable();
		});

		window.onresize = function() {
			clearTimeout(startResize);
			startResize = setTimeout(ResponsiveTablesConfig.resizewindow, 100);
		};
	});
})();

/* http://keith-wood.name/countdown.html
   Countdown for jQuery v1.6.2.
   Written by Keith Wood (kbwood{at}iinet.com.au) January 2008.
   Available under the MIT (https://github.com/jquery/jquery/blob/master/MIT-LICENSE.txt) license. 
   Please attribute the author if you use it. */

/* Display a countdown timer.
   Attach it with options like:
   $('div selector').countdown(
       {until: new Date(2009, 1 - 1, 1, 0, 0, 0), onExpiry: happyNewYear}); */

(function($) { // Hide scope, no $ conflict

/* Countdown manager. */
function Countdown() {
	this.regional = []; // Available regional settings, indexed by language code
	this.regional[''] = { // Default regional settings
		// The display texts for the counters
		labels: ['Years', 'Months', 'Weeks', 'Days', 'Hours', 'Minutes', 'Seconds'],
		// The display texts for the counters if only one
		labels1: ['Year', 'Month', 'Week', 'Day', 'Hour', 'Minute', 'Second'],
		compactLabels: ['y', 'm', 'w', 'd'], // The compact texts for the counters
		whichLabels: null, // Function to determine which labels to use
		digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], // The digits to display
		timeSeparator: ':', // Separator for time periods
		isRTL: false // True for right-to-left languages, false for left-to-right
	};
	this._defaults = {
		until: null, // new Date(year, mth - 1, day, hr, min, sec) - date/time to count down to
			// or numeric for seconds offset, or string for unit offset(s):
			// 'Y' years, 'O' months, 'W' weeks, 'D' days, 'H' hours, 'M' minutes, 'S' seconds
		since: null, // new Date(year, mth - 1, day, hr, min, sec) - date/time to count up from
			// or numeric for seconds offset, or string for unit offset(s):
			// 'Y' years, 'O' months, 'W' weeks, 'D' days, 'H' hours, 'M' minutes, 'S' seconds
		timezone: null, // The timezone (hours or minutes from GMT) for the target times,
			// or null for client local
		serverSync: null, // A function to retrieve the current server time for synchronisation
		format: 'dHMS', // Format for display - upper case for always, lower case only if non-zero,
			// 'Y' years, 'O' months, 'W' weeks, 'D' days, 'H' hours, 'M' minutes, 'S' seconds
		layout: '', // Build your own layout for the countdown
		compact: false, // True to display in a compact format, false for an expanded one
		significant: 0, // The number of periods with values to show, zero for all
		description: '', // The description displayed for the countdown
		expiryUrl: '', // A URL to load upon expiry, replacing the current page
		expiryText: '', // Text to display upon expiry, replacing the countdown
		alwaysExpire: false, // True to trigger onExpiry even if never counted down
		onExpiry: null, // Callback when the countdown expires -
			// receives no parameters and 'this' is the containing division
		onTick: null, // Callback when the countdown is updated -
			// receives int[7] being the breakdown by period (based on format)
			// and 'this' is the containing division
		tickInterval: 1 // Interval (seconds) between onTick callbacks
	};
	$.extend(this._defaults, this.regional['']);
	this._serverSyncs = [];
	// Shared timer for all countdowns
	function timerCallBack(timestamp) {
		var drawStart = (timestamp < 1e12 ? // New HTML5 high resolution timer
			(drawStart = performance.now ?
			(performance.now() + performance.timing.navigationStart) : Date.now()) :
			// Integer milliseconds since unix epoch
			timestamp || new Date().getTime());
		if (drawStart - animationStartTime >= 1000) {
			plugin._updateTargets();
			animationStartTime = drawStart;
		}
		requestAnimationFrame(timerCallBack);
	}
	var requestAnimationFrame = window.requestAnimationFrame ||
		window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame ||
		window.oRequestAnimationFrame || window.msRequestAnimationFrame || null;
		// This is when we expect a fall-back to setInterval as it's much more fluid
	var animationStartTime = 0;
	if (!requestAnimationFrame || $.noRequestAnimationFrame) {
		$.noRequestAnimationFrame = null;
		setInterval(function() { plugin._updateTargets(); }, 980); // Fall back to good old setInterval
	}
	else {
		animationStartTime = window.animationStartTime ||
			window.webkitAnimationStartTime || window.mozAnimationStartTime ||
			window.oAnimationStartTime || window.msAnimationStartTime || new Date().getTime();
		requestAnimationFrame(timerCallBack);
	}
}

var Y = 0; // Years
var O = 1; // Months
var W = 2; // Weeks
var D = 3; // Days
var H = 4; // Hours
var M = 5; // Minutes
var S = 6; // Seconds

$.extend(Countdown.prototype, {
	/* Class name added to elements to indicate already configured with countdown. */
	markerClassName: 'hasCountdown',
	/* Name of the data property for instance settings. */
	propertyName: 'countdown',

	/* Class name for the right-to-left marker. */
	_rtlClass: 'countdown_rtl',
	/* Class name for the countdown section marker. */
	_sectionClass: 'countdown_section',
	/* Class name for the period amount marker. */
	_amountClass: 'countdown_amount',
	/* Class name for the countdown row marker. */
	_rowClass: 'countdown_row',
	/* Class name for the holding countdown marker. */
	_holdingClass: 'countdown_holding',
	/* Class name for the showing countdown marker. */
	_showClass: 'countdown_show',
	/* Class name for the description marker. */
	_descrClass: 'countdown_descr',

	/* List of currently active countdown targets. */
	_timerTargets: [],
	
	/* Override the default settings for all instances of the countdown widget.
	   @param  options  (object) the new settings to use as defaults */
	setDefaults: function(options) {
		this._resetExtraLabels(this._defaults, options);
		$.extend(this._defaults, options || {});
	},

	/* Convert a date/time to UTC.
	   @param  tz     (number) the hour or minute offset from GMT, e.g. +9, -360
	   @param  year   (Date) the date/time in that timezone or
	                  (number) the year in that timezone
	   @param  month  (number, optional) the month (0 - 11) (omit if year is a Date)
	   @param  day    (number, optional) the day (omit if year is a Date)
	   @param  hours  (number, optional) the hour (omit if year is a Date)
	   @param  mins   (number, optional) the minute (omit if year is a Date)
	   @param  secs   (number, optional) the second (omit if year is a Date)
	   @param  ms     (number, optional) the millisecond (omit if year is a Date)
	   @return  (Date) the equivalent UTC date/time */
	UTCDate: function(tz, year, month, day, hours, mins, secs, ms) {
		if (typeof year == 'object' && year.constructor == Date) {
			ms = year.getMilliseconds();
			secs = year.getSeconds();
			mins = year.getMinutes();
			hours = year.getHours();
			day = year.getDate();
			month = year.getMonth();
			year = year.getFullYear();
		}
		var d = new Date();
		d.setUTCFullYear(year);
		d.setUTCDate(1);
		d.setUTCMonth(month || 0);
		d.setUTCDate(day || 1);
		d.setUTCHours(hours || 0);
		d.setUTCMinutes((mins || 0) - (Math.abs(tz) < 30 ? tz * 60 : tz));
		d.setUTCSeconds(secs || 0);
		d.setUTCMilliseconds(ms || 0);
		return d;
	},

	/* Convert a set of periods into seconds.
	   Averaged for months and years.
	   @param  periods  (number[7]) the periods per year/month/week/day/hour/minute/second
	   @return  (number) the corresponding number of seconds */
	periodsToSeconds: function(periods) {
		return periods[0] * 31557600 + periods[1] * 2629800 + periods[2] * 604800 +
			periods[3] * 86400 + periods[4] * 3600 + periods[5] * 60 + periods[6];
	},

	/* Attach the countdown widget to a div.
	   @param  target   (element) the containing division
	   @param  options  (object) the initial settings for the countdown */
	_attachPlugin: function(target, options) {
		target = $(target);
		if (target.hasClass(this.markerClassName)) {
			return;
		}
		var inst = {options: $.extend({}, this._defaults), _periods: [0, 0, 0, 0, 0, 0, 0]};
		target.addClass(this.markerClassName).data(this.propertyName, inst);
		this._optionPlugin(target, options);
	},

	/* Add a target to the list of active ones.
	   @param  target  (element) the countdown target */
	_addTarget: function(target) {
		if (!this._hasTarget(target)) {
			this._timerTargets.push(target);
		}
	},

	/* See if a target is in the list of active ones.
	   @param  target  (element) the countdown target
	   @return  (boolean) true if present, false if not */
	_hasTarget: function(target) {
		return ($.inArray(target, this._timerTargets) > -1);
	},

	/* Remove a target from the list of active ones.
	   @param  target  (element) the countdown target */
	_removeTarget: function(target) {
		this._timerTargets = $.map(this._timerTargets,
			function(value) { return (value == target ? null : value); }); // delete entry
	},

	/* Update each active timer target. */
	_updateTargets: function() {
		for (var i = this._timerTargets.length - 1; i >= 0; i--) {
			this._updateCountdown(this._timerTargets[i]);
		}
	},

	/* Reconfigure the settings for a countdown div.
	   @param  target   (element) the control to affect
	   @param  options  (object) the new options for this instance or
	                    (string) an individual property name
	   @param  value    (any) the individual property value (omit if options
	                    is an object or to retrieve the value of a setting)
	   @return  (any) if retrieving a value */
	_optionPlugin: function(target, options, value) {
		target = $(target);
		var inst = target.data(this.propertyName);
		if (!options || (typeof options == 'string' && value == null)) { // Get option
			var name = options;
			options = (inst || {}).options;
			return (options && name ? options[name] : options);
		}

		if (!target.hasClass(this.markerClassName)) {
			return;
		}
		options = options || {};
		if (typeof options == 'string') {
			var name = options;
			options = {};
			options[name] = value;
		}
		this._resetExtraLabels(inst.options, options);
		var timezoneChanged = (inst.options.timezone != options.timezone);
		$.extend(inst.options, options);
		this._adjustSettings(target, inst,
			options.until != null || options.since != null || timezoneChanged);
		var now = new Date();
		if ((inst._since && inst._since < now) || (inst._until && inst._until > now)) {
			this._addTarget(target[0]);
		}
		this._updateCountdown(target, inst);
	},

	/* Redisplay the countdown with an updated display.
	   @param  target  (jQuery) the containing division
	   @param  inst    (object) the current settings for this instance */
	_updateCountdown: function(target, inst) {
		var $target = $(target);
		inst = inst || $target.data(this.propertyName);
		if (!inst) {
			return;
		}
		$target.html(this._generateHTML(inst)).toggleClass(this._rtlClass, inst.options.isRTL);
		if ($.isFunction(inst.options.onTick)) {
			var periods = inst._hold != 'lap' ? inst._periods :
				this._calculatePeriods(inst, inst._show, inst.options.significant, new Date());
			if (inst.options.tickInterval == 1 ||
					this.periodsToSeconds(periods) % inst.options.tickInterval == 0) {
				inst.options.onTick.apply(target, [periods]);
			}
		}
		var expired = inst._hold != 'pause' &&
			(inst._since ? inst._now.getTime() < inst._since.getTime() :
			inst._now.getTime() >= inst._until.getTime());
		if (expired && !inst._expiring) {
			inst._expiring = true;
			if (this._hasTarget(target) || inst.options.alwaysExpire) {
				this._removeTarget(target);
				if ($.isFunction(inst.options.onExpiry)) {
					inst.options.onExpiry.apply(target, []);
				}
				if (inst.options.expiryText) {
					var layout = inst.options.layout;
					inst.options.layout = inst.options.expiryText;
					this._updateCountdown(target, inst);
					inst.options.layout = layout;
				}
				if (inst.options.expiryUrl) {
					window.location = inst.options.expiryUrl;
				}
			}
			inst._expiring = false;
		}
		else if (inst._hold == 'pause') {
			this._removeTarget(target);
		}
		$target.data(this.propertyName, inst);
	},

	/* Reset any extra labelsn and compactLabelsn entries if changing labels.
	   @param  base     (object) the options to be updated
	   @param  options  (object) the new option values */
	_resetExtraLabels: function(base, options) {
		var changingLabels = false;
		for (var n in options) {
			if (n != 'whichLabels' && n.match(/[Ll]abels/)) {
				changingLabels = true;
				break;
			}
		}
		if (changingLabels) {
			for (var n in base) { // Remove custom numbered labels
				if (n.match(/[Ll]abels[02-9]|compactLabels1/)) {
					base[n] = null;
				}
			}
		}
	},
	
	/* Calculate interal settings for an instance.
	   @param  target  (element) the containing division
	   @param  inst    (object) the current settings for this instance
	   @param  recalc  (boolean) true if until or since are set */
	_adjustSettings: function(target, inst, recalc) {
		var now;
		var serverOffset = 0;
		var serverEntry = null;
		for (var i = 0; i < this._serverSyncs.length; i++) {
			if (this._serverSyncs[i][0] == inst.options.serverSync) {
				serverEntry = this._serverSyncs[i][1];
				break;
			}
		}
		if (serverEntry != null) {
			serverOffset = (inst.options.serverSync ? serverEntry : 0);
			now = new Date();
		}
		else {
			var serverResult = ($.isFunction(inst.options.serverSync) ?
				inst.options.serverSync.apply(target, []) : null);
			now = new Date();
			serverOffset = (serverResult ? now.getTime() - serverResult.getTime() : 0);
			this._serverSyncs.push([inst.options.serverSync, serverOffset]);
		}
		var timezone = inst.options.timezone;
		timezone = (timezone == null ? -now.getTimezoneOffset() : timezone);
		if (recalc || (!recalc && inst._until == null && inst._since == null)) {
			inst._since = inst.options.since;
			if (inst._since != null) {
				inst._since = this.UTCDate(timezone, this._determineTime(inst._since, null));
				if (inst._since && serverOffset) {
					inst._since.setMilliseconds(inst._since.getMilliseconds() + serverOffset);
				}
			}
			inst._until = this.UTCDate(timezone, this._determineTime(inst.options.until, now));
			if (serverOffset) {
				inst._until.setMilliseconds(inst._until.getMilliseconds() + serverOffset);
			}
		}
		inst._show = this._determineShow(inst);
	},

	/* Remove the countdown widget from a div.
	   @param  target  (element) the containing division */
	_destroyPlugin: function(target) {
		target = $(target);
		if (!target.hasClass(this.markerClassName)) {
			return;
		}
		this._removeTarget(target[0]);
		target.removeClass(this.markerClassName).empty().removeData(this.propertyName);
	},

	/* Pause a countdown widget at the current time.
	   Stop it running but remember and display the current time.
	   @param  target  (element) the containing division */
	_pausePlugin: function(target) {
		this._hold(target, 'pause');
	},

	/* Pause a countdown widget at the current time.
	   Stop the display but keep the countdown running.
	   @param  target  (element) the containing division */
	_lapPlugin: function(target) {
		this._hold(target, 'lap');
	},

	/* Resume a paused countdown widget.
	   @param  target  (element) the containing division */
	_resumePlugin: function(target) {
		this._hold(target, null);
	},

	/* Pause or resume a countdown widget.
	   @param  target  (element) the containing division
	   @param  hold    (string) the new hold setting */
	_hold: function(target, hold) {
		var inst = $.data(target, this.propertyName);
		if (inst) {
			if (inst._hold == 'pause' && !hold) {
				inst._periods = inst._savePeriods;
				var sign = (inst._since ? '-' : '+');
				inst[inst._since ? '_since' : '_until'] =
					this._determineTime(sign + inst._periods[0] + 'y' +
						sign + inst._periods[1] + 'o' + sign + inst._periods[2] + 'w' +
						sign + inst._periods[3] + 'd' + sign + inst._periods[4] + 'h' + 
						sign + inst._periods[5] + 'm' + sign + inst._periods[6] + 's');
				this._addTarget(target);
			}
			inst._hold = hold;
			inst._savePeriods = (hold == 'pause' ? inst._periods : null);
			$.data(target, this.propertyName, inst);
			this._updateCountdown(target, inst);
		}
	},

	/* Return the current time periods.
	   @param  target  (element) the containing division
	   @return  (number[7]) the current periods for the countdown */
	_getTimesPlugin: function(target) {
		var inst = $.data(target, this.propertyName);
		return (!inst ? null : (inst._hold == 'pause' ? inst._savePeriods : (!inst._hold ? inst._periods :
			this._calculatePeriods(inst, inst._show, inst.options.significant, new Date()))));
	},

	/* A time may be specified as an exact value or a relative one.
	   @param  setting      (string or number or Date) - the date/time value
	                        as a relative or absolute value
	   @param  defaultTime  (Date) the date/time to use if no other is supplied
	   @return  (Date) the corresponding date/time */
	_determineTime: function(setting, defaultTime) {
		var offsetNumeric = function(offset) { // e.g. +300, -2
			var time = new Date();
			time.setTime(time.getTime() + offset * 1000);
			return time;
		};
		var offsetString = function(offset) { // e.g. '+2d', '-4w', '+3h +30m'
			offset = offset.toLowerCase();
			var time = new Date();
			var year = time.getFullYear();
			var month = time.getMonth();
			var day = time.getDate();
			var hour = time.getHours();
			var minute = time.getMinutes();
			var second = time.getSeconds();
			var pattern = /([+-]?[0-9]+)\s*(s|m|h|d|w|o|y)?/g;
			var matches = pattern.exec(offset);
			while (matches) {
				switch (matches[2] || 's') {
					case 's': second += parseInt(matches[1], 10); break;
					case 'm': minute += parseInt(matches[1], 10); break;
					case 'h': hour += parseInt(matches[1], 10); break;
					case 'd': day += parseInt(matches[1], 10); break;
					case 'w': day += parseInt(matches[1], 10) * 7; break;
					case 'o':
						month += parseInt(matches[1], 10); 
						day = Math.min(day, plugin._getDaysInMonth(year, month));
						break;
					case 'y':
						year += parseInt(matches[1], 10);
						day = Math.min(day, plugin._getDaysInMonth(year, month));
						break;
				}
				matches = pattern.exec(offset);
			}
			return new Date(year, month, day, hour, minute, second, 0);
		};
		var time = (setting == null ? defaultTime :
			(typeof setting == 'string' ? offsetString(setting) :
			(typeof setting == 'number' ? offsetNumeric(setting) : setting)));
		if (time) time.setMilliseconds(0);
		return time;
	},

	/* Determine the number of days in a month.
	   @param  year   (number) the year
	   @param  month  (number) the month
	   @return  (number) the days in that month */
	_getDaysInMonth: function(year, month) {
		return 32 - new Date(year, month, 32).getDate();
	},

	/* Determine which set of labels should be used for an amount.
	   @param  num  (number) the amount to be displayed
	   @return  (number) the set of labels to be used for this amount */
	_normalLabels: function(num) {
		return num;
	},

	/* Generate the HTML to display the countdown widget.
	   @param  inst  (object) the current settings for this instance
	   @return  (string) the new HTML for the countdown display */
	_generateHTML: function(inst) {
		var self = this;
		// Determine what to show
		inst._periods = (inst._hold ? inst._periods :
			this._calculatePeriods(inst, inst._show, inst.options.significant, new Date()));
		// Show all 'asNeeded' after first non-zero value
		var shownNonZero = false;
		var showCount = 0;
		var sigCount = inst.options.significant;
		var show = $.extend({}, inst._show);
		for (var period = Y; period <= S; period++) {
			shownNonZero |= (inst._show[period] == '?' && inst._periods[period] > 0);
			show[period] = (inst._show[period] == '?' && !shownNonZero ? null : inst._show[period]);
			showCount += (show[period] ? 1 : 0);
			sigCount -= (inst._periods[period] > 0 ? 1 : 0);
		}
		var showSignificant = [false, false, false, false, false, false, false];
		for (var period = S; period >= Y; period--) { // Determine significant periods
			if (inst._show[period]) {
				if (inst._periods[period]) {
					showSignificant[period] = true;
				}
				else {
					showSignificant[period] = sigCount > 0;
					sigCount--;
				}
			}
		}
		var labels = (inst.options.compact ? inst.options.compactLabels : inst.options.labels);
		var whichLabels = inst.options.whichLabels || this._normalLabels;
		var showCompact = function(period) {
			var labelsNum = inst.options['compactLabels' + whichLabels(inst._periods[period])];
			return (show[period] ? self._translateDigits(inst, inst._periods[period]) +
				(labelsNum ? labelsNum[period] : labels[period]) + ' ' : '');
		};
		var showFull = function(period) {
			var labelsNum = inst.options['labels' + whichLabels(inst._periods[period])];
			return ((!inst.options.significant && show[period]) ||
				(inst.options.significant && showSignificant[period]) ?
				'<span class="' + plugin._sectionClass + '">' +
				'<span class="' + plugin._amountClass + '">' +
				self._translateDigits(inst, inst._periods[period]) + '</span><br/>' +
				(labelsNum ? labelsNum[period] : labels[period]) + '</span>' : '');
		};
		return (inst.options.layout ? this._buildLayout(inst, show, inst.options.layout,
			inst.options.compact, inst.options.significant, showSignificant) :
			((inst.options.compact ? // Compact version
			'<span class="' + this._rowClass + ' ' + this._amountClass +
			(inst._hold ? ' ' + this._holdingClass : '') + '">' + 
			showCompact(Y) + showCompact(O) + showCompact(W) + showCompact(D) + 
			(show[H] ? this._minDigits(inst, inst._periods[H], 2) : '') +
			(show[M] ? (show[H] ? inst.options.timeSeparator : '') +
			this._minDigits(inst, inst._periods[M], 2) : '') +
			(show[S] ? (show[H] || show[M] ? inst.options.timeSeparator : '') +
			this._minDigits(inst, inst._periods[S], 2) : '') :
			// Full version
			'<span class="' + this._rowClass + ' ' + this._showClass + (inst.options.significant || showCount) +
			(inst._hold ? ' ' + this._holdingClass : '') + '">' +
			showFull(Y) + showFull(O) + showFull(W) + showFull(D) +
			showFull(H) + showFull(M) + showFull(S)) + '</span>' +
			(inst.options.description ? '<span class="' + this._rowClass + ' ' + this._descrClass + '">' +
			inst.options.description + '</span>' : '')));
	},

	/* Construct a custom layout.
	   @param  inst             (object) the current settings for this instance
	   @param  show             (string[7]) flags indicating which periods are requested
	   @param  layout           (string) the customised layout
	   @param  compact          (boolean) true if using compact labels
	   @param  significant      (number) the number of periods with values to show, zero for all
	   @param  showSignificant  (boolean[7]) other periods to show for significance
	   @return  (string) the custom HTML */
	_buildLayout: function(inst, show, layout, compact, significant, showSignificant) {
		var labels = inst.options[compact ? 'compactLabels' : 'labels'];
		var whichLabels = inst.options.whichLabels || this._normalLabels;
		var labelFor = function(index) {
			return (inst.options[(compact ? 'compactLabels' : 'labels') +
				whichLabels(inst._periods[index])] || labels)[index];
		};
		var digit = function(value, position) {
			return inst.options.digits[Math.floor(value / position) % 10];
		};
		var subs = {desc: inst.options.description, sep: inst.options.timeSeparator,
			yl: labelFor(Y), yn: this._minDigits(inst, inst._periods[Y], 1),
			ynn: this._minDigits(inst, inst._periods[Y], 2),
			ynnn: this._minDigits(inst, inst._periods[Y], 3), y1: digit(inst._periods[Y], 1),
			y10: digit(inst._periods[Y], 10), y100: digit(inst._periods[Y], 100),
			y1000: digit(inst._periods[Y], 1000),
			ol: labelFor(O), on: this._minDigits(inst, inst._periods[O], 1),
			onn: this._minDigits(inst, inst._periods[O], 2),
			onnn: this._minDigits(inst, inst._periods[O], 3), o1: digit(inst._periods[O], 1),
			o10: digit(inst._periods[O], 10), o100: digit(inst._periods[O], 100),
			o1000: digit(inst._periods[O], 1000),
			wl: labelFor(W), wn: this._minDigits(inst, inst._periods[W], 1),
			wnn: this._minDigits(inst, inst._periods[W], 2),
			wnnn: this._minDigits(inst, inst._periods[W], 3), w1: digit(inst._periods[W], 1),
			w10: digit(inst._periods[W], 10), w100: digit(inst._periods[W], 100),
			w1000: digit(inst._periods[W], 1000),
			dl: labelFor(D), dn: this._minDigits(inst, inst._periods[D], 1),
			dnn: this._minDigits(inst, inst._periods[D], 2),
			dnnn: this._minDigits(inst, inst._periods[D], 3), d1: digit(inst._periods[D], 1),
			d10: digit(inst._periods[D], 10), d100: digit(inst._periods[D], 100),
			d1000: digit(inst._periods[D], 1000),
			hl: labelFor(H), hn: this._minDigits(inst, inst._periods[H], 1),
			hnn: this._minDigits(inst, inst._periods[H], 2),
			hnnn: this._minDigits(inst, inst._periods[H], 3), h1: digit(inst._periods[H], 1),
			h10: digit(inst._periods[H], 10), h100: digit(inst._periods[H], 100),
			h1000: digit(inst._periods[H], 1000),
			ml: labelFor(M), mn: this._minDigits(inst, inst._periods[M], 1),
			mnn: this._minDigits(inst, inst._periods[M], 2),
			mnnn: this._minDigits(inst, inst._periods[M], 3), m1: digit(inst._periods[M], 1),
			m10: digit(inst._periods[M], 10), m100: digit(inst._periods[M], 100),
			m1000: digit(inst._periods[M], 1000),
			sl: labelFor(S), sn: this._minDigits(inst, inst._periods[S], 1),
			snn: this._minDigits(inst, inst._periods[S], 2),
			snnn: this._minDigits(inst, inst._periods[S], 3), s1: digit(inst._periods[S], 1),
			s10: digit(inst._periods[S], 10), s100: digit(inst._periods[S], 100),
			s1000: digit(inst._periods[S], 1000)};
		var html = layout;
		// Replace period containers: {p<}...{p>}
		for (var i = Y; i <= S; i++) {
			var period = 'yowdhms'.charAt(i);
			var re = new RegExp('\\{' + period + '<\\}(.*)\\{' + period + '>\\}', 'g');
			html = html.replace(re, ((!significant && show[i]) ||
				(significant && showSignificant[i]) ? '$1' : ''));
		}
		// Replace period values: {pn}
		$.each(subs, function(n, v) {
			var re = new RegExp('\\{' + n + '\\}', 'g');
			html = html.replace(re, v);
		});
		return html;
	},

	/* Ensure a numeric value has at least n digits for display.
	   @param  inst   (object) the current settings for this instance
	   @param  value  (number) the value to display
	   @param  len    (number) the minimum length
	   @return  (string) the display text */
	_minDigits: function(inst, value, len) {
		value = '' + value;
		if (value.length >= len) {
			return this._translateDigits(inst, value);
		}
		value = '0000000000' + value;
		return this._translateDigits(inst, value.substr(value.length - len));
	},

	/* Translate digits into other representations.
	   @param  inst   (object) the current settings for this instance
	   @param  value  (string) the text to translate
	   @return  (string) the translated text */
	_translateDigits: function(inst, value) {
		return ('' + value).replace(/[0-9]/g, function(digit) {
				return inst.options.digits[digit];
			});
	},

	/* Translate the format into flags for each period.
	   @param  inst  (object) the current settings for this instance
	   @return  (string[7]) flags indicating which periods are requested (?) or
	            required (!) by year, month, week, day, hour, minute, second */
	_determineShow: function(inst) {
		var format = inst.options.format;
		var show = [];
		show[Y] = (format.match('y') ? '?' : (format.match('Y') ? '!' : null));
		show[O] = (format.match('o') ? '?' : (format.match('O') ? '!' : null));
		show[W] = (format.match('w') ? '?' : (format.match('W') ? '!' : null));
		show[D] = (format.match('d') ? '?' : (format.match('D') ? '!' : null));
		show[H] = (format.match('h') ? '?' : (format.match('H') ? '!' : null));
		show[M] = (format.match('m') ? '?' : (format.match('M') ? '!' : null));
		show[S] = (format.match('s') ? '?' : (format.match('S') ? '!' : null));
		return show;
	},
	
	/* Calculate the requested periods between now and the target time.
	   @param  inst         (object) the current settings for this instance
	   @param  show         (string[7]) flags indicating which periods are requested/required
	   @param  significant  (number) the number of periods with values to show, zero for all
	   @param  now          (Date) the current date and time
	   @return  (number[7]) the current time periods (always positive)
	            by year, month, week, day, hour, minute, second */
	_calculatePeriods: function(inst, show, significant, now) {
		// Find endpoints
		inst._now = now;
		inst._now.setMilliseconds(0);
		var until = new Date(inst._now.getTime());
		if (inst._since) {
			if (now.getTime() < inst._since.getTime()) {
				inst._now = now = until;
			}
			else {
				now = inst._since;
			}
		}
		else {
			until.setTime(inst._until.getTime());
			if (now.getTime() > inst._until.getTime()) {
				inst._now = now = until;
			}
		}
		// Calculate differences by period
		var periods = [0, 0, 0, 0, 0, 0, 0];
		if (show[Y] || show[O]) {
			// Treat end of months as the same
			var lastNow = plugin._getDaysInMonth(now.getFullYear(), now.getMonth());
			var lastUntil = plugin._getDaysInMonth(until.getFullYear(), until.getMonth());
			var sameDay = (until.getDate() == now.getDate() ||
				(until.getDate() >= Math.min(lastNow, lastUntil) &&
				now.getDate() >= Math.min(lastNow, lastUntil)));
			var getSecs = function(date) {
				return (date.getHours() * 60 + date.getMinutes()) * 60 + date.getSeconds();
			};
			var months = Math.max(0,
				(until.getFullYear() - now.getFullYear()) * 12 + until.getMonth() - now.getMonth() +
				((until.getDate() < now.getDate() && !sameDay) ||
				(sameDay && getSecs(until) < getSecs(now)) ? -1 : 0));
			periods[Y] = (show[Y] ? Math.floor(months / 12) : 0);
			periods[O] = (show[O] ? months - periods[Y] * 12 : 0);
			// Adjust for months difference and end of month if necessary
			now = new Date(now.getTime());
			var wasLastDay = (now.getDate() == lastNow);
			var lastDay = plugin._getDaysInMonth(now.getFullYear() + periods[Y],
				now.getMonth() + periods[O]);
			if (now.getDate() > lastDay) {
				now.setDate(lastDay);
			}
			now.setFullYear(now.getFullYear() + periods[Y]);
			now.setMonth(now.getMonth() + periods[O]);
			if (wasLastDay) {
				now.setDate(lastDay);
			}
		}
		var diff = Math.floor((until.getTime() - now.getTime()) / 1000);
		var extractPeriod = function(period, numSecs) {
			periods[period] = (show[period] ? Math.floor(diff / numSecs) : 0);
			diff -= periods[period] * numSecs;
		};
		extractPeriod(W, 604800);
		extractPeriod(D, 86400);
		extractPeriod(H, 3600);
		extractPeriod(M, 60);
		extractPeriod(S, 1);
		if (diff > 0 && !inst._since) { // Round up if left overs
			var multiplier = [1, 12, 4.3482, 7, 24, 60, 60];
			var lastShown = S;
			var max = 1;
			for (var period = S; period >= Y; period--) {
				if (show[period]) {
					if (periods[lastShown] >= max) {
						periods[lastShown] = 0;
						diff = 1;
					}
					if (diff > 0) {
						periods[period]++;
						diff = 0;
						lastShown = period;
						max = 1;
					}
				}
				max *= multiplier[period];
			}
		}
		if (significant) { // Zero out insignificant periods
			for (var period = Y; period <= S; period++) {
				if (significant && periods[period]) {
					significant--;
				}
				else if (!significant) {
					periods[period] = 0;
				}
			}
		}
		return periods;
	}
});

// The list of commands that return values and don't permit chaining
var getters = ['getTimes'];

/* Determine whether a command is a getter and doesn't permit chaining.
   @param  command    (string, optional) the command to run
   @param  otherArgs  ([], optional) any other arguments for the command
   @return  true if the command is a getter, false if not */
function isNotChained(command, otherArgs) {
	if (command == 'option' && (otherArgs.length == 0 ||
			(otherArgs.length == 1 && typeof otherArgs[0] == 'string'))) {
		return true;
	}
	return $.inArray(command, getters) > -1;
}

/* Process the countdown functionality for a jQuery selection.
   @param  options  (object) the new settings to use for these instances (optional) or
                    (string) the command to run (optional)
   @return  (jQuery) for chaining further calls or
            (any) getter value */
$.fn.countdown = function(options) {
	var otherArgs = Array.prototype.slice.call(arguments, 1);
	if (isNotChained(options, otherArgs)) {
		return plugin['_' + options + 'Plugin'].
			apply(plugin, [this[0]].concat(otherArgs));
	}
	return this.each(function() {
		if (typeof options == 'string') {
			if (!plugin['_' + options + 'Plugin']) {
				throw 'Unknown command: ' + options;
			}
			plugin['_' + options + 'Plugin'].
				apply(plugin, [this].concat(otherArgs));
		}
		else {
			plugin._attachPlugin(this, options || {});
		}
	});
};

/* Initialise the countdown functionality. */
var plugin = $.countdown = new Countdown(); // Singleton instance

})(jQuery);

/* http://keith-wood.name/countdown.html
   German initialisation for the jQuery countdown extension
   Written by Samuel Wulf. */
(function($) {
	$.countdown.regional['de'] = {
		labels: ['Jahre', 'Monate', 'Wochen', 'Tage', 'Stunden', 'Minuten', 'Sekunden'],
		labels1: ['Jahr', 'Monat', 'Woche', 'Tag', 'Stunde', 'Minute', 'Sekunde'],
		compactLabels: ['J', 'M', 'W', 'T'],
		whichLabels: null,
		digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],
		timeSeparator: ':', isRTL: false};
	$.countdown.setDefaults($.countdown.regional['de']);
})(jQuery);

/* Placeholders.js v3.0.2 */
(function(t){"use strict";function e(t,e,r){return t.addEventListener?t.addEventListener(e,r,!1):t.attachEvent?t.attachEvent("on"+e,r):void 0}function r(t,e){var r,n;for(r=0,n=t.length;n>r;r++)if(t[r]===e)return!0;return!1}function n(t,e){var r;t.createTextRange?(r=t.createTextRange(),r.move("character",e),r.select()):t.selectionStart&&(t.focus(),t.setSelectionRange(e,e))}function a(t,e){try{return t.type=e,!0}catch(r){return!1}}t.Placeholders={Utils:{addEventListener:e,inArray:r,moveCaret:n,changeType:a}}})(this),function(t){"use strict";function e(){}function r(){try{return document.activeElement}catch(t){}}function n(t,e){var r,n,a=!!e&&t.value!==e,u=t.value===t.getAttribute(V);return(a||u)&&"true"===t.getAttribute(D)?(t.removeAttribute(D),t.value=t.value.replace(t.getAttribute(V),""),t.className=t.className.replace(R,""),n=t.getAttribute(F),parseInt(n,10)>=0&&(t.setAttribute("maxLength",n),t.removeAttribute(F)),r=t.getAttribute(P),r&&(t.type=r),!0):!1}function a(t){var e,r,n=t.getAttribute(V);return""===t.value&&n?(t.setAttribute(D,"true"),t.value=n,t.className+=" "+I,r=t.getAttribute(F),r||(t.setAttribute(F,t.maxLength),t.removeAttribute("maxLength")),e=t.getAttribute(P),e?t.type="text":"password"===t.type&&M.changeType(t,"text")&&t.setAttribute(P,"password"),!0):!1}function u(t,e){var r,n,a,u,i,l,o;if(t&&t.getAttribute(V))e(t);else for(a=t?t.getElementsByTagName("input"):b,u=t?t.getElementsByTagName("textarea"):f,r=a?a.length:0,n=u?u.length:0,o=0,l=r+n;l>o;o++)i=r>o?a[o]:u[o-r],e(i)}function i(t){u(t,n)}function l(t){u(t,a)}function o(t){return function(){m&&t.value===t.getAttribute(V)&&"true"===t.getAttribute(D)?M.moveCaret(t,0):n(t)}}function c(t){return function(){a(t)}}function s(t){return function(e){return A=t.value,"true"===t.getAttribute(D)&&A===t.getAttribute(V)&&M.inArray(C,e.keyCode)?(e.preventDefault&&e.preventDefault(),!1):void 0}}function d(t){return function(){n(t,A),""===t.value&&(t.blur(),M.moveCaret(t,0))}}function g(t){return function(){t===r()&&t.value===t.getAttribute(V)&&"true"===t.getAttribute(D)&&M.moveCaret(t,0)}}function v(t){return function(){i(t)}}function p(t){t.form&&(T=t.form,"string"==typeof T&&(T=document.getElementById(T)),T.getAttribute(U)||(M.addEventListener(T,"submit",v(T)),T.setAttribute(U,"true"))),M.addEventListener(t,"focus",o(t)),M.addEventListener(t,"blur",c(t)),m&&(M.addEventListener(t,"keydown",s(t)),M.addEventListener(t,"keyup",d(t)),M.addEventListener(t,"click",g(t))),t.setAttribute(j,"true"),t.setAttribute(V,x),(m||t!==r())&&a(t)}var b,f,m,h,A,y,E,x,L,T,N,S,w,B=["text","search","url","tel","email","password","number","textarea"],C=[27,33,34,35,36,37,38,39,40,8,46],k="#ccc",I="placeholdersjs",R=RegExp("(?:^|\\s)"+I+"(?!\\S)"),V="data-placeholder-value",D="data-placeholder-active",P="data-placeholder-type",U="data-placeholder-submit",j="data-placeholder-bound",q="data-placeholder-focus",z="data-placeholder-live",F="data-placeholder-maxlength",G=document.createElement("input"),H=document.getElementsByTagName("head")[0],J=document.documentElement,K=t.Placeholders,M=K.Utils;if(K.nativeSupport=void 0!==G.placeholder,!K.nativeSupport){for(b=document.getElementsByTagName("input"),f=document.getElementsByTagName("textarea"),m="false"===J.getAttribute(q),h="false"!==J.getAttribute(z),y=document.createElement("style"),y.type="text/css",E=document.createTextNode("."+I+" { color:"+k+"; }"),y.styleSheet?y.styleSheet.cssText=E.nodeValue:y.appendChild(E),H.insertBefore(y,H.firstChild),w=0,S=b.length+f.length;S>w;w++)N=b.length>w?b[w]:f[w-b.length],x=N.attributes.placeholder,x&&(x=x.nodeValue,x&&M.inArray(B,N.type)&&p(N));L=setInterval(function(){for(w=0,S=b.length+f.length;S>w;w++)N=b.length>w?b[w]:f[w-b.length],x=N.attributes.placeholder,x?(x=x.nodeValue,x&&M.inArray(B,N.type)&&(N.getAttribute(j)||p(N),(x!==N.getAttribute(V)||"password"===N.type&&!N.getAttribute(P))&&("password"===N.type&&!N.getAttribute(P)&&M.changeType(N,"text")&&N.setAttribute(P,"password"),N.value===N.getAttribute(V)&&(N.value=x),N.setAttribute(V,x)))):N.getAttribute(D)&&(n(N),N.removeAttribute(V));h||clearInterval(L)},100)}M.addEventListener(t,"beforeunload",function(){K.disable()}),K.disable=K.nativeSupport?e:i,K.enable=K.nativeSupport?e:l}(this);
/*! Backstretch - v2.0.1 - 2012-10-01
* http://srobbin.com/jquery-plugins/backstretch/
* Copyright (c) 2012 Scott Robbin; Licensed MIT */
(function(e,t,n){"use strict";e.fn.backstretch=function(r,s){return(r===n||r.length===0)&&e.error("No images were supplied for Backstretch"),e(t).scrollTop()===0&&t.scrollTo(0,0),this.each(function(){var t=e(this),n=t.data("backstretch");n&&(s=e.extend(n.options,s),n.destroy(!0)),n=new i(this,r,s),t.data("backstretch",n)})},e.backstretch=function(t,n){return e("body").backstretch(t,n).data("backstretch")},e.expr[":"].backstretch=function(t){return e(t).data("backstretch")!==n},e.fn.backstretch.defaults={centeredX:!0,centeredY:!0,duration:5e3,fade:0};var r={wrap:{left:0,top:0,overflow:"hidden",margin:0,padding:0,height:"100%",width:"100%",zIndex:-999999},img:{position:"absolute",display:"none",margin:0,padding:0,border:"none",width:"auto",height:"auto",maxWidth:"none",zIndex:-999999}},i=function(n,i,o){this.options=e.extend({},e.fn.backstretch.defaults,o||{}),this.images=e.isArray(i)?i:[i],e.each(this.images,function(){e("<img />")[0].src=this}),this.isBody=n===document.body,this.$container=e(n),this.$wrap=e('<div class="backstretch"></div>').css(r.wrap).appendTo(this.$container),this.$root=this.isBody?s?e(t):e(document):this.$container;if(!this.isBody){var u=this.$container.css("position"),a=this.$container.css("zIndex");this.$container.css({position:u==="static"?"relative":u,zIndex:a==="auto"?0:a,background:"none"}),this.$wrap.css({zIndex:-999998})}this.$wrap.css({position:this.isBody&&s?"fixed":"absolute"}),this.index=0,this.show(this.index),e(t).on("resize.backstretch",e.proxy(this.resize,this)).on("orientationchange.backstretch",e.proxy(function(){this.isBody&&t.pageYOffset===0&&(t.scrollTo(0,1),this.resize())},this))};i.prototype={resize:function(){try{var e={left:0,top:0},n=this.isBody?this.$root.width():this.$root.innerWidth(),r=n,i=this.isBody?t.innerHeight?t.innerHeight:this.$root.height():this.$root.innerHeight(),s=r/this.$img.data("ratio"),o;s>=i?(o=(s-i)/2,this.options.centeredY&&(e.top="-"+o+"px")):(s=i,r=s*this.$img.data("ratio"),o=(r-n)/2,this.options.centeredX&&(e.left="-"+o+"px")),this.$wrap.css({width:n,height:i}).find("img:not(.deleteable)").css({width:r,height:s}).css(e)}catch(u){}return this},show:function(t){if(Math.abs(t)>this.images.length-1)return;this.index=t;var n=this,i=n.$wrap.find("img").addClass("deleteable"),s=e.Event("backstretch.show",{relatedTarget:n.$container[0]});return clearInterval(n.interval),n.$img=e("<img />").css(r.img).bind("load",function(t){var r=this.width||e(t.target).width(),o=this.height||e(t.target).height();e(this).data("ratio",r/o),n.resize(),e(this).fadeIn(n.options.speed||n.options.fade,function(){i.remove(),n.paused||n.cycle(),n.$container.trigger(s)})}).appendTo(n.$wrap),n.$img.attr("src",n.images[t]),n},next:function(){return this.show(this.index<this.images.length-1?this.index+1:0)},prev:function(){return this.show(this.index===0?this.images.length-1:this.index-1)},pause:function(){return this.paused=!0,this},resume:function(){return this.paused=!1,this.next(),this},cycle:function(){return this.images.length>1&&(clearInterval(this.interval),this.interval=setInterval(e.proxy(function(){this.paused||this.next()},this),this.options.duration)),this},destroy:function(n){e(t).off("resize.backstretch orientationchange.backstretch"),clearInterval(this.interval),n||this.$wrap.remove(),this.$container.removeData("backstretch")}};var s=function(){var e=navigator.userAgent,n=navigator.platform,r=e.match(/AppleWebKit\/([0-9]+)/),i=!!r&&r[1],s=e.match(/Fennec\/([0-9]+)/),o=!!s&&s[1],u=e.match(/Opera Mobi\/([0-9]+)/),a=!!u&&u[1],f=e.match(/MSIE ([0-9]+)/),l=!!f&&f[1];return!((n.indexOf("iPhone")>-1||n.indexOf("iPad")>-1||n.indexOf("iPod")>-1)&&i&&i<534||t.operamini&&{}.toString.call(t.operamini)==="[object OperaMini]"||u&&a<7458||e.indexOf("Android")>-1&&i&&i<533||o&&o<6||"palmGetResource"in t&&i&&i<534||e.indexOf("MeeGo")>-1&&e.indexOf("NokiaBrowser/8.5.0")>-1||l&&l<=6)}()})(jQuery,window);

(function($){$.extend({tablesorter:new
function(){var parsers=[],widgets=[];this.defaults={cssHeader:"header",cssAsc:"headerSortUp",cssDesc:"headerSortDown",cssChildRow:"expand-child",sortInitialOrder:"asc",sortMultiSortKey:"shiftKey",sortForce:null,sortAppend:null,sortLocaleCompare:true,textExtraction:"simple",parsers:{},widgets:[],widgetZebra:{css:["even","odd"]},headers:{},widthFixed:false,cancelSelection:true,sortList:[],headerList:[],dateFormat:"us",decimal:'/\.|\,/g',onRenderHeader:null,selectorHeaders:'thead th',debug:false};function benchmark(s,d){log(s+","+(new Date().getTime()-d.getTime())+"ms");}this.benchmark=benchmark;function log(s){if(typeof console!="undefined"&&typeof console.debug!="undefined"){console.log(s);}else{alert(s);}}function buildParserCache(table,$headers){if(table.config.debug){var parsersDebug="";}if(table.tBodies.length==0)return;var rows=table.tBodies[0].rows;if(rows[0]){var list=[],cells=rows[0].cells,l=cells.length;for(var i=0;i<l;i++){var p=false;if($.metadata&&($($headers[i]).metadata()&&$($headers[i]).metadata().sorter)){p=getParserById($($headers[i]).metadata().sorter);}else if((table.config.headers[i]&&table.config.headers[i].sorter)){p=getParserById(table.config.headers[i].sorter);}if(!p){p=detectParserForColumn(table,rows,-1,i);}if(table.config.debug){parsersDebug+="column:"+i+" parser:"+p.id+"\n";}list.push(p);}}if(table.config.debug){log(parsersDebug);}return list;};function detectParserForColumn(table,rows,rowIndex,cellIndex){var l=parsers.length,node=false,nodeValue=false,keepLooking=true;while(nodeValue==''&&keepLooking){rowIndex++;if(rows[rowIndex]){node=getNodeFromRowAndCellIndex(rows,rowIndex,cellIndex);nodeValue=trimAndGetNodeText(table.config,node);if(table.config.debug){log('Checking if value was empty on row:'+rowIndex);}}else{keepLooking=false;}}for(var i=1;i<l;i++){if(parsers[i].is(nodeValue,table,node)){return parsers[i];}}return parsers[0];}function getNodeFromRowAndCellIndex(rows,rowIndex,cellIndex){return rows[rowIndex].cells[cellIndex];}function trimAndGetNodeText(config,node){return $.trim(getElementText(config,node));}function getParserById(name){var l=parsers.length;for(var i=0;i<l;i++){if(parsers[i].id.toLowerCase()==name.toLowerCase()){return parsers[i];}}return false;}function buildCache(table){if(table.config.debug){var cacheTime=new Date();}var totalRows=(table.tBodies[0]&&table.tBodies[0].rows.length)||0,totalCells=(table.tBodies[0].rows[0]&&table.tBodies[0].rows[0].cells.length)||0,parsers=table.config.parsers,cache={row:[],normalized:[]};for(var i=0;i<totalRows;++i){var c=$(table.tBodies[0].rows[i]),cols=[];if(c.hasClass(table.config.cssChildRow)){cache.row[cache.row.length-1]=cache.row[cache.row.length-1].add(c);continue;}cache.row.push(c);for(var j=0;j<totalCells;++j){cols.push(parsers[j].format(getElementText(table.config,c[0].cells[j]),table,c[0].cells[j]));}cols.push(cache.normalized.length);cache.normalized.push(cols);cols=null;};if(table.config.debug){benchmark("Building cache for "+totalRows+" rows:",cacheTime);}return cache;};function getElementText(config,node){var text="";if(!node)return"";if(!config.supportsTextContent)config.supportsTextContent=node.textContent||false;if(config.textExtraction=="simple"){if(config.supportsTextContent){text=node.textContent;}else{if(node.childNodes[0]&&node.childNodes[0].hasChildNodes()){text=node.childNodes[0].innerHTML;}else{text=node.innerHTML;}}}else{if(typeof(config.textExtraction)=="function"){text=config.textExtraction(node);}else{text=$(node).text();}}return text;}function appendToTable(table,cache){if(table.config.debug){var appendTime=new Date()}var c=cache,r=c.row,n=c.normalized,totalRows=n.length,checkCell=(n[0].length-1),tableBody=$(table.tBodies[0]),rows=[];for(var i=0;i<totalRows;i++){var pos=n[i][checkCell];rows.push(r[pos]);if(!table.config.appender){var l=r[pos].length;for(var j=0;j<l;j++){tableBody[0].appendChild(r[pos][j]);}}}if(table.config.appender){table.config.appender(table,rows);}rows=null;if(table.config.debug){benchmark("Rebuilt table:",appendTime);}applyWidget(table);setTimeout(function(){$(table).trigger("sortEnd");},0);};function buildHeaders(table){if(table.config.debug){var time=new Date();}var meta=($.metadata)?true:false;var header_index=computeTableHeaderCellIndexes(table);$tableHeaders=$(table.config.selectorHeaders,table).each(function(index){this.column=header_index[this.parentNode.rowIndex+"-"+this.cellIndex];this.order=formatSortingOrder(table.config.sortInitialOrder);this.count=this.order;if(checkHeaderMetadata(this)||checkHeaderOptions(table,index))this.sortDisabled=true;if(checkHeaderOptionsSortingLocked(table,index))this.order=this.lockedOrder=checkHeaderOptionsSortingLocked(table,index);if(!this.sortDisabled){var $th=$(this).addClass(table.config.cssHeader);if(table.config.onRenderHeader)table.config.onRenderHeader.apply($th);}table.config.headerList[index]=this;});if(table.config.debug){benchmark("Built headers:",time);log($tableHeaders);}return $tableHeaders;};function computeTableHeaderCellIndexes(t){var matrix=[];var lookup={};var thead=t.getElementsByTagName('THEAD')[0];var trs=thead.getElementsByTagName('TR');for(var i=0;i<trs.length;i++){var cells=trs[i].cells;for(var j=0;j<cells.length;j++){var c=cells[j];var rowIndex=c.parentNode.rowIndex;var cellId=rowIndex+"-"+c.cellIndex;var rowSpan=c.rowSpan||1;var colSpan=c.colSpan||1
var firstAvailCol;if(typeof(matrix[rowIndex])=="undefined"){matrix[rowIndex]=[];}for(var k=0;k<matrix[rowIndex].length+1;k++){if(typeof(matrix[rowIndex][k])=="undefined"){firstAvailCol=k;break;}}lookup[cellId]=firstAvailCol;for(var k=rowIndex;k<rowIndex+rowSpan;k++){if(typeof(matrix[k])=="undefined"){matrix[k]=[];}var matrixrow=matrix[k];for(var l=firstAvailCol;l<firstAvailCol+colSpan;l++){matrixrow[l]="x";}}}}return lookup;}function checkCellColSpan(table,rows,row){var arr=[],r=table.tHead.rows,c=r[row].cells;for(var i=0;i<c.length;i++){var cell=c[i];if(cell.colSpan>1){arr=arr.concat(checkCellColSpan(table,headerArr,row++));}else{if(table.tHead.length==1||(cell.rowSpan>1||!r[row+1])){arr.push(cell);}}}return arr;};function checkHeaderMetadata(cell){if(($.metadata)&&($(cell).metadata().sorter===false)){return true;};return false;}function checkHeaderOptions(table,i){if((table.config.headers[i])&&(table.config.headers[i].sorter===false)){return true;};return false;}function checkHeaderOptionsSortingLocked(table,i){if((table.config.headers[i])&&(table.config.headers[i].lockedOrder))return table.config.headers[i].lockedOrder;return false;}function applyWidget(table){var c=table.config.widgets;var l=c.length;for(var i=0;i<l;i++){getWidgetById(c[i]).format(table);}}function getWidgetById(name){var l=widgets.length;for(var i=0;i<l;i++){if(widgets[i].id.toLowerCase()==name.toLowerCase()){return widgets[i];}}};function formatSortingOrder(v){if(typeof(v)!="Number"){return(v.toLowerCase()=="desc")?1:0;}else{return(v==1)?1:0;}}function isValueInArray(v,a){var l=a.length;for(var i=0;i<l;i++){if(a[i][0]==v){return true;}}return false;}function setHeadersCss(table,$headers,list,css){$headers.removeClass(css[0]).removeClass(css[1]);var h=[];$headers.each(function(offset){if(!this.sortDisabled){h[this.column]=$(this);}});var l=list.length;for(var i=0;i<l;i++){h[list[i][0]].addClass(css[list[i][1]]);}}function fixColumnWidth(table,$headers){var c=table.config;if(c.widthFixed){var colgroup=$('<colgroup>');$("tr:first td",table.tBodies[0]).each(function(){colgroup.append($('<col>').css('width',$(this).width()));});$(table).prepend(colgroup);};}function updateHeaderSortCount(table,sortList){var c=table.config,l=sortList.length;for(var i=0;i<l;i++){var s=sortList[i],o=c.headerList[s[0]];o.count=s[1];o.count++;}}function multisort(table,sortList,cache){if(table.config.debug){var sortTime=new Date();}var dynamicExp="var sortWrapper = function(a,b) {",l=sortList.length;for(var i=0;i<l;i++){var c=sortList[i][0];var order=sortList[i][1];var s=(table.config.parsers[c].type=="text")?((order==0)?makeSortFunction("text","asc",c):makeSortFunction("text","desc",c)):((order==0)?makeSortFunction("numeric","asc",c):makeSortFunction("numeric","desc",c));var e="e"+i;dynamicExp+="var "+e+" = "+s;dynamicExp+="if("+e+") { return "+e+"; } ";dynamicExp+="else { ";}var orgOrderCol=cache.normalized[0].length-1;dynamicExp+="return a["+orgOrderCol+"]-b["+orgOrderCol+"];";for(var i=0;i<l;i++){dynamicExp+="}; ";}dynamicExp+="return 0; ";dynamicExp+="}; ";if(table.config.debug){benchmark("Evaling expression:"+dynamicExp,new Date());}eval(dynamicExp);cache.normalized.sort(sortWrapper);if(table.config.debug){benchmark("Sorting on "+sortList.toString()+" and dir "+order+" time:",sortTime);}return cache;};function makeSortFunction(type,direction,index){var a="a["+index+"]",b="b["+index+"]";if(type=='text'&&direction=='asc'){return"("+a+" == "+b+" ? 0 : ("+a+" === null ? Number.POSITIVE_INFINITY : ("+b+" === null ? Number.NEGATIVE_INFINITY : ("+a+" < "+b+") ? -1 : 1 )));";}else if(type=='text'&&direction=='desc'){return"("+a+" == "+b+" ? 0 : ("+a+" === null ? Number.POSITIVE_INFINITY : ("+b+" === null ? Number.NEGATIVE_INFINITY : ("+b+" < "+a+") ? -1 : 1 )));";}else if(type=='numeric'&&direction=='asc'){return"("+a+" === null && "+b+" === null) ? 0 :("+a+" === null ? Number.POSITIVE_INFINITY : ("+b+" === null ? Number.NEGATIVE_INFINITY : "+a+" - "+b+"));";}else if(type=='numeric'&&direction=='desc'){return"("+a+" === null && "+b+" === null) ? 0 :("+a+" === null ? Number.POSITIVE_INFINITY : ("+b+" === null ? Number.NEGATIVE_INFINITY : "+b+" - "+a+"));";}};function makeSortText(i){return"((a["+i+"] < b["+i+"]) ? -1 : ((a["+i+"] > b["+i+"]) ? 1 : 0));";};function makeSortTextDesc(i){return"((b["+i+"] < a["+i+"]) ? -1 : ((b["+i+"] > a["+i+"]) ? 1 : 0));";};function makeSortNumeric(i){return"a["+i+"]-b["+i+"];";};function makeSortNumericDesc(i){return"b["+i+"]-a["+i+"];";};function sortText(a,b){if(table.config.sortLocaleCompare)return a.localeCompare(b);return((a<b)?-1:((a>b)?1:0));};function sortTextDesc(a,b){if(table.config.sortLocaleCompare)return b.localeCompare(a);return((b<a)?-1:((b>a)?1:0));};function sortNumeric(a,b){return a-b;};function sortNumericDesc(a,b){return b-a;};function getCachedSortType(parsers,i){return parsers[i].type;};this.construct=function(settings){return this.each(function(){if(!this.tHead||!this.tBodies)return;var $this,$document,$headers,cache,config,shiftDown=0,sortOrder;this.config={};config=$.extend(this.config,$.tablesorter.defaults,settings);$this=$(this);$.data(this,"tablesorter",config);$headers=buildHeaders(this);this.config.parsers=buildParserCache(this,$headers);cache=buildCache(this);var sortCSS=[config.cssDesc,config.cssAsc];fixColumnWidth(this);$headers.click(function(e){var totalRows=($this[0].tBodies[0]&&$this[0].tBodies[0].rows.length)||0;if(!this.sortDisabled&&totalRows>0){$this.trigger("sortStart");var $cell=$(this);var i=this.column;this.order=this.count++%2;if(this.lockedOrder)this.order=this.lockedOrder;if(!e[config.sortMultiSortKey]){config.sortList=[];if(config.sortForce!=null){var a=config.sortForce;for(var j=0;j<a.length;j++){if(a[j][0]!=i){config.sortList.push(a[j]);}}}config.sortList.push([i,this.order]);}else{if(isValueInArray(i,config.sortList)){for(var j=0;j<config.sortList.length;j++){var s=config.sortList[j],o=config.headerList[s[0]];if(s[0]==i){o.count=s[1];o.count++;s[1]=o.count%2;}}}else{config.sortList.push([i,this.order]);}};setTimeout(function(){setHeadersCss($this[0],$headers,config.sortList,sortCSS);appendToTable($this[0],multisort($this[0],config.sortList,cache));},1);return false;}}).mousedown(function(){if(config.cancelSelection){this.onselectstart=function(){return false};return false;}});$this.bind("update",function(){var me=this;setTimeout(function(){me.config.parsers=buildParserCache(me,$headers);cache=buildCache(me);},1);}).bind("updateCell",function(e,cell){var config=this.config;var pos=[(cell.parentNode.rowIndex-1),cell.cellIndex];cache.normalized[pos[0]][pos[1]]=config.parsers[pos[1]].format(getElementText(config,cell),cell);}).bind("sorton",function(e,list){$(this).trigger("sortStart");config.sortList=list;var sortList=config.sortList;updateHeaderSortCount(this,sortList);setHeadersCss(this,$headers,sortList,sortCSS);appendToTable(this,multisort(this,sortList,cache));}).bind("appendCache",function(){appendToTable(this,cache);}).bind("applyWidgetId",function(e,id){getWidgetById(id).format(this);}).bind("applyWidgets",function(){applyWidget(this);});if($.metadata&&($(this).metadata()&&$(this).metadata().sortlist)){config.sortList=$(this).metadata().sortlist;}if(config.sortList.length>0){$this.trigger("sorton",[config.sortList]);}applyWidget(this);});};this.addParser=function(parser){var l=parsers.length,a=true;for(var i=0;i<l;i++){if(parsers[i].id.toLowerCase()==parser.id.toLowerCase()){a=false;}}if(a){parsers.push(parser);};};this.addWidget=function(widget){widgets.push(widget);};this.formatFloat=function(s){var i=parseFloat(s);return(isNaN(i))?0:i;};this.formatInt=function(s){var i=parseInt(s);return(isNaN(i))?0:i;};this.isDigit=function(s,config){return/^[-+]?\d*$/.test($.trim(s.replace(/[,.']/g,'')));};this.clearTableBody=function(table){if($.browser.msie){function empty(){while(this.firstChild)this.removeChild(this.firstChild);}empty.apply(table.tBodies[0]);}else{table.tBodies[0].innerHTML="";}};}});$.fn.extend({tablesorter:$.tablesorter.construct});var ts=$.tablesorter;ts.addParser({id:"text",is:function(s){return true;},format:function(s){return $.trim(s.toLocaleLowerCase());},type:"text"});ts.addParser({id:"digit",is:function(s,table){var c=table.config;return $.tablesorter.isDigit(s,c);},format:function(s){return $.tablesorter.formatFloat(s);},type:"numeric"});ts.addParser({id:"currency",is:function(s){return/^[£$€?.]/.test(s);},format:function(s){return $.tablesorter.formatFloat(s.replace(new RegExp(/[£$€]/g),""));},type:"numeric"});ts.addParser({id:"ipAddress",is:function(s){return/^\d{2,3}[\.]\d{2,3}[\.]\d{2,3}[\.]\d{2,3}$/.test(s);},format:function(s){var a=s.split("."),r="",l=a.length;for(var i=0;i<l;i++){var item=a[i];if(item.length==2){r+="0"+item;}else{r+=item;}}return $.tablesorter.formatFloat(r);},type:"numeric"});ts.addParser({id:"url",is:function(s){return/^(https?|ftp|file):\/\/$/.test(s);},format:function(s){return jQuery.trim(s.replace(new RegExp(/(https?|ftp|file):\/\//),''));},type:"text"});ts.addParser({id:"isoDate",is:function(s){return/^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(s);},format:function(s){return $.tablesorter.formatFloat((s!="")?new Date(s.replace(new RegExp(/-/g),"/")).getTime():"0");},type:"numeric"});ts.addParser({id:"percent",is:function(s){return/\%$/.test($.trim(s));},format:function(s){return $.tablesorter.formatFloat(s.replace(new RegExp(/%/g),""));},type:"numeric"});ts.addParser({id:"usLongDate",is:function(s){return s.match(new RegExp(/^[A-Za-z]{3,10}\.? [0-9]{1,2}, ([0-9]{4}|'?[0-9]{2}) (([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(AM|PM)))$/));},format:function(s){return $.tablesorter.formatFloat(new Date(s).getTime());},type:"numeric"});ts.addParser({id:"shortDate",is:function(s){return/\d{1,2}[\/\-]\d{1,2}[\/\-]\d{2,4}/.test(s);},format:function(s,table){var c=table.config;s=s.replace(/\-/g,"/");if(c.dateFormat=="us"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/,"$3/$1/$2");}else if(c.dateFormat=="uk"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/,"$3/$2/$1");}else if(c.dateFormat=="dd/mm/yy"||c.dateFormat=="dd-mm-yy"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{2})/,"$1/$2/$3");}return $.tablesorter.formatFloat(new Date(s).getTime());},type:"numeric"});ts.addParser({id:"time",is:function(s){return/^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/.test(s);},format:function(s){return $.tablesorter.formatFloat(new Date("2000/01/01 "+s).getTime());},type:"numeric"});ts.addParser({id:"metadata",is:function(s){return false;},format:function(s,table,cell){var c=table.config,p=(!c.parserMetadataName)?'sortValue':c.parserMetadataName;return $(cell).metadata()[p];},type:"numeric"});ts.addWidget({id:"zebra",format:function(table){if(table.config.debug){var time=new Date();}var $tr,row=-1,odd;$("tr:visible",table.tBodies[0]).each(function(i){$tr=$(this);if(!$tr.hasClass(table.config.cssChildRow))row++;odd=(row%2==0);$tr.removeClass(table.config.widgetZebra.css[odd?0:1]).addClass(table.config.widgetZebra.css[odd?1:0])});if(table.config.debug){$.tablesorter.benchmark("Applying Zebra widget",time);}}});})(jQuery);
jQuery(document).ready(function() {

	// manipulate only if there is more then only one table
	if ($('.in2tableview_table').length > 1) {
		// show only first table
		$('.in2tableview_table').hide();
		$('.in2tableview_table:first').show();

		// create selection
		createTableSelector();
	}

	// tablesorter
	//$('.in2tableview_table table').tablesorter();
	$('.in2tableview-address-table').find('tr').hide();
	$('.in2tableview-address-table').show();
	$("#in2tableview-address-selector").on('change', function() {
		$('.in2tableview-address-table').find('tr').hide().find('td').css({borderTopWidth: '1px'});
		$('[data-legal-entity="' + $(this).val() + '"]').show().first().find('td').css({borderTopWidth:'0'});
	});

});

function createTableSelector() {
	var select = $('<select></select>')
		.addClass('in2tableview_selection')
		.prependTo('.tx-in2tableview')
		.on('change', function() {
			var index = parseInt($(this).val());
			$('.in2tableview_table').hide();
			$('.in2tableview_table').slice(index, index + 1).show();
		});

	$('.sheetName').each(function(i) {
		$('<option></option>')
			.val(i)
			.html($(this).val())
			.appendTo(select);
	});
}
(function(e){var o="left",n="right",d="up",v="down",c="in",w="out",l="none",r="auto",k="swipe",s="pinch",x="tap",i="doubletap",b="longtap",A="horizontal",t="vertical",h="all",q=10,f="start",j="move",g="end",p="cancel",a="ontouchstart" in window,y="TouchSwipe";var m={fingers:1,threshold:75,cancelThreshold:25,pinchThreshold:20,maxTimeThreshold:null,fingerReleaseThreshold:250,longTapThreshold:500,doubleTapThreshold:200,swipe:null,swipeLeft:null,swipeRight:null,swipeUp:null,swipeDown:null,swipeStatus:null,pinchIn:null,pinchOut:null,pinchStatus:null,click:null,tap:null,doubleTap:null,longTap:null,triggerOnTouchEnd:true,triggerOnTouchLeave:false,allowPageScroll:"auto",fallbackToMouseEvents:true,excludedElements:"button, input, select, textarea, a, .noSwipe"};e.fn.swipe=function(D){var C=e(this),B=C.data(y);if(B&&typeof D==="string"){if(B[D]){return B[D].apply(this,Array.prototype.slice.call(arguments,1))}else{e.error("Method "+D+" does not exist on jQuery.swipe")}}else{if(!B&&(typeof D==="object"||!D)){return u.apply(this,arguments)}}return C};e.fn.swipe.defaults=m;e.fn.swipe.phases={PHASE_START:f,PHASE_MOVE:j,PHASE_END:g,PHASE_CANCEL:p};e.fn.swipe.directions={LEFT:o,RIGHT:n,UP:d,DOWN:v,IN:c,OUT:w};e.fn.swipe.pageScroll={NONE:l,HORIZONTAL:A,VERTICAL:t,AUTO:r};e.fn.swipe.fingers={ONE:1,TWO:2,THREE:3,ALL:h};function u(B){if(B&&(B.allowPageScroll===undefined&&(B.swipe!==undefined||B.swipeStatus!==undefined))){B.allowPageScroll=l}if(B.click!==undefined&&B.tap===undefined){B.tap=B.click}if(!B){B={}}B=e.extend({},e.fn.swipe.defaults,B);return this.each(function(){var D=e(this);var C=D.data(y);if(!C){C=new z(this,B);D.data(y,C)}})}function z(a0,aq){var av=(a||!aq.fallbackToMouseEvents),G=av?"touchstart":"mousedown",au=av?"touchmove":"mousemove",R=av?"touchend":"mouseup",P=av?null:"mouseleave",az="touchcancel";var ac=0,aL=null,Y=0,aX=0,aV=0,D=1,am=0,aF=0,J=null;var aN=e(a0);var W="start";var T=0;var aM=null;var Q=0,aY=0,a1=0,aa=0,K=0;var aS=null;try{aN.bind(G,aJ);aN.bind(az,a5)}catch(ag){e.error("events not supported "+G+","+az+" on jQuery.swipe")}this.enable=function(){aN.bind(G,aJ);aN.bind(az,a5);return aN};this.disable=function(){aG();return aN};this.destroy=function(){aG();aN.data(y,null);return aN};this.option=function(a7,a6){if(aq[a7]!==undefined){if(a6===undefined){return aq[a7]}else{aq[a7]=a6}}else{e.error("Option "+a7+" does not exist on jQuery.swipe.options")}};function aJ(a8){if(ax()){return}if(e(a8.target).closest(aq.excludedElements,aN).length>0){return}var a9=a8.originalEvent?a8.originalEvent:a8;var a7,a6=a?a9.touches[0]:a9;W=f;if(a){T=a9.touches.length}else{a8.preventDefault()}ac=0;aL=null;aF=null;Y=0;aX=0;aV=0;D=1;am=0;aM=af();J=X();O();if(!a||(T===aq.fingers||aq.fingers===h)||aT()){ae(0,a6);Q=ao();if(T==2){ae(1,a9.touches[1]);aX=aV=ap(aM[0].start,aM[1].start)}if(aq.swipeStatus||aq.pinchStatus){a7=L(a9,W)}}else{a7=false}if(a7===false){W=p;L(a9,W);return a7}else{ak(true)}}function aZ(a9){var bc=a9.originalEvent?a9.originalEvent:a9;if(W===g||W===p||ai()){return}var a8,a7=a?bc.touches[0]:bc;var ba=aD(a7);aY=ao();if(a){T=bc.touches.length}W=j;if(T==2){if(aX==0){ae(1,bc.touches[1]);aX=aV=ap(aM[0].start,aM[1].start)}else{aD(bc.touches[1]);aV=ap(aM[0].end,aM[1].end);aF=an(aM[0].end,aM[1].end)}D=a3(aX,aV);am=Math.abs(aX-aV)}if((T===aq.fingers||aq.fingers===h)||!a||aT()){aL=aH(ba.start,ba.end);ah(a9,aL);ac=aO(ba.start,ba.end);Y=aI();aE(aL,ac);if(aq.swipeStatus||aq.pinchStatus){a8=L(bc,W)}if(!aq.triggerOnTouchEnd||aq.triggerOnTouchLeave){var a6=true;if(aq.triggerOnTouchLeave){var bb=aU(this);a6=B(ba.end,bb)}if(!aq.triggerOnTouchEnd&&a6){W=ay(j)}else{if(aq.triggerOnTouchLeave&&!a6){W=ay(g)}}if(W==p||W==g){L(bc,W)}}}else{W=p;L(bc,W)}if(a8===false){W=p;L(bc,W)}}function I(a6){var a7=a6.originalEvent;if(a){if(a7.touches.length>0){C();return true}}if(ai()){T=aa}a6.preventDefault();aY=ao();Y=aI();if(aq.triggerOnTouchEnd||(aq.triggerOnTouchEnd==false&&W===j)){W=g;L(a7,W)}else{if(!aq.triggerOnTouchEnd&&a2()){W=g;aB(a7,W,x)}else{if(W===j){W=p;L(a7,W)}}}ak(false)}function a5(){T=0;aY=0;Q=0;aX=0;aV=0;D=1;O();ak(false)}function H(a6){var a7=a6.originalEvent;if(aq.triggerOnTouchLeave){W=ay(g);L(a7,W)}}function aG(){aN.unbind(G,aJ);aN.unbind(az,a5);aN.unbind(au,aZ);aN.unbind(R,I);if(P){aN.unbind(P,H)}ak(false)}function ay(a9){var a8=a9;var a7=aw();var a6=aj();if(!a7){a8=p}else{if(a6&&a9==j&&(!aq.triggerOnTouchEnd||aq.triggerOnTouchLeave)){a8=g}else{if(!a6&&a9==g&&aq.triggerOnTouchLeave){a8=p}}}return a8}function L(a8,a6){var a7=undefined;if(F()){a7=aB(a8,a6,k)}else{if(M()&&a7!==false){a7=aB(a8,a6,s)}}if(aC()&&a7!==false){a7=aB(a8,a6,i)}else{if(al()&&a7!==false){a7=aB(a8,a6,b)}else{if(ad()&&a7!==false){a7=aB(a8,a6,x)}}}if(a6===p){a5(a8)}if(a6===g){if(a){if(a8.touches.length==0){a5(a8)}}else{a5(a8)}}return a7}function aB(a9,a6,a8){var a7=undefined;if(a8==k){aN.trigger("swipeStatus",[a6,aL||null,ac||0,Y||0,T]);if(aq.swipeStatus){a7=aq.swipeStatus.call(aN,a9,a6,aL||null,ac||0,Y||0,T);if(a7===false){return false}}if(a6==g&&aR()){aN.trigger("swipe",[aL,ac,Y,T]);if(aq.swipe){a7=aq.swipe.call(aN,a9,aL,ac,Y,T);if(a7===false){return false}}switch(aL){case o:aN.trigger("swipeLeft",[aL,ac,Y,T]);if(aq.swipeLeft){a7=aq.swipeLeft.call(aN,a9,aL,ac,Y,T)}break;case n:aN.trigger("swipeRight",[aL,ac,Y,T]);if(aq.swipeRight){a7=aq.swipeRight.call(aN,a9,aL,ac,Y,T)}break;case d:aN.trigger("swipeUp",[aL,ac,Y,T]);if(aq.swipeUp){a7=aq.swipeUp.call(aN,a9,aL,ac,Y,T)}break;case v:aN.trigger("swipeDown",[aL,ac,Y,T]);if(aq.swipeDown){a7=aq.swipeDown.call(aN,a9,aL,ac,Y,T)}break}}}if(a8==s){aN.trigger("pinchStatus",[a6,aF||null,am||0,Y||0,T,D]);if(aq.pinchStatus){a7=aq.pinchStatus.call(aN,a9,a6,aF||null,am||0,Y||0,T,D);if(a7===false){return false}}if(a6==g&&a4()){switch(aF){case c:aN.trigger("pinchIn",[aF||null,am||0,Y||0,T,D]);if(aq.pinchIn){a7=aq.pinchIn.call(aN,a9,aF||null,am||0,Y||0,T,D)}break;case w:aN.trigger("pinchOut",[aF||null,am||0,Y||0,T,D]);if(aq.pinchOut){a7=aq.pinchOut.call(aN,a9,aF||null,am||0,Y||0,T,D)}break}}}if(a8==x){if(a6===p||a6===g){clearTimeout(aS);if(V()&&!E()){K=ao();aS=setTimeout(e.proxy(function(){K=null;aN.trigger("tap",[a9.target]);if(aq.tap){a7=aq.tap.call(aN,a9,a9.target)}},this),aq.doubleTapThreshold)}else{K=null;aN.trigger("tap",[a9.target]);if(aq.tap){a7=aq.tap.call(aN,a9,a9.target)}}}}else{if(a8==i){if(a6===p||a6===g){clearTimeout(aS);K=null;aN.trigger("doubletap",[a9.target]);if(aq.doubleTap){a7=aq.doubleTap.call(aN,a9,a9.target)}}}else{if(a8==b){if(a6===p||a6===g){clearTimeout(aS);K=null;aN.trigger("longtap",[a9.target]);if(aq.longTap){a7=aq.longTap.call(aN,a9,a9.target)}}}}}return a7}function aj(){var a6=true;if(aq.threshold!==null){a6=ac>=aq.threshold}if(a6&&aq.cancelThreshold!==null){a6=(aP(aL)-ac)<aq.cancelThreshold}return a6}function ab(){if(aq.pinchThreshold!==null){return am>=aq.pinchThreshold}return true}function aw(){var a6;if(aq.maxTimeThreshold){if(Y>=aq.maxTimeThreshold){a6=false}else{a6=true}}else{a6=true}return a6}function ah(a6,a7){if(aq.allowPageScroll===l||aT()){a6.preventDefault()}else{var a8=aq.allowPageScroll===r;switch(a7){case o:if((aq.swipeLeft&&a8)||(!a8&&aq.allowPageScroll!=A)){a6.preventDefault()}break;case n:if((aq.swipeRight&&a8)||(!a8&&aq.allowPageScroll!=A)){a6.preventDefault()}break;case d:if((aq.swipeUp&&a8)||(!a8&&aq.allowPageScroll!=t)){a6.preventDefault()}break;case v:if((aq.swipeDown&&a8)||(!a8&&aq.allowPageScroll!=t)){a6.preventDefault()}break}}}function a4(){var a7=aK();var a6=U();var a8=ab();return a7&&a6&&a8}function aT(){return !!(aq.pinchStatus||aq.pinchIn||aq.pinchOut)}function M(){return !!(a4()&&aT())}function aR(){var a8=aw();var ba=aj();var a7=aK();var a6=U();var a9=a6&&a7&&ba&&a8;return a9}function S(){return !!(aq.swipe||aq.swipeStatus||aq.swipeLeft||aq.swipeRight||aq.swipeUp||aq.swipeDown)}function F(){return !!(aR()&&S())}function aK(){return((T===aq.fingers||aq.fingers===h)||!a)}function U(){return aM[0].end.x!==0}function a2(){return !!(aq.tap)}function V(){return !!(aq.doubleTap)}function aQ(){return !!(aq.longTap)}function N(){if(K==null){return false}var a6=ao();return(V()&&((a6-K)<=aq.doubleTapThreshold))}function E(){return N()}function at(){return((T===1||!a)&&(isNaN(ac)||ac===0))}function aW(){return((Y>aq.longTapThreshold)&&(ac<q))}function ad(){return !!(at()&&a2())}function aC(){return !!(N()&&V())}function al(){return !!(aW()&&aQ())}function C(){a1=ao();aa=event.touches.length+1}function O(){a1=0;aa=0}function ai(){var a6=false;if(a1){var a7=ao()-a1;if(a7<=aq.fingerReleaseThreshold){a6=true}}return a6}function ax(){return !!(aN.data(y+"_intouch")===true)}function ak(a6){if(a6===true){aN.bind(au,aZ);aN.bind(R,I);if(P){aN.bind(P,H)}}else{aN.unbind(au,aZ,false);aN.unbind(R,I,false);if(P){aN.unbind(P,H,false)}}aN.data(y+"_intouch",a6===true)}function ae(a7,a6){var a8=a6.identifier!==undefined?a6.identifier:0;aM[a7].identifier=a8;aM[a7].start.x=aM[a7].end.x=a6.pageX||a6.clientX;aM[a7].start.y=aM[a7].end.y=a6.pageY||a6.clientY;return aM[a7]}function aD(a6){var a8=a6.identifier!==undefined?a6.identifier:0;var a7=Z(a8);a7.end.x=a6.pageX||a6.clientX;a7.end.y=a6.pageY||a6.clientY;return a7}function Z(a7){for(var a6=0;a6<aM.length;a6++){if(aM[a6].identifier==a7){return aM[a6]}}}function af(){var a6=[];for(var a7=0;a7<=5;a7++){a6.push({start:{x:0,y:0},end:{x:0,y:0},identifier:0})}return a6}function aE(a6,a7){a7=Math.max(a7,aP(a6));J[a6].distance=a7}function aP(a6){return J[a6].distance}function X(){var a6={};a6[o]=ar(o);a6[n]=ar(n);a6[d]=ar(d);a6[v]=ar(v);return a6}function ar(a6){return{direction:a6,distance:0}}function aI(){return aY-Q}function ap(a9,a8){var a7=Math.abs(a9.x-a8.x);var a6=Math.abs(a9.y-a8.y);return Math.round(Math.sqrt(a7*a7+a6*a6))}function a3(a6,a7){var a8=(a7/a6)*1;return a8.toFixed(2)}function an(){if(D<1){return w}else{return c}}function aO(a7,a6){return Math.round(Math.sqrt(Math.pow(a6.x-a7.x,2)+Math.pow(a6.y-a7.y,2)))}function aA(a9,a7){var a6=a9.x-a7.x;var bb=a7.y-a9.y;var a8=Math.atan2(bb,a6);var ba=Math.round(a8*180/Math.PI);if(ba<0){ba=360-Math.abs(ba)}return ba}function aH(a7,a6){var a8=aA(a7,a6);if((a8<=45)&&(a8>=0)){return o}else{if((a8<=360)&&(a8>=315)){return o}else{if((a8>=135)&&(a8<=225)){return n}else{if((a8>45)&&(a8<135)){return v}else{return d}}}}}function ao(){var a6=new Date();return a6.getTime()}function aU(a6){a6=e(a6);var a8=a6.offset();var a7={left:a8.left,right:a8.left+a6.outerWidth(),top:a8.top,bottom:a8.top+a6.outerHeight()};return a7}function B(a6,a7){return(a6.x>a7.left&&a6.x<a7.right&&a6.y>a7.top&&a6.y<a7.bottom)}}})(jQuery);
/**
 * Options Array
 */
var competencepresenterOptions;
var slideshowTimeout;

jQuery.fn.competencepresenter = function(competencepresenterOptions) {
	var $this = $(this);
	window.competencepresenterOptions = $.extend({
		overall: 6, // show X pictures
		start: 1, // start with picture 1
		pictureWidth: 183, // in Px
		borderLeft: 1, // in Px
		firstVisibleImageUid: 0, // internal use
		cutTextOnXLetters: 130 // cut description on X characters
	}, competencepresenterOptions);
	if (!$('.in2competencepresenter_images').length || !$('.in2competencepresenter_images > li').length) {
		return;
	}
	$('.in2competencepresenter_images').hide();

	buildCarousel($this); // initially create carousel

	// touchmove() event
	$this.swipe({
		swipe: function(event, direction, distance, duration, fingerCount) {
			if (direction == 'left') {
				slideNext($this);
			}
			if (direction == 'right') {
				slidePrevious($this);
			}
		}
	});

	// act state mouseover
	$(document).on('mouseover', '.in2competencepresenter_image', function () {
		setActStatus($(this).closest('li').data('uid'));
	});
}

var carouselElement;

/**
 * Create Carousel
 *
 * @param element
 * @param options
 * @returns {*}
 */
function buildCarousel(element) {
	carouselElement = element;

	element.find('.in2competencepresenter_carousel').remove();
	var container = $('<div />').addClass('in2competencepresenter_carousel')
	var ul = $('<ul />').
		css('left', '-' + (competencepresenterOptions.pictureWidth + competencepresenterOptions.borderLeft) + 'px').
		prependTo(container);
	
	var imageArray = getImageArray(competencepresenterOptions.start, competencepresenterOptions.overall, element);
	for (var i = 0; i < imageArray.length; i++) {
		var imgHtml = $('.in2competencepresenter_images  img[data-uid="' + imageArray[i]  + '"]').closest('.figure').children(':first').outerHTML();
		var li = $('<li />').
			html(imgHtml).
			attr('data-uid', imageArray[i]).
			addClass(i == 1 ? 'in2competencepresenter_image_act' : '').
			addClass('in2competencepresenter_number_' + i).
			appendTo(ul);
	}

	// add text/control container
	var textcontainer = $('<div />').
		addClass('in2competencepresenter_carousel_textcontainer').
		appendTo(container);
	$('<h3 />').
		html(getTitle(competencepresenterOptions.firstVisibleImageUid)).
		appendTo(textcontainer);
	$('<p />').
		html(getDescription(competencepresenterOptions.firstVisibleImageUid)).
		appendTo(textcontainer);
	$('<span />').
		addClass('in2competencepresenter_carousel_next').
		html('&gt;').
		click(function() {
			slideNext(element);
		}).
		appendTo(textcontainer);
	$('<span />').
		addClass('in2competencepresenter_carousel_previous').
		html('&lt;').
		click(function() {
			slidePrevious(element);
		}).
		appendTo(textcontainer);

	// add container
	container.prependTo(element);

	// start timer for automatic slide
	slideShowTimerStart();
}

/**
 * Return image Array with uids from any startpoint
 *
 * @param int start
 * @param object element
 * @returns {Array}
 */
function getImageArray(start, max, element) {
	start -= 2;
	max += 2; // we want to show 1 before and 1 after all viewable
	var initialImageArray = new Array();

	// initially get image array
	element.find('.in2competencepresenter_images').children().each(function() {
		var uid = $(this).find('.figure').find('img').data('uid');
		initialImageArray.push(uid);
	});

	// get correct startpoint
	if (start > 0) {
		for (var i=0; start > initialImageArray.length; i++) {
			start -= initialImageArray.length;
		}
	}
	if (start < 0) {
		for (var i=0; start < 0; i++) {
			start += initialImageArray.length;
		}
	}

	// get correct sorting
	var imageArray = new Array();
	var j = 0;
	for (var i = 0; i < max; i++) {
		var key = start + i;
		if (initialImageArray[key] == undefined) { // reset at the and of the array
			key = j;
			j++;
		}
		imageArray.push(initialImageArray[key]);
	}

	competencepresenterOptions.firstVisibleImageUid = imageArray[1];
	return imageArray;
}

/**
 * Git title of a given image uid
 *
 * @param imageUid
 * @returns {*|jQuery}
 */
function getTitle(imageUid) {
	var text = $('.in2competencepresenter_images img[data-uid="' + imageUid  + '"]').closest('.figure').find('.figcaption').children('h3').html(); // get h3 html
	return text;
}

/**
 * Git description of a given image uid
 *
 * @param imageUid
 * @returns {*|jQuery}
 */
function getDescription(imageUid) {
	var text = $('.in2competencepresenter_images img[data-uid="' + imageUid  + '"]').closest('.figure').find('.figcaption').children('p').html(); // get p html
	if (text != undefined && text.length > competencepresenterOptions.cutTextOnXLetters) {
		var description = text;
		text = '<span title="' + text + '">';
		text += description.substr(0, competencepresenterOptions.cutTextOnXLetters) + '...';
		text += '</span>';
	}
	return text;
}

/**
 * Set the Activestatus, title and description on hover
 * @param imageUid
 */
function setActStatus(imageUid) {
	$('.in2competencepresenter_image_act').removeClass('in2competencepresenter_image_act');
	$('.in2competencepresenter_last_visible').removeClass('in2competencepresenter_last_visible');
	var current = $('.in2competencepresenter_carousel img[data-uid="' + imageUid  + '"]').closest('li');
	if(current.hasClass('in2competencepresenter_number_6')) {
		current.find('span').addClass('in2competencepresenter_last_visible');
	}
	current.addClass('in2competencepresenter_image_act');
	$('.in2competencepresenter_carousel_textcontainer h3').html(getTitle(imageUid));
	$('.in2competencepresenter_carousel_textcontainer p').html(getDescription(imageUid));
}

/**
 * Slide to Next Element
 *
 * @param element
 * @return void
 */
function slideNext(element) {
	$('.in2competencepresenter_carousel ul').animate({
		left: '-=' + (competencepresenterOptions.pictureWidth + competencepresenterOptions.borderLeft)
	}, function() {
		competencepresenterOptions.start ++;
		buildCarousel(element);
	});
}

/**
 * Slide to Previous Element
 *
 * @param element
 * @return void
 */
function slidePrevious(element) {
	$('.in2competencepresenter_carousel ul').animate({
		left: '+=' + (competencepresenterOptions.pictureWidth + competencepresenterOptions.borderLeft)
	}, function() {
		competencepresenterOptions.start --;
		buildCarousel(element);
	});
}

/**
 * Function with timeout for the slideshow
 *
 * @return void
 */
function slideShowTimerStart() {
	var slideshow = $('.in2competencepresenter_images').attr('data-rotation');

	if(slideshow > 0){
		window.clearTimeout(slideshowTimeout);
		slideshowTimeout = window.setTimeout('slideNext(carouselElement)', slideshow);
	}
}

/**
 * Like jQuery .html() but with wrapping Tag
 *
 * @param string	String if string should be setted
 * @return string
 */
jQuery.fn.outerHTML = function(s) {
	return (s) ? $(this).replaceWith(s) : $(this).clone().wrap('<p>').parent().html();
}
jQuery('document').ready(function() {
	$('.tx-in2competencepresenter').competencepresenter();

	$(window).bind('enterBreakpoint1330 exitBreakpoint1330', function () {
		$('.tx-in2competencepresenter').competencepresenter({
			cutTextOnXLetters: 130
		});
	});

	$(window).bind('enterBreakpoint1323 exitBreakpoint1323 enterBreakpoint1280 exitBreakpoint1280 enterBreakpoint1024 exitBreakpoint1024 enterBreakpoint1000 exitBreakpoint1000 exitBreakpoint992 enterBreakpoint992', function () {
		$('.tx-in2competencepresenter').competencepresenter({
			cutTextOnXLetters: 90
		});
	});

	$(window).bind('enterBreakpoint990 exitBreakpoint990 enterBreakpoint768 exitBreakpoint768 enterBreakpoint480 exitBreakpoint480 enterBreakpoint320 exitBreakpoint320', function () {
		$('.tx-in2competencepresenter').competencepresenter({
			cutTextOnXLetters: 50
		});
	});
});