/* * jQuery FlexSlider v2.7.1 * Copyright 2012 WooThemes * Contributing Author: Tyler Smith */ ; (function ($) { var focused = true; //FlexSlider: Object Instance $.flexslider = function(el, options) { var slider = $(el); // making variables public //if rtl value was not passed and html is in rtl..enable it by default. if(typeof options.rtl=='undefined' && $('html').attr('dir')=='rtl'){ options.rtl=true; } slider.vars = $.extend({}, $.flexslider.defaults, options); var namespace = slider.vars.namespace, msGesture = window.navigator && window.navigator.msPointerEnabled && window.MSGesture, touch = (( "ontouchstart" in window ) || msGesture || window.DocumentTouch && document instanceof DocumentTouch) && slider.vars.touch, // deprecating this idea, as devices are being released with both of these events eventType = "click touchend MSPointerUp keyup", watchedEvent = "", watchedEventClearTimer, vertical = slider.vars.direction === "vertical", reverse = slider.vars.reverse, carousel = (slider.vars.itemWidth > 0), fade = slider.vars.animation === "fade", asNav = slider.vars.asNavFor !== "", methods = {}; // Store a reference to the slider object $.data(el, "flexslider", slider); // Private slider methods methods = { init: function() { slider.animating = false; // Get current slide and make sure it is a number slider.currentSlide = parseInt( ( slider.vars.startAt ? slider.vars.startAt : 0), 10 ); if ( isNaN( slider.currentSlide ) ) { slider.currentSlide = 0; } slider.animatingTo = slider.currentSlide; slider.atEnd = (slider.currentSlide === 0 || slider.currentSlide === slider.last); slider.containerSelector = slider.vars.selector.substr(0,slider.vars.selector.search(' ')); slider.slides = $(slider.vars.selector, slider); slider.container = $(slider.containerSelector, slider); slider.count = slider.slides.length; // SYNC: slider.syncExists = $(slider.vars.sync).length > 0; // SLIDE: if (slider.vars.animation === "slide") { slider.vars.animation = "swing"; } slider.prop = (vertical) ? "top" : ( slider.vars.rtl ? "marginRight" : "marginLeft" ); slider.args = {}; // SLIDESHOW: slider.manualPause = false; slider.stopped = false; //PAUSE WHEN INVISIBLE slider.started = false; slider.startTimeout = null; // TOUCH/USECSS: slider.transitions = !slider.vars.video && !fade && slider.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; }()); slider.isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1; slider.ensureAnimationEnd = ''; // CONTROLSCONTAINER: if (slider.vars.controlsContainer !== "") slider.controlsContainer = $(slider.vars.controlsContainer).length > 0 && $(slider.vars.controlsContainer); // MANUAL: if (slider.vars.manualControls !== "") slider.manualControls = $(slider.vars.manualControls).length > 0 && $(slider.vars.manualControls); // CUSTOM DIRECTION NAV: if (slider.vars.customDirectionNav !== "") slider.customDirectionNav = $(slider.vars.customDirectionNav).length === 2 && $(slider.vars.customDirectionNav); // RANDOMIZE: if (slider.vars.randomize) { slider.slides.sort(function() { return (Math.round(Math.random())-0.5); }); slider.container.empty().append(slider.slides); } slider.doMath(); // INIT slider.setup("init"); // CONTROLNAV: if (slider.vars.controlNav) { methods.controlNav.setup(); } // DIRECTIONNAV: if (slider.vars.directionNav) { methods.directionNav.setup(); } // KEYBOARD: if (slider.vars.keyboard && ($(slider.containerSelector).length === 1 || slider.vars.multipleKeyboard)) { $(document).bind('keyup', function(event) { var keycode = event.keyCode; if (!slider.animating && (keycode === 39 || keycode === 37)) { var target = (slider.vars.rtl? ((keycode === 37) ? slider.getTarget('next') : (keycode === 39) ? slider.getTarget('prev') : false) : ((keycode === 39) ? slider.getTarget('next') : (keycode === 37) ? slider.getTarget('prev') : false) ) ; slider.flexAnimate(target, slider.vars.pauseOnAction); } }); } // MOUSEWHEEL: if (slider.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, slider.vars.pauseOnAction); }); } // PAUSEPLAY if (slider.vars.pausePlay) { methods.pausePlay.setup(); } //PAUSE WHEN INVISIBLE if (slider.vars.slideshow && slider.vars.pauseInvisible) { methods.pauseInvisible.init(); } // SLIDSESHOW if (slider.vars.slideshow) { if (slider.vars.pauseOnHover) { slider.hover(function() { if (!slider.manualPlay && !slider.manualPause) { slider.pause(); } }, function() { if (!slider.manualPause && !slider.manualPlay && !slider.stopped) { slider.play(); } }); } // initialize animation //If we're visible, or we don't use PageVisibility API if(!slider.vars.pauseInvisible || !methods.pauseInvisible.isHidden()) { (slider.vars.initDelay > 0) ? slider.startTimeout = setTimeout(slider.play, slider.vars.initDelay) : slider.play(); } } // ASNAV: if (asNav) { methods.asNav.setup(); } // TOUCH if (touch && slider.vars.touch) { methods.touch(); } // FADE&&SMOOTHHEIGHT || SLIDE: if (!fade || (fade && slider.vars.smoothHeight)) { $(window).bind("resize orientationchange focus", methods.resize); } slider.find("img").attr("draggable", "false"); // API: start() Callback setTimeout(function(){ slider.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"); if(!msGesture){ slider.slides.on(eventType, function(e){ e.preventDefault(); var $slide = $(this), target = $slide.index(); var posFromX; if(slider.vars.rtl){ posFromX = -1*($slide.offset().right - $(slider).scrollLeft()); // Find position of slide relative to right of slider container } else { posFromX = $slide.offset().left - $(slider).scrollLeft(); // Find position of slide relative to left of slider container } if( posFromX <= 0 && $slide.hasClass( namespace + 'active-slide' ) ) { slider.flexAnimate(slider.getTarget("prev"), true); } else if (!$(slider.vars.asNavFor).data('flexslider').animating && !$slide.hasClass(namespace + "active-slide")) { slider.direction = (slider.currentItem < target) ? "next" : "prev"; slider.flexAnimate(target, slider.vars.pauseOnAction, false, true, true); } }); }else{ el._slider = slider; slider.slides.each(function (){ var that = this; that._gesture = new MSGesture(); that._gesture.target = that; that.addEventListener("MSPointerDown", function (e){ e.preventDefault(); if(e.currentTarget._gesture) { e.currentTarget._gesture.addPointer(e.pointerId); } }, false); that.addEventListener("MSGestureTap", function (e){ e.preventDefault(); var $slide = $(this), target = $slide.index(); if (!$(slider.vars.asNavFor).data('flexslider').animating && !$slide.hasClass('active')) { slider.direction = (slider.currentItem < target) ? "next" : "prev"; slider.flexAnimate(target, slider.vars.pauseOnAction, false, true, true); } }); }); } } }, controlNav: { setup: function() { if (!slider.manualControls) { methods.controlNav.setupPaging(); } else { // MANUALCONTROLS: methods.controlNav.setupManual(); } }, setupPaging: function() { var type = (slider.vars.controlNav === "thumbnails") ? 'control-thumbs' : 'control-paging', j = 1, item, slide; slider.controlNavScaffold = $('
    '); if (slider.pagingCount > 1) { for (var i = 0; i < slider.pagingCount; i++) { slide = slider.slides.eq(i); if ( undefined === slide.attr( 'data-thumb-alt' ) ) { slide.attr( 'data-thumb-alt', '' ); } var altText = ( '' !== slide.attr( 'data-thumb-alt' ) ) ? altText = ' alt="' + slide.attr( 'data-thumb-alt' ) + '"' : ''; item = (slider.vars.controlNav === "thumbnails") ? '' : '' + j + ''; if ( 'thumbnails' === slider.vars.controlNav && true === slider.vars.thumbCaptions ) { var captn = slide.attr( 'data-thumbcaption' ); if ( '' !== captn && undefined !== captn ) { item += '' + captn + ''; } } slider.controlNavScaffold.append('
  1. ' + item + '
  2. '); 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(); if (watchedEvent === "" || watchedEvent === event.type) { var $this = $(this), target = slider.controlNav.index($this); if (!$this.hasClass(namespace + 'active')) { slider.direction = (target > slider.currentSlide) ? "next" : "prev"; slider.flexAnimate(target, slider.vars.pauseOnAction); } } // setup flags to prevent event duplication if (watchedEvent === "") { watchedEvent = event.type; } methods.setToClearWatchedEvent(); }); }, setupManual: function() { slider.controlNav = slider.manualControls; methods.controlNav.active(); slider.controlNav.bind(eventType, function(event) { event.preventDefault(); if (watchedEvent === "" || watchedEvent === event.type) { 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, slider.vars.pauseOnAction); } } // setup flags to prevent event duplication if (watchedEvent === "") { watchedEvent = event.type; } methods.setToClearWatchedEvent(); }); }, set: function() { var selector = (slider.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($('
  3. ' + slider.count + '
  4. ')); } 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 = $(''); // CUSTOM DIRECTION NAV: if (slider.customDirectionNav) { slider.directionNav = slider.customDirectionNav; // CONTROLSCONTAINER: } else 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; if (watchedEvent === "" || watchedEvent === event.type) { target = ($(this).hasClass(namespace + 'next')) ? slider.getTarget('next') : slider.getTarget('prev'); slider.flexAnimate(target, slider.vars.pauseOnAction); } // setup flags to prevent event duplication if (watchedEvent === "") { watchedEvent = event.type; } methods.setToClearWatchedEvent(); }); }, update: function() { var disabledClass = namespace + 'disabled'; if (slider.pagingCount === 1) { slider.directionNav.addClass(disabledClass).attr('tabindex', '-1'); } else if (!slider.vars.animationLoop) { if (slider.animatingTo === 0) { slider.directionNav.removeClass(disabledClass).filter('.' + namespace + "prev").addClass(disabledClass).attr('tabindex', '-1'); } else if (slider.animatingTo === slider.last) { slider.directionNav.removeClass(disabledClass).filter('.' + namespace + "next").addClass(disabledClass).attr('tabindex', '-1'); } else { slider.directionNav.removeClass(disabledClass).removeAttr('tabindex'); } } else { slider.directionNav.removeClass(disabledClass).removeAttr('tabindex'); } } }, pausePlay: { setup: function() { var pausePlayScaffold = $('
    '); // 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((slider.vars.slideshow) ? namespace + 'pause' : namespace + 'play'); slider.pausePlay.bind(eventType, function(event) { event.preventDefault(); if (watchedEvent === "" || watchedEvent === event.type) { if ($(this).hasClass(namespace + 'pause')) { slider.manualPause = true; slider.manualPlay = false; slider.pause(); } else { slider.manualPause = false; slider.manualPlay = true; slider.play(); } } // setup flags to prevent event duplication if (watchedEvent === "") { watchedEvent = event.type; } methods.setToClearWatchedEvent(); }); }, update: function(state) { (state === "play") ? slider.pausePlay.removeClass(namespace + 'pause').addClass(namespace + 'play').html(slider.vars.playText) : slider.pausePlay.removeClass(namespace + 'play').addClass(namespace + 'pause').html(slider.vars.pauseText); } }, touch: function() { var startX, startY, offset, cwidth, dx, startT, onTouchStart, onTouchMove, onTouchEnd, scrolling = false, localX = 0, localY = 0, accDx = 0; if(!msGesture){ onTouchStart = function(e) { if (slider.animating) { e.preventDefault(); } else if ( ( window.navigator.msPointerEnabled ) || e.touches.length === 1 ) { slider.pause(); // CAROUSEL: cwidth = (vertical) ? slider.h : slider. w; startT = Number(new Date()); // CAROUSEL: // Local vars for X and Y points. localX = e.touches[0].pageX; localY = e.touches[0].pageY; offset = (carousel && reverse && slider.animatingTo === slider.last) ? 0 : (carousel && reverse) ? slider.limit - (((slider.itemW + slider.vars.itemMargin) * slider.move) * slider.animatingTo) : (carousel && slider.currentSlide === slider.last) ? slider.limit : (carousel) ? ((slider.itemW + slider.vars.itemMargin) * slider.move) * slider.currentSlide : (reverse) ? (slider.last - slider.currentSlide + slider.cloneOffset) * cwidth : (slider.currentSlide + slider.cloneOffset) * cwidth; startX = (vertical) ? localY : localX; startY = (vertical) ? localX : localY; el.addEventListener('touchmove', onTouchMove, false); el.addEventListener('touchend', onTouchEnd, false); } }; onTouchMove = function(e) { // Local vars for X and Y points. localX = e.touches[0].pageX; localY = e.touches[0].pageY; dx = (vertical) ? startX - localY : (slider.vars.rtl?-1:1)*(startX - localX); scrolling = (vertical) ? (Math.abs(dx) < Math.abs(localX - startY)) : (Math.abs(dx) < Math.abs(localY - startY)); var fxms = 500; if ( ! scrolling || Number( new Date() ) - startT > fxms ) { e.preventDefault(); if (!fade && slider.transitions) { if (!slider.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"); } } }; onTouchEnd = function(e) { // finish the touch by undoing the touch session el.removeEventListener('touchmove', onTouchMove, false); 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, slider.vars.pauseOnAction); } else { if (!fade) { slider.flexAnimate(slider.currentSlide, slider.vars.pauseOnAction, true); } } } el.removeEventListener('touchend', onTouchEnd, false); startX = null; startY = null; dx = null; offset = null; }; el.addEventListener('touchstart', onTouchStart, false); }else{ el.style.msTouchAction = "none"; el._gesture = new MSGesture(); el._gesture.target = el; el.addEventListener("MSPointerDown", onMSPointerDown, false); el._slider = slider; el.addEventListener("MSGestureChange", onMSGestureChange, false); el.addEventListener("MSGestureEnd", onMSGestureEnd, false); function onMSPointerDown(e){ e.stopPropagation(); if (slider.animating) { e.preventDefault(); }else{ slider.pause(); el._gesture.addPointer(e.pointerId); accDx = 0; 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 + slider.vars.itemMargin) * slider.move) * slider.animatingTo) : (carousel && slider.currentSlide === slider.last) ? slider.limit : (carousel) ? ((slider.itemW + slider.vars.itemMargin) * slider.move) * slider.currentSlide : (reverse) ? (slider.last - slider.currentSlide + slider.cloneOffset) * cwidth : (slider.currentSlide + slider.cloneOffset) * cwidth; } } function onMSGestureChange(e) { e.stopPropagation(); var slider = e.target._slider; if(!slider){ return; } var transX = -e.translationX, transY = -e.translationY; //Accumulate translations. accDx = accDx + ((vertical) ? transY : transX); dx = (slider.vars.rtl?-1:1)*accDx; scrolling = (vertical) ? (Math.abs(accDx) < Math.abs(-transX)) : (Math.abs(accDx) < Math.abs(-transY)); if(e.detail === e.MSGESTURE_FLAG_INERTIA){ setImmediate(function (){ el._gesture.stop(); }); return; } if (!scrolling || Number(new Date()) - startT > 500) { e.preventDefault(); if (!fade && slider.transitions) { if (!slider.vars.animationLoop) { dx = accDx / ((slider.currentSlide === 0 && accDx < 0 || slider.currentSlide === slider.last && accDx > 0) ? (Math.abs(accDx) / cwidth + 2) : 1); } slider.setProps(offset + dx, "setTouch"); } } } function onMSGestureEnd(e) { e.stopPropagation(); var slider = e.target._slider; if(!slider){ return; } 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, slider.vars.pauseOnAction); } else { if (!fade) { slider.flexAnimate(slider.currentSlide, slider.vars.pauseOnAction, true); } } } startX = null; startY = null; dx = null; offset = null; accDx = 0; } } }, 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 (slider.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).innerHeight()}, dur) : $obj.innerHeight(slider.slides.eq(slider.animatingTo).innerHeight()); } }, sync: function(action) { var $obj = $(slider.vars.sync).data("flexslider"), target = slider.animatingTo; switch (action) { case "animate": $obj.flexAnimate(target, slider.vars.pauseOnAction, false, true); break; case "play": if (!$obj.playing && !$obj.asNav) { $obj.play(); } break; case "pause": $obj.pause(); break; } }, uniqueID: function($clone) { // Append _clone to current level and children elements with id attributes $clone.filter( '[id]' ).add($clone.find( '[id]' )).each(function() { var $this = $(this); $this.attr( 'id', $this.attr( 'id' ) + '_clone' ); }); return $clone; }, pauseInvisible: { visProp: null, init: function() { var visProp = methods.pauseInvisible.getHiddenProp(); if (visProp) { var evtname = visProp.replace(/[H|h]idden/,'') + 'visibilitychange'; document.addEventListener(evtname, function() { if (methods.pauseInvisible.isHidden()) { if(slider.startTimeout) { clearTimeout(slider.startTimeout); //If clock is ticking, stop timer and prevent from starting while invisible } else { slider.pause(); //Or just pause } } else { if(slider.started) { slider.play(); //Initiated before, just play } else { if (slider.vars.initDelay > 0) { setTimeout(slider.play, slider.vars.initDelay); } else { slider.play(); //Didn't init before: simply init or wait for it } } } }); } }, isHidden: function() { var prop = methods.pauseInvisible.getHiddenProp(); if (!prop) { return false; } return document[prop]; }, getHiddenProp: function() { var prefixes = ['webkit','moz','ms','o']; // if 'hidden' is natively supported just return it if ('hidden' in document) { return 'hidden'; } // otherwise loop over all the known prefixes until we find one for ( var i = 0; i < prefixes.length; i++ ) { if ((prefixes[i] + 'Hidden') in document) { return prefixes[i] + 'Hidden'; } } // otherwise it's not supported return null; } }, setToClearWatchedEvent: function() { clearTimeout(watchedEventClearTimer); watchedEventClearTimer = setTimeout(function() { watchedEvent = ""; }, 3000); } }; // public methods slider.flexAnimate = function(target, pause, override, withSync, fromNav) { if (!slider.vars.animationLoop && target !== slider.currentSlide) { slider.direction = (target > slider.currentSlide) ? "next" : "prev"; } 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 = $(slider.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; // SLIDESHOW: if (pause) { slider.pause(); } // API: before() animation Callback slider.vars.before(slider); // SYNC: if (slider.syncExists && !fromNav) { methods.sync("animate"); } // CONTROLNAV if (slider.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 (slider.vars.directionNav) { methods.directionNav.update(); } if (target === slider.last) { // API: end() of cycle Callback slider.vars.end(slider); // SLIDESHOW && !INFINITE LOOP: if (!slider.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 = slider.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 && slider.vars.animationLoop && slider.direction !== "next") { slideString = (reverse) ? (slider.count + slider.cloneOffset) * dimension : 0; } else if (slider.currentSlide === slider.last && target === 0 && slider.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, "", slider.vars.animationSpeed); if (slider.transitions) { if (!slider.vars.animationLoop || !slider.atEnd) { slider.animating = false; slider.currentSlide = slider.animatingTo; } // Unbind previous transitionEnd events and re-bind new transitionEnd event slider.container.unbind("webkitTransitionEnd transitionend"); slider.container.bind("webkitTransitionEnd transitionend", function() { clearTimeout(slider.ensureAnimationEnd); slider.wrapup(dimension); }); // Insurance for the ever-so-fickle transitionEnd event clearTimeout(slider.ensureAnimationEnd); slider.ensureAnimationEnd = setTimeout(function() { slider.wrapup(dimension); }, slider.vars.animationSpeed + 100); } else { slider.container.animate(slider.args, slider.vars.animationSpeed, slider.vars.easing, function(){ slider.wrapup(dimension); }); } } else { // FADE: if (!touch) { slider.slides.eq(slider.currentSlide).css({"zIndex": 1}).animate({"opacity": 0}, slider.vars.animationSpeed, slider.vars.easing); slider.slides.eq(target).css({"zIndex": 2}).animate({"opacity": 1}, slider.vars.animationSpeed, slider.vars.easing, slider.wrapup); } else { slider.slides.eq(slider.currentSlide).css({ "opacity": 0, "zIndex": 1 }); slider.slides.eq(target).css({ "opacity": 1, "zIndex": 2 }); slider.wrapup(dimension); } } // SMOOTH HEIGHT: if (slider.vars.smoothHeight) { methods.smoothHeight(slider.vars.animationSpeed); } } }; slider.wrapup = function(dimension) { // SLIDE: if (!fade && !carousel) { if (slider.currentSlide === 0 && slider.animatingTo === slider.last && slider.vars.animationLoop) { slider.setProps(dimension, "jumpEnd"); } else if (slider.currentSlide === slider.last && slider.animatingTo === 0 && slider.vars.animationLoop) { slider.setProps(dimension, "jumpStart"); } } slider.animating = false; slider.currentSlide = slider.animatingTo; // API: after() animation Callback slider.vars.after(slider); }; // SLIDESHOW: slider.animateSlides = function() { if (!slider.animating && focused ) { slider.flexAnimate(slider.getTarget("next")); } }; // SLIDESHOW: slider.pause = function() { clearInterval(slider.animatedSlides); slider.animatedSlides = null; slider.playing = false; // PAUSEPLAY: if (slider.vars.pausePlay) { methods.pausePlay.update("play"); } // SYNC: if (slider.syncExists) { methods.sync("pause"); } }; // SLIDESHOW: slider.play = function() { if (slider.playing) { clearInterval(slider.animatedSlides); } slider.animatedSlides = slider.animatedSlides || setInterval(slider.animateSlides, slider.vars.slideshowSpeed); slider.started = slider.playing = true; // PAUSEPLAY: if (slider.vars.pausePlay) { methods.pausePlay.update("pause"); } // SYNC: if (slider.syncExists) { methods.sync("play"); } }; // STOP: slider.stop = function () { slider.pause(); slider.stopped = true; }; 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 : (slider.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 + slider.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 + slider.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 * ((slider.vars.rtl)?1:-1)) + "px"; }()); if (slider.transitions) { if (slider.isFirefox) { target = (vertical) ? "translate3d(0," + target + ",0)" : "translate3d(" + (parseInt(target)+'px') + ",0,0)"; } else { target = (vertical) ? "translate3d(0," + target + ",0)" : "translate3d(" + ((slider.vars.rtl?-1:1)*parseInt(target)+'px') + ",0,0)"; } dur = (dur !== undefined) ? (dur/1000) + "s" : "0s"; slider.container.css("-" + slider.pfx + "-transition-duration", dur); slider.container.css("transition-duration", dur); } slider.args[slider.prop] = target; if (slider.transitions || dur === undefined) { slider.container.css(slider.args); } slider.container.css('transform',target); }; slider.setup = function(type) { // SLIDE: if (!fade) { var sliderOffset, arr; if (type === "init") { slider.viewport = $('
    ').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 (slider.vars.animationLoop && !carousel) { slider.cloneCount = 2; slider.cloneOffset = 1; // clear out old clones if (type !== "init") { slider.container.find('.clone').remove(); } slider.container.append(methods.uniqueID(slider.slides.first().clone().addClass('clone')).attr('aria-hidden', 'true')) .prepend(methods.uniqueID(slider.slides.last().clone().addClass('clone')).attr('aria-hidden', 'true')); } slider.newSlides = $(slider.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": "block"}); 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(); if(slider.vars.rtl){ if (slider.isFirefox) { slider.newSlides.css({"width": slider.computedW, "marginRight" : slider.computedM, "float": "right", "display": "block"}); } else { slider.newSlides.css({"width": slider.computedW, "marginRight" : slider.computedM, "float": "left", "display": "block"}); } } else{ slider.newSlides.css({"width": slider.computedW, "marginRight" : slider.computedM, "float": "left", "display": "block"}); } // SMOOTH HEIGHT: if (slider.vars.smoothHeight) { methods.smoothHeight(); } }, (type === "init") ? 100 : 0); } } else { // FADE: if(slider.vars.rtl){ slider.slides.css({"width": "100%", "float": 'right', "marginLeft": "-100%", "position": "relative"}); } else{ slider.slides.css({"width": "100%", "float": 'left', "marginRight": "-100%", "position": "relative"}); } if (type === "init") { if (!touch) { //slider.slides.eq(slider.currentSlide).fadeIn(slider.vars.animationSpeed, slider.vars.easing); if (slider.vars.fadeFirstSlide == false) { slider.slides.css({ "opacity": 0, "display": "block", "zIndex": 1 }).eq(slider.currentSlide).css({"zIndex": 2}).css({"opacity": 1}); } else { slider.slides.css({ "opacity": 0, "display": "block", "zIndex": 1 }).eq(slider.currentSlide).css({"zIndex": 2}).animate({"opacity": 1},slider.vars.animationSpeed,slider.vars.easing); } } else { slider.slides.css({ "opacity": 0, "display": "block", "webkitTransition": "opacity " + slider.vars.animationSpeed / 1000 + "s ease", "zIndex": 1 }).eq(slider.currentSlide).css({ "opacity": 1, "zIndex": 2}); } } // SMOOTH HEIGHT: if (slider.vars.smoothHeight) { methods.smoothHeight(); } } // !CAROUSEL: // CANDIDATE: active slide if (!carousel) { slider.slides.removeClass(namespace + "active-slide").eq(slider.currentSlide).addClass(namespace + "active-slide"); } //FlexSlider: init() Callback slider.vars.init(slider); }; slider.doMath = function() { var slide = slider.slides.first(), slideMargin = slider.vars.itemMargin, minItems = slider.vars.minItems, maxItems = slider.vars.maxItems; slider.w = (slider.viewport===undefined) ? slider.width() : slider.viewport.width(); if (slider.isFirefox) { slider.w = slider.width(); } slider.h = slide.height(); slider.boxPadding = slide.outerWidth() - slide.width(); // CAROUSEL: if (carousel) { slider.itemT = slider.vars.itemWidth + slideMargin; slider.itemM = slideMargin; slider.minW = (minItems) ? minItems * slider.itemT : slider.w; slider.maxW = (maxItems) ? (maxItems * slider.itemT) - slideMargin : slider.w; slider.itemW = (slider.minW > slider.w) ? (slider.w - (slideMargin * (minItems - 1)))/minItems : (slider.maxW < slider.w) ? (slider.w - (slideMargin * (maxItems - 1)))/maxItems : (slider.vars.itemWidth > slider.w) ? slider.w : slider.vars.itemWidth; slider.visible = Math.floor(slider.w/(slider.itemW)); slider.move = (slider.vars.move > 0 && slider.vars.move < slider.visible ) ? slider.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 : (slider.vars.itemWidth > slider.w) ? (slider.itemW * (slider.count - 1)) + (slideMargin * (slider.count - 1)) : ((slider.itemW + slideMargin) * slider.count) - slider.w - slideMargin; } else { slider.itemW = slider.w; slider.itemM = slideMargin; slider.pagingCount = slider.count; slider.last = slider.count - 1; } slider.computedW = slider.itemW - slider.boxPadding; slider.computedM = slider.itemM; }; 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 (slider.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 (slider.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 = $(slider.vars.selector + ':not(.clone)', slider); // re-setup the slider to accomdate new slide slider.setup(); //FlexSlider: added() Callback slider.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 = $(slider.vars.selector + ':not(.clone)', slider); // re-setup the slider to accomdate new slide slider.setup(); // FlexSlider: removed() Callback slider.vars.removed(slider); }; //FlexSlider: Initialize methods.init(); }; // Ensure the slider isn't focussed if the window loses focus. $( window ).blur( function ( e ) { focused = false; }).focus( function ( e ) { focused = true; }); //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 fadeFirstSlide: true, //Boolean: Fade in the first slide when animation type is "fade" thumbCaptions: false, //Boolean: Whether or not to put captions on thumbnails when using the "thumbnails" controlNav. // 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 pauseInvisible: true, //{NEW} Boolean: Pause the slideshow when tab is invisible, resume when visible. Provides better UX, lower CPU usage. 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 slide? 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. customDirectionNav: "", //{NEW} jQuery Object/Selector: Custom prev / next button. Must be two jQuery elements. In order to make the events work they have to have the classes "prev" and "next" (plus namespace) 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: 1, //{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. allowOneSlide: true, //{NEW} Boolean: Whether or not to allow a slider comprised of a single slide // Browser Specific isFirefox: false, // {NEW} Boolean: Set to true when Firefox is the browser used. // 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 init: function() {}, //{NEW} Callback: function(slider) - Fires after the slider is initially setup rtl: false //{NEW} Boolean: Whether or not to enable RTL mode }; //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 && options.allowOneSlide === false ) || $slides.length === 0 ) { $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 "stop": $slider.stop(); 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); /*! Magnific Popup - v1.1.0 - 2016-02-20 * http://dimsemenov.com/plugins/magnific-popup/ * Copyright (c) 2016 Dmitry Semenov; */ ;(function (factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['jquery'], factory); } else if (typeof exports === 'object') { // Node/CommonJS factory(require('jquery')); } else { // Browser globals factory(window.jQuery || window.Zepto); } }(function($) { /*>>core*/ /** * * Magnific Popup Core JS file * */ /** * Private static constants */ var CLOSE_EVENT = 'Close', BEFORE_CLOSE_EVENT = 'BeforeClose', AFTER_CLOSE_EVENT = 'AfterClose', BEFORE_APPEND_EVENT = 'BeforeAppend', MARKUP_PARSE_EVENT = 'MarkupParse', OPEN_EVENT = 'Open', CHANGE_EVENT = 'Change', NS = 'mfp', EVENT_NS = '.' + NS, READY_CLASS = 'mfp-ready', REMOVING_CLASS = 'mfp-removing', PREVENT_CLOSE_CLASS = 'mfp-prevent-close'; /** * Private vars */ /*jshint -W079 */ var mfp, // As we have only one instance of MagnificPopup object, we define it locally to not to use 'this' MagnificPopup = function(){}, _isJQ = !!(window.jQuery), _prevStatus, _window = $(window), _document, _prevContentType, _wrapClasses, _currPopupType; /** * Private functions */ var _mfpOn = function(name, f) { mfp.ev.on(NS + name + EVENT_NS, f); }, _getEl = function(className, appendTo, html, raw) { var el = document.createElement('div'); el.className = 'mfp-'+className; if(html) { el.innerHTML = html; } if(!raw) { el = $(el); if(appendTo) { el.appendTo(appendTo); } } else if(appendTo) { appendTo.appendChild(el); } return el; }, _mfpTrigger = function(e, data) { mfp.ev.triggerHandler(NS + e, data); if(mfp.st.callbacks) { // converts "mfpEventName" to "eventName" callback and triggers it if it's present e = e.charAt(0).toLowerCase() + e.slice(1); if(mfp.st.callbacks[e]) { mfp.st.callbacks[e].apply(mfp, $.isArray(data) ? data : [data]); } } }, _getCloseBtn = function(type) { if(type !== _currPopupType || !mfp.currTemplate.closeBtn) { mfp.currTemplate.closeBtn = $( mfp.st.closeMarkup.replace('%title%', mfp.st.tClose ) ); _currPopupType = type; } return mfp.currTemplate.closeBtn; }, // Initialize Magnific Popup only when called at least once _checkInstance = function() { if(!$.magnificPopup.instance) { /*jshint -W020 */ mfp = new MagnificPopup(); mfp.init(); $.magnificPopup.instance = mfp; } }, // CSS transition detection, http://stackoverflow.com/questions/7264899/detect-css-transitions-using-javascript-and-without-modernizr supportsTransitions = function() { var s = document.createElement('p').style, // 's' for style. better to create an element if body yet to exist v = ['ms','O','Moz','Webkit']; // 'v' for vendor if( s['transition'] !== undefined ) { return true; } while( v.length ) { if( v.pop() + 'Transition' in s ) { return true; } } return false; }; /** * Public functions */ MagnificPopup.prototype = { constructor: MagnificPopup, /** * Initializes Magnific Popup plugin. * This function is triggered only once when $.fn.magnificPopup or $.magnificPopup is executed */ init: function() { var appVersion = navigator.appVersion; mfp.isLowIE = mfp.isIE8 = document.all && !document.addEventListener; mfp.isAndroid = (/android/gi).test(appVersion); mfp.isIOS = (/iphone|ipad|ipod/gi).test(appVersion); mfp.supportsTransition = supportsTransitions(); // We disable fixed positioned lightbox on devices that don't handle it nicely. // If you know a better way of detecting this - let me know. mfp.probablyMobile = (mfp.isAndroid || mfp.isIOS || /(Opera Mini)|Kindle|webOS|BlackBerry|(Opera Mobi)|(Windows Phone)|IEMobile/i.test(navigator.userAgent) ); _document = $(document); mfp.popupsCache = {}; }, /** * Opens popup * @param data [description] */ open: function(data) { var i; if(data.isObj === false) { // convert jQuery collection to array to avoid conflicts later mfp.items = data.items.toArray(); mfp.index = 0; var items = data.items, item; for(i = 0; i < items.length; i++) { item = items[i]; if(item.parsed) { item = item.el[0]; } if(item === data.el[0]) { mfp.index = i; break; } } } else { mfp.items = $.isArray(data.items) ? data.items : [data.items]; mfp.index = data.index || 0; } // if popup is already opened - we just update the content if(mfp.isOpen) { mfp.updateItemHTML(); return; } mfp.types = []; _wrapClasses = ''; if(data.mainEl && data.mainEl.length) { mfp.ev = data.mainEl.eq(0); } else { mfp.ev = _document; } if(data.key) { if(!mfp.popupsCache[data.key]) { mfp.popupsCache[data.key] = {}; } mfp.currTemplate = mfp.popupsCache[data.key]; } else { mfp.currTemplate = {}; } mfp.st = $.extend(true, {}, $.magnificPopup.defaults, data ); mfp.fixedContentPos = mfp.st.fixedContentPos === 'auto' ? !mfp.probablyMobile : mfp.st.fixedContentPos; if(mfp.st.modal) { mfp.st.closeOnContentClick = false; mfp.st.closeOnBgClick = false; mfp.st.showCloseBtn = false; mfp.st.enableEscapeKey = false; } // Building markup // main containers are created only once if(!mfp.bgOverlay) { // Dark overlay mfp.bgOverlay = _getEl('bg').on('click'+EVENT_NS, function() { mfp.close(); }); mfp.wrap = _getEl('wrap').attr('tabindex', -1).on('click'+EVENT_NS, function(e) { if(mfp._checkIfClose(e.target)) { mfp.close(); } }); mfp.container = _getEl('container', mfp.wrap); } mfp.contentContainer = _getEl('content'); if(mfp.st.preloader) { mfp.preloader = _getEl('preloader', mfp.container, mfp.st.tLoading); } // Initializing modules var modules = $.magnificPopup.modules; for(i = 0; i < modules.length; i++) { var n = modules[i]; n = n.charAt(0).toUpperCase() + n.slice(1); mfp['init'+n].call(mfp); } _mfpTrigger('BeforeOpen'); if(mfp.st.showCloseBtn) { // Close button if(!mfp.st.closeBtnInside) { mfp.wrap.append( _getCloseBtn() ); } else { _mfpOn(MARKUP_PARSE_EVENT, function(e, template, values, item) { values.close_replaceWith = _getCloseBtn(item.type); }); _wrapClasses += ' mfp-close-btn-in'; } } if(mfp.st.alignTop) { _wrapClasses += ' mfp-align-top'; } if(mfp.fixedContentPos) { mfp.wrap.css({ overflow: mfp.st.overflowY, overflowX: 'hidden', overflowY: mfp.st.overflowY }); } else { mfp.wrap.css({ top: _window.scrollTop(), position: 'absolute' }); } if( mfp.st.fixedBgPos === false || (mfp.st.fixedBgPos === 'auto' && !mfp.fixedContentPos) ) { mfp.bgOverlay.css({ height: _document.height(), position: 'absolute' }); } if(mfp.st.enableEscapeKey) { // Close on ESC key _document.on('keyup' + EVENT_NS, function(e) { if(e.keyCode === 27) { mfp.close(); } }); } _window.on('resize' + EVENT_NS, function() { mfp.updateSize(); }); if(!mfp.st.closeOnContentClick) { _wrapClasses += ' mfp-auto-cursor'; } if(_wrapClasses) mfp.wrap.addClass(_wrapClasses); // this triggers recalculation of layout, so we get it once to not to trigger twice var windowHeight = mfp.wH = _window.height(); var windowStyles = {}; if( mfp.fixedContentPos ) { if(mfp._hasScrollBar(windowHeight)){ var s = mfp._getScrollbarSize(); if(s) { windowStyles.marginRight = s; } } } if(mfp.fixedContentPos) { if(!mfp.isIE7) { windowStyles.overflow = 'hidden'; } else { // ie7 double-scroll bug $('body, html').css('overflow', 'hidden'); } } var classesToadd = mfp.st.mainClass; if(mfp.isIE7) { classesToadd += ' mfp-ie7'; } if(classesToadd) { mfp._addClassToMFP( classesToadd ); } // add content mfp.updateItemHTML(); _mfpTrigger('BuildControls'); // remove scrollbar, add margin e.t.c $('html').css(windowStyles); // add everything to DOM mfp.bgOverlay.add(mfp.wrap).prependTo( mfp.st.prependTo || $(document.body) ); // Save last focused element mfp._lastFocusedEl = document.activeElement; // Wait for next cycle to allow CSS transition setTimeout(function() { if(mfp.content) { mfp._addClassToMFP(READY_CLASS); mfp._setFocus(); } else { // if content is not defined (not loaded e.t.c) we add class only for BG mfp.bgOverlay.addClass(READY_CLASS); } // Trap the focus in popup _document.on('focusin' + EVENT_NS, mfp._onFocusIn); }, 16); mfp.isOpen = true; mfp.updateSize(windowHeight); _mfpTrigger(OPEN_EVENT); return data; }, /** * Closes the popup */ close: function() { if(!mfp.isOpen) return; _mfpTrigger(BEFORE_CLOSE_EVENT); mfp.isOpen = false; // for CSS3 animation if(mfp.st.removalDelay && !mfp.isLowIE && mfp.supportsTransition ) { mfp._addClassToMFP(REMOVING_CLASS); setTimeout(function() { mfp._close(); }, mfp.st.removalDelay); } else { mfp._close(); } }, /** * Helper for close() function */ _close: function() { _mfpTrigger(CLOSE_EVENT); var classesToRemove = REMOVING_CLASS + ' ' + READY_CLASS + ' '; mfp.bgOverlay.detach(); mfp.wrap.detach(); mfp.container.empty(); if(mfp.st.mainClass) { classesToRemove += mfp.st.mainClass + ' '; } mfp._removeClassFromMFP(classesToRemove); if(mfp.fixedContentPos) { var windowStyles = {marginRight: ''}; if(mfp.isIE7) { $('body, html').css('overflow', ''); } else { windowStyles.overflow = ''; } $('html').css(windowStyles); } _document.off('keyup' + EVENT_NS + ' focusin' + EVENT_NS); mfp.ev.off(EVENT_NS); // clean up DOM elements that aren't removed mfp.wrap.attr('class', 'mfp-wrap').removeAttr('style'); mfp.bgOverlay.attr('class', 'mfp-bg'); mfp.container.attr('class', 'mfp-container'); // remove close button from target element if(mfp.st.showCloseBtn && (!mfp.st.closeBtnInside || mfp.currTemplate[mfp.currItem.type] === true)) { if(mfp.currTemplate.closeBtn) mfp.currTemplate.closeBtn.detach(); } if(mfp.st.autoFocusLast && mfp._lastFocusedEl) { $(mfp._lastFocusedEl).focus(); // put tab focus back } mfp.currItem = null; mfp.content = null; mfp.currTemplate = null; mfp.prevHeight = 0; _mfpTrigger(AFTER_CLOSE_EVENT); }, updateSize: function(winHeight) { if(mfp.isIOS) { // fixes iOS nav bars https://github.com/dimsemenov/Magnific-Popup/issues/2 var zoomLevel = document.documentElement.clientWidth / window.innerWidth; var height = window.innerHeight * zoomLevel; mfp.wrap.css('height', height); mfp.wH = height; } else { mfp.wH = winHeight || _window.height(); } // Fixes #84: popup incorrectly positioned with position:relative on body if(!mfp.fixedContentPos) { mfp.wrap.css('height', mfp.wH); } _mfpTrigger('Resize'); }, /** * Set content of popup based on current index */ updateItemHTML: function() { var item = mfp.items[mfp.index]; // Detach and perform modifications mfp.contentContainer.detach(); if(mfp.content) mfp.content.detach(); if(!item.parsed) { item = mfp.parseEl( mfp.index ); } var type = item.type; _mfpTrigger('BeforeChange', [mfp.currItem ? mfp.currItem.type : '', type]); // BeforeChange event works like so: // _mfpOn('BeforeChange', function(e, prevType, newType) { }); mfp.currItem = item; if(!mfp.currTemplate[type]) { var markup = mfp.st[type] ? mfp.st[type].markup : false; // allows to modify markup _mfpTrigger('FirstMarkupParse', markup); if(markup) { mfp.currTemplate[type] = $(markup); } else { // if there is no markup found we just define that template is parsed mfp.currTemplate[type] = true; } } if(_prevContentType && _prevContentType !== item.type) { mfp.container.removeClass('mfp-'+_prevContentType+'-holder'); } var newContent = mfp['get' + type.charAt(0).toUpperCase() + type.slice(1)](item, mfp.currTemplate[type]); mfp.appendContent(newContent, type); item.preloaded = true; _mfpTrigger(CHANGE_EVENT, item); _prevContentType = item.type; // Append container back after its content changed mfp.container.prepend(mfp.contentContainer); _mfpTrigger('AfterChange'); }, /** * Set HTML content of popup */ appendContent: function(newContent, type) { mfp.content = newContent; if(newContent) { if(mfp.st.showCloseBtn && mfp.st.closeBtnInside && mfp.currTemplate[type] === true) { // if there is no markup, we just append close button element inside if(!mfp.content.find('.mfp-close').length) { mfp.content.append(_getCloseBtn()); } } else { mfp.content = newContent; } } else { mfp.content = ''; } _mfpTrigger(BEFORE_APPEND_EVENT); mfp.container.addClass('mfp-'+type+'-holder'); mfp.contentContainer.append(mfp.content); }, /** * Creates Magnific Popup data object based on given data * @param {int} index Index of item to parse */ parseEl: function(index) { var item = mfp.items[index], type; if(item.tagName) { item = { el: $(item) }; } else { type = item.type; item = { data: item, src: item.src }; } if(item.el) { var types = mfp.types; // check for 'mfp-TYPE' class for(var i = 0; i < types.length; i++) { if( item.el.hasClass('mfp-'+types[i]) ) { type = types[i]; break; } } item.src = item.el.attr('data-mfp-src'); if(!item.src) { item.src = item.el.attr('href'); } } item.type = type || mfp.st.type || 'inline'; item.index = index; item.parsed = true; mfp.items[index] = item; _mfpTrigger('ElementParse', item); return mfp.items[index]; }, /** * Initializes single popup or a group of popups */ addGroup: function(el, options) { var eHandler = function(e) { e.mfpEl = this; mfp._openClick(e, el, options); }; if(!options) { options = {}; } var eName = 'click.magnificPopup'; options.mainEl = el; if(options.items) { options.isObj = true; el.off(eName).on(eName, eHandler); } else { options.isObj = false; if(options.delegate) { el.off(eName).on(eName, options.delegate , eHandler); } else { options.items = el; el.off(eName).on(eName, eHandler); } } }, _openClick: function(e, el, options) { var midClick = options.midClick !== undefined ? options.midClick : $.magnificPopup.defaults.midClick; if(!midClick && ( e.which === 2 || e.ctrlKey || e.metaKey || e.altKey || e.shiftKey ) ) { return; } var disableOn = options.disableOn !== undefined ? options.disableOn : $.magnificPopup.defaults.disableOn; if(disableOn) { if($.isFunction(disableOn)) { if( !disableOn.call(mfp) ) { return true; } } else { // else it's number if( _window.width() < disableOn ) { return true; } } } if(e.type) { e.preventDefault(); // This will prevent popup from closing if element is inside and popup is already opened if(mfp.isOpen) { e.stopPropagation(); } } options.el = $(e.mfpEl); if(options.delegate) { options.items = el.find(options.delegate); } mfp.open(options); }, /** * Updates text on preloader */ updateStatus: function(status, text) { if(mfp.preloader) { if(_prevStatus !== status) { mfp.container.removeClass('mfp-s-'+_prevStatus); } if(!text && status === 'loading') { text = mfp.st.tLoading; } var data = { status: status, text: text }; // allows to modify status _mfpTrigger('UpdateStatus', data); status = data.status; text = data.text; mfp.preloader.html(text); mfp.preloader.find('a').on('click', function(e) { e.stopImmediatePropagation(); }); mfp.container.addClass('mfp-s-'+status); _prevStatus = status; } }, /* "Private" helpers that aren't private at all */ // Check to close popup or not // "target" is an element that was clicked _checkIfClose: function(target) { if($(target).hasClass(PREVENT_CLOSE_CLASS)) { return; } var closeOnContent = mfp.st.closeOnContentClick; var closeOnBg = mfp.st.closeOnBgClick; if(closeOnContent && closeOnBg) { return true; } else { // We close the popup if click is on close button or on preloader. Or if there is no content. if(!mfp.content || $(target).hasClass('mfp-close') || (mfp.preloader && target === mfp.preloader[0]) ) { return true; } // if click is outside the content if( (target !== mfp.content[0] && !$.contains(mfp.content[0], target)) ) { if(closeOnBg) { // last check, if the clicked element is in DOM, (in case it's removed onclick) if( $.contains(document, target) ) { return true; } } } else if(closeOnContent) { return true; } } return false; }, _addClassToMFP: function(cName) { mfp.bgOverlay.addClass(cName); mfp.wrap.addClass(cName); }, _removeClassFromMFP: function(cName) { this.bgOverlay.removeClass(cName); mfp.wrap.removeClass(cName); }, _hasScrollBar: function(winHeight) { return ( (mfp.isIE7 ? _document.height() : document.body.scrollHeight) > (winHeight || _window.height()) ); }, _setFocus: function() { (mfp.st.focus ? mfp.content.find(mfp.st.focus).eq(0) : mfp.wrap).focus(); }, _onFocusIn: function(e) { if( e.target !== mfp.wrap[0] && !$.contains(mfp.wrap[0], e.target) ) { mfp._setFocus(); return false; } }, _parseMarkup: function(template, values, item) { var arr; if(item.data) { values = $.extend(item.data, values); } _mfpTrigger(MARKUP_PARSE_EVENT, [template, values, item] ); $.each(values, function(key, value) { if(value === undefined || value === false) { return true; } arr = key.split('_'); if(arr.length > 1) { var el = template.find(EVENT_NS + '-'+arr[0]); if(el.length > 0) { var attr = arr[1]; if(attr === 'replaceWith') { if(el[0] !== value[0]) { el.replaceWith(value); } } else if(attr === 'img') { if(el.is('img')) { el.attr('src', value); } else { el.replaceWith( $('').attr('src', value).attr('class', el.attr('class')) ); } } else { el.attr(arr[1], value); } } } else { template.find(EVENT_NS + '-'+key).html(value); } }); }, _getScrollbarSize: function() { // thx David if(mfp.scrollbarSize === undefined) { var scrollDiv = document.createElement("div"); scrollDiv.style.cssText = 'width: 99px; height: 99px; overflow: scroll; position: absolute; top: -9999px;'; document.body.appendChild(scrollDiv); mfp.scrollbarSize = scrollDiv.offsetWidth - scrollDiv.clientWidth; document.body.removeChild(scrollDiv); } return mfp.scrollbarSize; } }; /* MagnificPopup core prototype end */ /** * Public static functions */ $.magnificPopup = { instance: null, proto: MagnificPopup.prototype, modules: [], open: function(options, index) { _checkInstance(); if(!options) { options = {}; } else { options = $.extend(true, {}, options); } options.isObj = true; options.index = index || 0; return this.instance.open(options); }, close: function() { return $.magnificPopup.instance && $.magnificPopup.instance.close(); }, registerModule: function(name, module) { if(module.options) { $.magnificPopup.defaults[name] = module.options; } $.extend(this.proto, module.proto); this.modules.push(name); }, defaults: { // Info about options is in docs: // http://dimsemenov.com/plugins/magnific-popup/documentation.html#options disableOn: 0, key: null, midClick: false, mainClass: '', preloader: true, focus: '', // CSS selector of input to focus after popup is opened closeOnContentClick: false, closeOnBgClick: true, closeBtnInside: true, showCloseBtn: true, enableEscapeKey: true, modal: false, alignTop: false, removalDelay: 0, prependTo: null, fixedContentPos: 'auto', fixedBgPos: 'auto', overflowY: 'auto', closeMarkup: '', tClose: 'Close (Esc)', tLoading: 'Loading...', autoFocusLast: true } }; $.fn.magnificPopup = function(options) { _checkInstance(); var jqEl = $(this); // We call some API method of first param is a string if (typeof options === "string" ) { if(options === 'open') { var items, itemOpts = _isJQ ? jqEl.data('magnificPopup') : jqEl[0].magnificPopup, index = parseInt(arguments[1], 10) || 0; if(itemOpts.items) { items = itemOpts.items[index]; } else { items = jqEl; if(itemOpts.delegate) { items = items.find(itemOpts.delegate); } items = items.eq( index ); } mfp._openClick({mfpEl:items}, jqEl, itemOpts); } else { if(mfp.isOpen) mfp[options].apply(mfp, Array.prototype.slice.call(arguments, 1)); } } else { // clone options obj options = $.extend(true, {}, options); /* * As Zepto doesn't support .data() method for objects * and it works only in normal browsers * we assign "options" object directly to the DOM element. FTW! */ if(_isJQ) { jqEl.data('magnificPopup', options); } else { jqEl[0].magnificPopup = options; } mfp.addGroup(jqEl, options); } return jqEl; }; /*>>core*/ /*>>inline*/ var INLINE_NS = 'inline', _hiddenClass, _inlinePlaceholder, _lastInlineElement, _putInlineElementsBack = function() { if(_lastInlineElement) { _inlinePlaceholder.after( _lastInlineElement.addClass(_hiddenClass) ).detach(); _lastInlineElement = null; } }; $.magnificPopup.registerModule(INLINE_NS, { options: { hiddenClass: 'hide', // will be appended with `mfp-` prefix markup: '', tNotFound: 'Content not found' }, proto: { initInline: function() { mfp.types.push(INLINE_NS); _mfpOn(CLOSE_EVENT+'.'+INLINE_NS, function() { _putInlineElementsBack(); }); }, getInline: function(item, template) { _putInlineElementsBack(); if(item.src) { var inlineSt = mfp.st.inline, el = $(item.src); if(el.length) { // If target element has parent - we replace it with placeholder and put it back after popup is closed var parent = el[0].parentNode; if(parent && parent.tagName) { if(!_inlinePlaceholder) { _hiddenClass = inlineSt.hiddenClass; _inlinePlaceholder = _getEl(_hiddenClass); _hiddenClass = 'mfp-'+_hiddenClass; } // replace target inline element with placeholder _lastInlineElement = el.after(_inlinePlaceholder).detach().removeClass(_hiddenClass); } mfp.updateStatus('ready'); } else { mfp.updateStatus('error', inlineSt.tNotFound); el = $('
    '); } item.inlineElement = el; return el; } mfp.updateStatus('ready'); mfp._parseMarkup(template, {}, item); return template; } } }); /*>>inline*/ /*>>ajax*/ var AJAX_NS = 'ajax', _ajaxCur, _removeAjaxCursor = function() { if(_ajaxCur) { $(document.body).removeClass(_ajaxCur); } }, _destroyAjaxRequest = function() { _removeAjaxCursor(); if(mfp.req) { mfp.req.abort(); } }; $.magnificPopup.registerModule(AJAX_NS, { options: { settings: null, cursor: 'mfp-ajax-cur', tError: 'The content could not be loaded.' }, proto: { initAjax: function() { mfp.types.push(AJAX_NS); _ajaxCur = mfp.st.ajax.cursor; _mfpOn(CLOSE_EVENT+'.'+AJAX_NS, _destroyAjaxRequest); _mfpOn('BeforeChange.' + AJAX_NS, _destroyAjaxRequest); }, getAjax: function(item) { if(_ajaxCur) { $(document.body).addClass(_ajaxCur); } mfp.updateStatus('loading'); var opts = $.extend({ url: item.src, success: function(data, textStatus, jqXHR) { var temp = { data:data, xhr:jqXHR }; _mfpTrigger('ParseAjax', temp); mfp.appendContent( $(temp.data), AJAX_NS ); item.finished = true; _removeAjaxCursor(); mfp._setFocus(); setTimeout(function() { mfp.wrap.addClass(READY_CLASS); }, 16); mfp.updateStatus('ready'); _mfpTrigger('AjaxContentAdded'); }, error: function() { _removeAjaxCursor(); item.finished = item.loadError = true; mfp.updateStatus('error', mfp.st.ajax.tError.replace('%url%', item.src)); } }, mfp.st.ajax.settings); mfp.req = $.ajax(opts); return ''; } } }); /*>>ajax*/ /*>>image*/ var _imgInterval, _getTitle = function(item) { if(item.data && item.data.title !== undefined) return item.data.title; var src = mfp.st.image.titleSrc; if(src) { if($.isFunction(src)) { return src.call(mfp, item); } else if(item.el) { return item.el.attr(src) || ''; } } return ''; }; $.magnificPopup.registerModule('image', { options: { markup: '
    '+ '
    '+ '
    '+ '
    '+ '
    '+ '
    '+ '
    '+ '
    '+ '
    '+ '
    '+ '
    '+ '
    ', cursor: 'mfp-zoom-out-cur', titleSrc: 'title', verticalFit: true, tError: 'The image could not be loaded.' }, proto: { initImage: function() { var imgSt = mfp.st.image, ns = '.image'; mfp.types.push('image'); _mfpOn(OPEN_EVENT+ns, function() { if(mfp.currItem.type === 'image' && imgSt.cursor) { $(document.body).addClass(imgSt.cursor); } }); _mfpOn(CLOSE_EVENT+ns, function() { if(imgSt.cursor) { $(document.body).removeClass(imgSt.cursor); } _window.off('resize' + EVENT_NS); }); _mfpOn('Resize'+ns, mfp.resizeImage); if(mfp.isLowIE) { _mfpOn('AfterChange', mfp.resizeImage); } }, resizeImage: function() { var item = mfp.currItem; if(!item || !item.img) return; if(mfp.st.image.verticalFit) { var decr = 0; // fix box-sizing in ie7/8 if(mfp.isLowIE) { decr = parseInt(item.img.css('padding-top'), 10) + parseInt(item.img.css('padding-bottom'),10); } item.img.css('max-height', mfp.wH-decr); } }, _onImageHasSize: function(item) { if(item.img) { item.hasSize = true; if(_imgInterval) { clearInterval(_imgInterval); } item.isCheckingImgSize = false; _mfpTrigger('ImageHasSize', item); if(item.imgHidden) { if(mfp.content) mfp.content.removeClass('mfp-loading'); item.imgHidden = false; } } }, /** * Function that loops until the image has size to display elements that rely on it asap */ findImageSize: function(item) { var counter = 0, img = item.img[0], mfpSetInterval = function(delay) { if(_imgInterval) { clearInterval(_imgInterval); } // decelerating interval that checks for size of an image _imgInterval = setInterval(function() { if(img.naturalWidth > 0) { mfp._onImageHasSize(item); return; } if(counter > 200) { clearInterval(_imgInterval); } counter++; if(counter === 3) { mfpSetInterval(10); } else if(counter === 40) { mfpSetInterval(50); } else if(counter === 100) { mfpSetInterval(500); } }, delay); }; mfpSetInterval(1); }, getImage: function(item, template) { var guard = 0, // image load complete handler onLoadComplete = function() { if(item) { if (item.img[0].complete) { item.img.off('.mfploader'); if(item === mfp.currItem){ mfp._onImageHasSize(item); mfp.updateStatus('ready'); } item.hasSize = true; item.loaded = true; _mfpTrigger('ImageLoadComplete'); } else { // if image complete check fails 200 times (20 sec), we assume that there was an error. guard++; if(guard < 200) { setTimeout(onLoadComplete,100); } else { onLoadError(); } } } }, // image error handler onLoadError = function() { if(item) { item.img.off('.mfploader'); if(item === mfp.currItem){ mfp._onImageHasSize(item); mfp.updateStatus('error', imgSt.tError.replace('%url%', item.src) ); } item.hasSize = true; item.loaded = true; item.loadError = true; } }, imgSt = mfp.st.image; var el = template.find('.mfp-img'); if(el.length) { var img = document.createElement('img'); img.className = 'mfp-img'; if(item.el && item.el.find('img').length) { img.alt = item.el.find('img').attr('alt'); } item.img = $(img).on('load.mfploader', onLoadComplete).on('error.mfploader', onLoadError); img.src = item.src; // without clone() "error" event is not firing when IMG is replaced by new IMG // TODO: find a way to avoid such cloning if(el.is('img')) { item.img = item.img.clone(); } img = item.img[0]; if(img.naturalWidth > 0) { item.hasSize = true; } else if(!img.width) { item.hasSize = false; } } mfp._parseMarkup(template, { title: _getTitle(item), img_replaceWith: item.img }, item); mfp.resizeImage(); if(item.hasSize) { if(_imgInterval) clearInterval(_imgInterval); if(item.loadError) { template.addClass('mfp-loading'); mfp.updateStatus('error', imgSt.tError.replace('%url%', item.src) ); } else { template.removeClass('mfp-loading'); mfp.updateStatus('ready'); } return template; } mfp.updateStatus('loading'); item.loading = true; if(!item.hasSize) { item.imgHidden = true; template.addClass('mfp-loading'); mfp.findImageSize(item); } return template; } } }); /*>>image*/ /*>>zoom*/ var hasMozTransform, getHasMozTransform = function() { if(hasMozTransform === undefined) { hasMozTransform = document.createElement('p').style.MozTransform !== undefined; } return hasMozTransform; }; $.magnificPopup.registerModule('zoom', { options: { enabled: false, easing: 'ease-in-out', duration: 300, opener: function(element) { return element.is('img') ? element : element.find('img'); } }, proto: { initZoom: function() { var zoomSt = mfp.st.zoom, ns = '.zoom', image; if(!zoomSt.enabled || !mfp.supportsTransition) { return; } var duration = zoomSt.duration, getElToAnimate = function(image) { var newImg = image.clone().removeAttr('style').removeAttr('class').addClass('mfp-animated-image'), transition = 'all '+(zoomSt.duration/1000)+'s ' + zoomSt.easing, cssObj = { position: 'fixed', zIndex: 9999, left: 0, top: 0, '-webkit-backface-visibility': 'hidden' }, t = 'transition'; cssObj['-webkit-'+t] = cssObj['-moz-'+t] = cssObj['-o-'+t] = cssObj[t] = transition; newImg.css(cssObj); return newImg; }, showMainContent = function() { mfp.content.css('visibility', 'visible'); }, openTimeout, animatedImg; _mfpOn('BuildControls'+ns, function() { if(mfp._allowZoom()) { clearTimeout(openTimeout); mfp.content.css('visibility', 'hidden'); // Basically, all code below does is clones existing image, puts in on top of the current one and animated it image = mfp._getItemToZoom(); if(!image) { showMainContent(); return; } animatedImg = getElToAnimate(image); animatedImg.css( mfp._getOffset() ); mfp.wrap.append(animatedImg); openTimeout = setTimeout(function() { animatedImg.css( mfp._getOffset( true ) ); openTimeout = setTimeout(function() { showMainContent(); setTimeout(function() { animatedImg.remove(); image = animatedImg = null; _mfpTrigger('ZoomAnimationEnded'); }, 16); // avoid blink when switching images }, duration); // this timeout equals animation duration }, 16); // by adding this timeout we avoid short glitch at the beginning of animation // Lots of timeouts... } }); _mfpOn(BEFORE_CLOSE_EVENT+ns, function() { if(mfp._allowZoom()) { clearTimeout(openTimeout); mfp.st.removalDelay = duration; if(!image) { image = mfp._getItemToZoom(); if(!image) { return; } animatedImg = getElToAnimate(image); } animatedImg.css( mfp._getOffset(true) ); mfp.wrap.append(animatedImg); mfp.content.css('visibility', 'hidden'); setTimeout(function() { animatedImg.css( mfp._getOffset() ); }, 16); } }); _mfpOn(CLOSE_EVENT+ns, function() { if(mfp._allowZoom()) { showMainContent(); if(animatedImg) { animatedImg.remove(); } image = null; } }); }, _allowZoom: function() { return mfp.currItem.type === 'image'; }, _getItemToZoom: function() { if(mfp.currItem.hasSize) { return mfp.currItem.img; } else { return false; } }, // Get element postion relative to viewport _getOffset: function(isLarge) { var el; if(isLarge) { el = mfp.currItem.img; } else { el = mfp.st.zoom.opener(mfp.currItem.el || mfp.currItem); } var offset = el.offset(); var paddingTop = parseInt(el.css('padding-top'),10); var paddingBottom = parseInt(el.css('padding-bottom'),10); offset.top -= ( $(window).scrollTop() - paddingTop ); /* Animating left + top + width/height looks glitchy in Firefox, but perfect in Chrome. And vice-versa. */ var obj = { width: el.width(), // fix Zepto height+padding issue height: (_isJQ ? el.innerHeight() : el[0].offsetHeight) - paddingBottom - paddingTop }; // I hate to do this, but there is no another option if( getHasMozTransform() ) { obj['-moz-transform'] = obj['transform'] = 'translate(' + offset.left + 'px,' + offset.top + 'px)'; } else { obj.left = offset.left; obj.top = offset.top; } return obj; } } }); /*>>zoom*/ /*>>iframe*/ var IFRAME_NS = 'iframe', _emptyPage = '//about:blank', _fixIframeBugs = function(isShowing) { if(mfp.currTemplate[IFRAME_NS]) { var el = mfp.currTemplate[IFRAME_NS].find('iframe'); if(el.length) { // reset src after the popup is closed to avoid "video keeps playing after popup is closed" bug if(!isShowing) { el[0].src = _emptyPage; } // IE8 black screen bug fix if(mfp.isIE8) { el.css('display', isShowing ? 'block' : 'none'); } } } }; $.magnificPopup.registerModule(IFRAME_NS, { options: { markup: '
    '+ '
    '+ ''+ '
    ', srcAction: 'iframe_src', // we don't care and support only one default type of URL by default patterns: { youtube: { index: 'youtube.com', id: 'v=', src: '//www.youtube.com/embed/%id%?autoplay=1' }, vimeo: { index: 'vimeo.com/', id: '/', src: '//player.vimeo.com/video/%id%?autoplay=1' }, gmaps: { index: '//maps.google.', src: '%id%&output=embed' } } }, proto: { initIframe: function() { mfp.types.push(IFRAME_NS); _mfpOn('BeforeChange', function(e, prevType, newType) { if(prevType !== newType) { if(prevType === IFRAME_NS) { _fixIframeBugs(); // iframe if removed } else if(newType === IFRAME_NS) { _fixIframeBugs(true); // iframe is showing } }// else { // iframe source is switched, don't do anything //} }); _mfpOn(CLOSE_EVENT + '.' + IFRAME_NS, function() { _fixIframeBugs(); }); }, getIframe: function(item, template) { var embedSrc = item.src; var iframeSt = mfp.st.iframe; $.each(iframeSt.patterns, function() { if(embedSrc.indexOf( this.index ) > -1) { if(this.id) { if(typeof this.id === 'string') { embedSrc = embedSrc.substr(embedSrc.lastIndexOf(this.id)+this.id.length, embedSrc.length); } else { embedSrc = this.id.call( this, embedSrc ); } } embedSrc = this.src.replace('%id%', embedSrc ); return false; // break; } }); var dataObj = {}; if(iframeSt.srcAction) { dataObj[iframeSt.srcAction] = embedSrc; } mfp._parseMarkup(template, dataObj, item); mfp.updateStatus('ready'); return template; } } }); /*>>iframe*/ /*>>gallery*/ /** * Get looped index depending on number of slides */ var _getLoopedId = function(index) { var numSlides = mfp.items.length; if(index > numSlides - 1) { return index - numSlides; } else if(index < 0) { return numSlides + index; } return index; }, _replaceCurrTotal = function(text, curr, total) { return text.replace(/%curr%/gi, curr + 1).replace(/%total%/gi, total); }; $.magnificPopup.registerModule('gallery', { options: { enabled: false, arrowMarkup: '', preload: [0,2], navigateByImgClick: true, arrows: true, tPrev: 'Previous (Left arrow key)', tNext: 'Next (Right arrow key)', tCounter: '%curr% of %total%' }, proto: { initGallery: function() { var gSt = mfp.st.gallery, ns = '.mfp-gallery'; mfp.direction = true; // true - next, false - prev if(!gSt || !gSt.enabled ) return false; _wrapClasses += ' mfp-gallery'; _mfpOn(OPEN_EVENT+ns, function() { if(gSt.navigateByImgClick) { mfp.wrap.on('click'+ns, '.mfp-img', function() { if(mfp.items.length > 1) { mfp.next(); return false; } }); } _document.on('keydown'+ns, function(e) { if (e.keyCode === 37) { mfp.prev(); } else if (e.keyCode === 39) { mfp.next(); } }); }); _mfpOn('UpdateStatus'+ns, function(e, data) { if(data.text) { data.text = _replaceCurrTotal(data.text, mfp.currItem.index, mfp.items.length); } }); _mfpOn(MARKUP_PARSE_EVENT+ns, function(e, element, values, item) { var l = mfp.items.length; values.counter = l > 1 ? _replaceCurrTotal(gSt.tCounter, item.index, l) : ''; }); _mfpOn('BuildControls' + ns, function() { if(mfp.items.length > 1 && gSt.arrows && !mfp.arrowLeft) { var markup = gSt.arrowMarkup, arrowLeft = mfp.arrowLeft = $( markup.replace(/%title%/gi, gSt.tPrev).replace(/%dir%/gi, 'left') ).addClass(PREVENT_CLOSE_CLASS), arrowRight = mfp.arrowRight = $( markup.replace(/%title%/gi, gSt.tNext).replace(/%dir%/gi, 'right') ).addClass(PREVENT_CLOSE_CLASS); arrowLeft.click(function() { mfp.prev(); }); arrowRight.click(function() { mfp.next(); }); mfp.container.append(arrowLeft.add(arrowRight)); } }); _mfpOn(CHANGE_EVENT+ns, function() { if(mfp._preloadTimeout) clearTimeout(mfp._preloadTimeout); mfp._preloadTimeout = setTimeout(function() { mfp.preloadNearbyImages(); mfp._preloadTimeout = null; }, 16); }); _mfpOn(CLOSE_EVENT+ns, function() { _document.off(ns); mfp.wrap.off('click'+ns); mfp.arrowRight = mfp.arrowLeft = null; }); }, next: function() { mfp.direction = true; mfp.index = _getLoopedId(mfp.index + 1); mfp.updateItemHTML(); }, prev: function() { mfp.direction = false; mfp.index = _getLoopedId(mfp.index - 1); mfp.updateItemHTML(); }, goTo: function(newIndex) { mfp.direction = (newIndex >= mfp.index); mfp.index = newIndex; mfp.updateItemHTML(); }, preloadNearbyImages: function() { var p = mfp.st.gallery.preload, preloadBefore = Math.min(p[0], mfp.items.length), preloadAfter = Math.min(p[1], mfp.items.length), i; for(i = 1; i <= (mfp.direction ? preloadAfter : preloadBefore); i++) { mfp._preloadItem(mfp.index+i); } for(i = 1; i <= (mfp.direction ? preloadBefore : preloadAfter); i++) { mfp._preloadItem(mfp.index-i); } }, _preloadItem: function(index) { index = _getLoopedId(index); if(mfp.items[index].preloaded) { return; } var item = mfp.items[index]; if(!item.parsed) { item = mfp.parseEl( index ); } _mfpTrigger('LazyLoad', item); if(item.type === 'image') { item.img = $('').on('load.mfploader', function() { item.hasSize = true; }).on('error.mfploader', function() { item.hasSize = true; item.loadError = true; _mfpTrigger('LazyLoadError', item); }).attr('src', item.src); } item.preloaded = true; } } }); /*>>gallery*/ /*>>retina*/ var RETINA_NS = 'retina'; $.magnificPopup.registerModule(RETINA_NS, { options: { replaceSrc: function(item) { return item.src.replace(/\.\w+$/, function(m) { return '@2x' + m; }); }, ratio: 1 // Function or number. Set to 1 to disable. }, proto: { initRetina: function() { if(window.devicePixelRatio > 1) { var st = mfp.st.retina, ratio = st.ratio; ratio = !isNaN(ratio) ? ratio : ratio(); if(ratio > 1) { _mfpOn('ImageHasSize' + '.' + RETINA_NS, function(e, item) { item.img.css({ 'max-width': item.img[0].naturalWidth / ratio, 'width': '100%' }); }); _mfpOn('ElementParse' + '.' + RETINA_NS, function(e, item) { item.src = st.replaceSrc(item, ratio); }); } } } } }); /*>>retina*/ _checkInstance(); })); /*! jQuery Validation Plugin - v1.17.0 - 7/29/2017 * https://jqueryvalidation.org/ * Copyright (c) 2017 Jæžšrn Zaefferer; Licensed MIT */ !function(a){"function"==typeof define&&define.amd?define(["jquery"],a):"object"==typeof module&&module.exports?module.exports=a(require("jquery")):a(jQuery)}(function(a){a.extend(a.fn,{validate:function(b){if(!this.length)return void(b&&b.debug&&window.console&&console.warn("Nothing selected, can't validate, returning nothing."));var c=a.data(this[0],"validator");return c?c:(this.attr("novalidate","novalidate"),c=new a.validator(b,this[0]),a.data(this[0],"validator",c),c.settings.onsubmit&&(this.on("click.validate",":submit",function(b){c.submitButton=b.currentTarget,a(this).hasClass("cancel")&&(c.cancelSubmit=!0),void 0!==a(this).attr("formnovalidate")&&(c.cancelSubmit=!0)}),this.on("submit.validate",function(b){function d(){var d,e;return c.submitButton&&(c.settings.submitHandler||c.formSubmitted)&&(d=a("").attr("name",c.submitButton.name).val(a(c.submitButton).val()).appendTo(c.currentForm)),!c.settings.submitHandler||(e=c.settings.submitHandler.call(c,c.currentForm,b),d&&d.remove(),void 0!==e&&e)}return c.settings.debug&&b.preventDefault(),c.cancelSubmit?(c.cancelSubmit=!1,d()):c.form()?c.pendingRequest?(c.formSubmitted=!0,!1):d():(c.focusInvalid(),!1)})),c)},valid:function(){var b,c,d;return a(this[0]).is("form")?b=this.validate().form():(d=[],b=!0,c=a(this[0].form).validate(),this.each(function(){b=c.element(this)&&b,b||(d=d.concat(c.errorList))}),c.errorList=d),b},rules:function(b,c){var d,e,f,g,h,i,j=this[0];if(null!=j&&(!j.form&&j.hasAttribute("contenteditable")&&(j.form=this.closest("form")[0],j.name=this.attr("name")),null!=j.form)){if(b)switch(d=a.data(j.form,"validator").settings,e=d.rules,f=a.validator.staticRules(j),b){case"add":a.extend(f,a.validator.normalizeRule(c)),delete f.messages,e[j.name]=f,c.messages&&(d.messages[j.name]=a.extend(d.messages[j.name],c.messages));break;case"remove":return c?(i={},a.each(c.split(/\s/),function(a,b){i[b]=f[b],delete f[b]}),i):(delete e[j.name],f)}return g=a.validator.normalizeRules(a.extend({},a.validator.classRules(j),a.validator.attributeRules(j),a.validator.dataRules(j),a.validator.staticRules(j)),j),g.required&&(h=g.required,delete g.required,g=a.extend({required:h},g)),g.remote&&(h=g.remote,delete g.remote,g=a.extend(g,{remote:h})),g}}}),a.extend(a.expr.pseudos||a.expr[":"],{blank:function(b){return!a.trim(""+a(b).val())},filled:function(b){var c=a(b).val();return null!==c&&!!a.trim(""+c)},unchecked:function(b){return!a(b).prop("checked")}}),a.validator=function(b,c){this.settings=a.extend(!0,{},a.validator.defaults,b),this.currentForm=c,this.init()},a.validator.format=function(b,c){return 1===arguments.length?function(){var c=a.makeArray(arguments);return c.unshift(b),a.validator.format.apply(this,c)}:void 0===c?b:(arguments.length>2&&c.constructor!==Array&&(c=a.makeArray(arguments).slice(1)),c.constructor!==Array&&(c=[c]),a.each(c,function(a,c){b=b.replace(new RegExp("\\{"+a+"\\}","g"),function(){return c})}),b)},a.extend(a.validator,{defaults:{messages:{},groups:{},rules:{},errorClass:"error",pendingClass:"pending",validClass:"valid",errorElement:"label",focusCleanup:!1,focusInvalid:!0,errorContainer:a([]),errorLabelContainer:a([]),onsubmit:!0,ignore:":hidden",ignoreTitle:!1,onfocusin:function(a){this.lastActive=a,this.settings.focusCleanup&&(this.settings.unhighlight&&this.settings.unhighlight.call(this,a,this.settings.errorClass,this.settings.validClass),this.hideThese(this.errorsFor(a)))},onfocusout:function(a){this.checkable(a)||!(a.name in this.submitted)&&this.optional(a)||this.element(a)},onkeyup:function(b,c){var d=[16,17,18,20,35,36,37,38,39,40,45,144,225];9===c.which&&""===this.elementValue(b)||a.inArray(c.keyCode,d)!==-1||(b.name in this.submitted||b.name in this.invalid)&&this.element(b)},onclick:function(a){a.name in this.submitted?this.element(a):a.parentNode.name in this.submitted&&this.element(a.parentNode)},highlight:function(b,c,d){"radio"===b.type?this.findByName(b.name).addClass(c).removeClass(d):a(b).addClass(c).removeClass(d)},unhighlight:function(b,c,d){"radio"===b.type?this.findByName(b.name).removeClass(c).addClass(d):a(b).removeClass(c).addClass(d)}},setDefaults:function(b){a.extend(a.validator.defaults,b)},messages:{required:"This field is required.",remote:"Please fix this field.",email:"Please enter a valid email address.",url:"Please enter a valid URL.",date:"Please enter a valid date.",dateISO:"Please enter a valid date (ISO).",number:"Please enter a valid number.",digits:"Please enter only digits.",equalTo:"Please enter the same value again.",maxlength:a.validator.format("Please enter no more than {0} characters."),minlength:a.validator.format("Please enter at least {0} characters."),rangelength:a.validator.format("Please enter a value between {0} and {1} characters long."),range:a.validator.format("Please enter a value between {0} and {1}."),max:a.validator.format("Please enter a value less than or equal to {0}."),min:a.validator.format("Please enter a value greater than or equal to {0}."),step:a.validator.format("Please enter a multiple of {0}.")},autoCreateRanges:!1,prototype:{init:function(){function b(b){!this.form&&this.hasAttribute("contenteditable")&&(this.form=a(this).closest("form")[0],this.name=a(this).attr("name"));var c=a.data(this.form,"validator"),d="on"+b.type.replace(/^validate/,""),e=c.settings;e[d]&&!a(this).is(e.ignore)&&e[d].call(c,this,b)}this.labelContainer=a(this.settings.errorLabelContainer),this.errorContext=this.labelContainer.length&&this.labelContainer||a(this.currentForm),this.containers=a(this.settings.errorContainer).add(this.settings.errorLabelContainer),this.submitted={},this.valueCache={},this.pendingRequest=0,this.pending={},this.invalid={},this.reset();var c,d=this.groups={};a.each(this.settings.groups,function(b,c){"string"==typeof c&&(c=c.split(/\s/)),a.each(c,function(a,c){d[c]=b})}),c=this.settings.rules,a.each(c,function(b,d){c[b]=a.validator.normalizeRule(d)}),a(this.currentForm).on("focusin.validate focusout.validate keyup.validate",":text, [type='password'], [type='file'], select, textarea, [type='number'], [type='search'], [type='tel'], [type='url'], [type='email'], [type='datetime'], [type='date'], [type='month'], [type='week'], [type='time'], [type='datetime-local'], [type='range'], [type='color'], [type='radio'], [type='checkbox'], [contenteditable], [type='button']",b).on("click.validate","select, option, [type='radio'], [type='checkbox']",b),this.settings.invalidHandler&&a(this.currentForm).on("invalid-form.validate",this.settings.invalidHandler)},form:function(){return this.checkForm(),a.extend(this.submitted,this.errorMap),this.invalid=a.extend({},this.errorMap),this.valid()||a(this.currentForm).triggerHandler("invalid-form",[this]),this.showErrors(),this.valid()},checkForm:function(){this.prepareForm();for(var a=0,b=this.currentElements=this.elements();b[a];a++)this.check(b[a]);return this.valid()},element:function(b){var c,d,e=this.clean(b),f=this.validationTargetFor(e),g=this,h=!0;return void 0===f?delete this.invalid[e.name]:(this.prepareElement(f),this.currentElements=a(f),d=this.groups[f.name],d&&a.each(this.groups,function(a,b){b===d&&a!==f.name&&(e=g.validationTargetFor(g.clean(g.findByName(a))),e&&e.name in g.invalid&&(g.currentElements.push(e),h=g.check(e)&&h))}),c=this.check(f)!==!1,h=h&&c,c?this.invalid[f.name]=!1:this.invalid[f.name]=!0,this.numberOfInvalids()||(this.toHide=this.toHide.add(this.containers)),this.showErrors(),a(b).attr("aria-invalid",!c)),h},showErrors:function(b){if(b){var c=this;a.extend(this.errorMap,b),this.errorList=a.map(this.errorMap,function(a,b){return{message:a,element:c.findByName(b)[0]}}),this.successList=a.grep(this.successList,function(a){return!(a.name in b)})}this.settings.showErrors?this.settings.showErrors.call(this,this.errorMap,this.errorList):this.defaultShowErrors()},resetForm:function(){a.fn.resetForm&&a(this.currentForm).resetForm(),this.invalid={},this.submitted={},this.prepareForm(),this.hideErrors();var b=this.elements().removeData("previousValue").removeAttr("aria-invalid");this.resetElements(b)},resetElements:function(a){var b;if(this.settings.unhighlight)for(b=0;a[b];b++)this.settings.unhighlight.call(this,a[b],this.settings.errorClass,""),this.findByName(a[b].name).removeClass(this.settings.validClass);else a.removeClass(this.settings.errorClass).removeClass(this.settings.validClass)},numberOfInvalids:function(){return this.objectLength(this.invalid)},objectLength:function(a){var b,c=0;for(b in a)void 0!==a[b]&&null!==a[b]&&a[b]!==!1&&c++;return c},hideErrors:function(){this.hideThese(this.toHide)},hideThese:function(a){a.not(this.containers).text(""),this.addWrapper(a).hide()},valid:function(){return 0===this.size()},size:function(){return this.errorList.length},focusInvalid:function(){if(this.settings.focusInvalid)try{a(this.findLastActive()||this.errorList.length&&this.errorList[0].element||[]).filter(":visible").focus().trigger("focusin")}catch(b){}},findLastActive:function(){var b=this.lastActive;return b&&1===a.grep(this.errorList,function(a){return a.element.name===b.name}).length&&b},elements:function(){var b=this,c={};return a(this.currentForm).find("input, select, textarea, [contenteditable]").not(":submit, :reset, :image, :disabled").not(this.settings.ignore).filter(function(){var d=this.name||a(this).attr("name");return!d&&b.settings.debug&&window.console&&console.error("%o has no name assigned",this),this.hasAttribute("contenteditable")&&(this.form=a(this).closest("form")[0],this.name=d),!(d in c||!b.objectLength(a(this).rules()))&&(c[d]=!0,!0)})},clean:function(b){return a(b)[0]},errors:function(){var b=this.settings.errorClass.split(" ").join(".");return a(this.settings.errorElement+"."+b,this.errorContext)},resetInternals:function(){this.successList=[],this.errorList=[],this.errorMap={},this.toShow=a([]),this.toHide=a([])},reset:function(){this.resetInternals(),this.currentElements=a([])},prepareForm:function(){this.reset(),this.toHide=this.errors().add(this.containers)},prepareElement:function(a){this.reset(),this.toHide=this.errorsFor(a)},elementValue:function(b){var c,d,e=a(b),f=b.type;return"radio"===f||"checkbox"===f?this.findByName(b.name).filter(":checked").val():"number"===f&&"undefined"!=typeof b.validity?b.validity.badInput?"NaN":e.val():(c=b.hasAttribute("contenteditable")?e.text():e.val(),"file"===f?"C:\\fakepath\\"===c.substr(0,12)?c.substr(12):(d=c.lastIndexOf("/"),d>=0?c.substr(d+1):(d=c.lastIndexOf("\\"),d>=0?c.substr(d+1):c)):"string"==typeof c?c.replace(/\r/g,""):c)},check:function(b){b=this.validationTargetFor(this.clean(b));var c,d,e,f,g=a(b).rules(),h=a.map(g,function(a,b){return b}).length,i=!1,j=this.elementValue(b);if("function"==typeof g.normalizer?f=g.normalizer:"function"==typeof this.settings.normalizer&&(f=this.settings.normalizer),f){if(j=f.call(b,j),"string"!=typeof j)throw new TypeError("The normalizer should return a string value.");delete g.normalizer}for(d in g){e={method:d,parameters:g[d]};try{if(c=a.validator.methods[d].call(this,j,b,e.parameters),"dependency-mismatch"===c&&1===h){i=!0;continue}if(i=!1,"pending"===c)return void(this.toHide=this.toHide.not(this.errorsFor(b)));if(!c)return this.formatAndAdd(b,e),!1}catch(k){throw this.settings.debug&&window.console&&console.log("Exception occurred when checking element "+b.id+", check the '"+e.method+"' method.",k),k instanceof TypeError&&(k.message+=". Exception occurred when checking element "+b.id+", check the '"+e.method+"' method."),k}}if(!i)return this.objectLength(g)&&this.successList.push(b),!0},customDataMessage:function(b,c){return a(b).data("msg"+c.charAt(0).toUpperCase()+c.substring(1).toLowerCase())||a(b).data("msg")},customMessage:function(a,b){var c=this.settings.messages[a];return c&&(c.constructor===String?c:c[b])},findDefined:function(){for(var a=0;aWarning: No message defined for "+b.name+""),e=/\$?\{(\d+)\}/g;return"function"==typeof d?d=d.call(this,c.parameters,b):e.test(d)&&(d=a.validator.format(d.replace(e,"{$1}"),c.parameters)),d},formatAndAdd:function(a,b){var c=this.defaultMessage(a,b);this.errorList.push({message:c,element:a,method:b.method}),this.errorMap[a.name]=c,this.submitted[a.name]=c},addWrapper:function(a){return this.settings.wrapper&&(a=a.add(a.parent(this.settings.wrapper))),a},defaultShowErrors:function(){var a,b,c;for(a=0;this.errorList[a];a++)c=this.errorList[a],this.settings.highlight&&this.settings.highlight.call(this,c.element,this.settings.errorClass,this.settings.validClass),this.showLabel(c.element,c.message);if(this.errorList.length&&(this.toShow=this.toShow.add(this.containers)),this.settings.success)for(a=0;this.successList[a];a++)this.showLabel(this.successList[a]);if(this.settings.unhighlight)for(a=0,b=this.validElements();b[a];a++)this.settings.unhighlight.call(this,b[a],this.settings.errorClass,this.settings.validClass);this.toHide=this.toHide.not(this.toShow),this.hideErrors(),this.addWrapper(this.toShow).show()},validElements:function(){return this.currentElements.not(this.invalidElements())},invalidElements:function(){return a(this.errorList).map(function(){return this.element})},showLabel:function(b,c){var d,e,f,g,h=this.errorsFor(b),i=this.idOrName(b),j=a(b).attr("aria-describedby");h.length?(h.removeClass(this.settings.validClass).addClass(this.settings.errorClass),h.html(c)):(h=a("<"+this.settings.errorElement+">").attr("id",i+"-error").addClass(this.settings.errorClass).html(c||""),d=h,this.settings.wrapper&&(d=h.hide().show().wrap("<"+this.settings.wrapper+"/>").parent()),this.labelContainer.length?this.labelContainer.append(d):this.settings.errorPlacement?this.settings.errorPlacement.call(this,d,a(b)):d.insertAfter(b),h.is("label")?h.attr("for",i):0===h.parents("label[for='"+this.escapeCssMeta(i)+"']").length&&(f=h.attr("id"),j?j.match(new RegExp("\\b"+this.escapeCssMeta(f)+"\\b"))||(j+=" "+f):j=f,a(b).attr("aria-describedby",j),e=this.groups[b.name],e&&(g=this,a.each(g.groups,function(b,c){c===e&&a("[name='"+g.escapeCssMeta(b)+"']",g.currentForm).attr("aria-describedby",h.attr("id"))})))),!c&&this.settings.success&&(h.text(""),"string"==typeof this.settings.success?h.addClass(this.settings.success):this.settings.success(h,b)),this.toShow=this.toShow.add(h)},errorsFor:function(b){var c=this.escapeCssMeta(this.idOrName(b)),d=a(b).attr("aria-describedby"),e="label[for='"+c+"'], label[for='"+c+"'] *";return d&&(e=e+", #"+this.escapeCssMeta(d).replace(/\s+/g,", #")),this.errors().filter(e)},escapeCssMeta:function(a){return a.replace(/([\\!"#$%&'()*+,.\/:;<=>?@\[\]^`{|}~])/g,"\\$1")},idOrName:function(a){return this.groups[a.name]||(this.checkable(a)?a.name:a.id||a.name)},validationTargetFor:function(b){return this.checkable(b)&&(b=this.findByName(b.name)),a(b).not(this.settings.ignore)[0]},checkable:function(a){return/radio|checkbox/i.test(a.type)},findByName:function(b){return a(this.currentForm).find("[name='"+this.escapeCssMeta(b)+"']")},getLength:function(b,c){switch(c.nodeName.toLowerCase()){case"select":return a("option:selected",c).length;case"input":if(this.checkable(c))return this.findByName(c.name).filter(":checked").length}return b.length},depend:function(a,b){return!this.dependTypes[typeof a]||this.dependTypes[typeof a](a,b)},dependTypes:{"boolean":function(a){return a},string:function(b,c){return!!a(b,c.form).length},"function":function(a,b){return a(b)}},optional:function(b){var c=this.elementValue(b);return!a.validator.methods.required.call(this,c,b)&&"dependency-mismatch"},startRequest:function(b){this.pending[b.name]||(this.pendingRequest++,a(b).addClass(this.settings.pendingClass),this.pending[b.name]=!0)},stopRequest:function(b,c){this.pendingRequest--,this.pendingRequest<0&&(this.pendingRequest=0),delete this.pending[b.name],a(b).removeClass(this.settings.pendingClass),c&&0===this.pendingRequest&&this.formSubmitted&&this.form()?(a(this.currentForm).submit(),this.submitButton&&a("input:hidden[name='"+this.submitButton.name+"']",this.currentForm).remove(),this.formSubmitted=!1):!c&&0===this.pendingRequest&&this.formSubmitted&&(a(this.currentForm).triggerHandler("invalid-form",[this]),this.formSubmitted=!1)},previousValue:function(b,c){return c="string"==typeof c&&c||"remote",a.data(b,"previousValue")||a.data(b,"previousValue",{old:null,valid:!0,message:this.defaultMessage(b,{method:c})})},destroy:function(){this.resetForm(),a(this.currentForm).off(".validate").removeData("validator").find(".validate-equalTo-blur").off(".validate-equalTo").removeClass("validate-equalTo-blur")}},classRuleSettings:{required:{required:!0},email:{email:!0},url:{url:!0},date:{date:!0},dateISO:{dateISO:!0},number:{number:!0},digits:{digits:!0},creditcard:{creditcard:!0}},addClassRules:function(b,c){b.constructor===String?this.classRuleSettings[b]=c:a.extend(this.classRuleSettings,b)},classRules:function(b){var c={},d=a(b).attr("class");return d&&a.each(d.split(" "),function(){this in a.validator.classRuleSettings&&a.extend(c,a.validator.classRuleSettings[this])}),c},normalizeAttributeRule:function(a,b,c,d){/min|max|step/.test(c)&&(null===b||/number|range|text/.test(b))&&(d=Number(d),isNaN(d)&&(d=void 0)),d||0===d?a[c]=d:b===c&&"range"!==b&&(a[c]=!0)},attributeRules:function(b){var c,d,e={},f=a(b),g=b.getAttribute("type");for(c in a.validator.methods)"required"===c?(d=b.getAttribute(c),""===d&&(d=!0),d=!!d):d=f.attr(c),this.normalizeAttributeRule(e,g,c,d);return e.maxlength&&/-1|2147483647|524288/.test(e.maxlength)&&delete e.maxlength,e},dataRules:function(b){var c,d,e={},f=a(b),g=b.getAttribute("type");for(c in a.validator.methods)d=f.data("rule"+c.charAt(0).toUpperCase()+c.substring(1).toLowerCase()),this.normalizeAttributeRule(e,g,c,d);return e},staticRules:function(b){var c={},d=a.data(b.form,"validator");return d.settings.rules&&(c=a.validator.normalizeRule(d.settings.rules[b.name])||{}),c},normalizeRules:function(b,c){return a.each(b,function(d,e){if(e===!1)return void delete b[d];if(e.param||e.depends){var f=!0;switch(typeof e.depends){case"string":f=!!a(e.depends,c.form).length;break;case"function":f=e.depends.call(c,c)}f?b[d]=void 0===e.param||e.param:(a.data(c.form,"validator").resetElements(a(c)),delete b[d])}}),a.each(b,function(d,e){b[d]=a.isFunction(e)&&"normalizer"!==d?e(c):e}),a.each(["minlength","maxlength"],function(){b[this]&&(b[this]=Number(b[this]))}),a.each(["rangelength","range"],function(){var c;b[this]&&(a.isArray(b[this])?b[this]=[Number(b[this][0]),Number(b[this][1])]:"string"==typeof b[this]&&(c=b[this].replace(/[\[\]]/g,"").split(/[\s,]+/),b[this]=[Number(c[0]),Number(c[1])]))}),a.validator.autoCreateRanges&&(null!=b.min&&null!=b.max&&(b.range=[b.min,b.max],delete b.min,delete b.max),null!=b.minlength&&null!=b.maxlength&&(b.rangelength=[b.minlength,b.maxlength],delete b.minlength,delete b.maxlength)),b},normalizeRule:function(b){if("string"==typeof b){var c={};a.each(b.split(/\s/),function(){c[this]=!0}),b=c}return b},addMethod:function(b,c,d){a.validator.methods[b]=c,a.validator.messages[b]=void 0!==d?d:a.validator.messages[b],c.length<3&&a.validator.addClassRules(b,a.validator.normalizeRule(b))},methods:{required:function(b,c,d){if(!this.depend(d,c))return"dependency-mismatch";if("select"===c.nodeName.toLowerCase()){var e=a(c).val();return e&&e.length>0}return this.checkable(c)?this.getLength(b,c)>0:b.length>0},email:function(a,b){return this.optional(b)||/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(a)},url:function(a,b){return this.optional(b)||/^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[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.test(a)},date:function(a,b){return this.optional(b)||!/Invalid|NaN/.test(new Date(a).toString())},dateISO:function(a,b){return this.optional(b)||/^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/.test(a)},number:function(a,b){return this.optional(b)||/^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(a)},digits:function(a,b){return this.optional(b)||/^\d+$/.test(a)},minlength:function(b,c,d){var e=a.isArray(b)?b.length:this.getLength(b,c);return this.optional(c)||e>=d},maxlength:function(b,c,d){var e=a.isArray(b)?b.length:this.getLength(b,c);return this.optional(c)||e<=d},rangelength:function(b,c,d){var e=a.isArray(b)?b.length:this.getLength(b,c);return this.optional(c)||e>=d[0]&&e<=d[1]},min:function(a,b,c){return this.optional(b)||a>=c},max:function(a,b,c){return this.optional(b)||a<=c},range:function(a,b,c){return this.optional(b)||a>=c[0]&&a<=c[1]},step:function(b,c,d){var e,f=a(c).attr("type"),g="Step attribute on input type "+f+" is not supported.",h=["text","number","range"],i=new RegExp("\\b"+f+"\\b"),j=f&&!i.test(h.join()),k=function(a){var b=(""+a).match(/(?:\.(\d+))?$/);return b&&b[1]?b[1].length:0},l=function(a){return Math.round(a*Math.pow(10,e))},m=!0;if(j)throw new Error(g);return e=k(d),(k(b)>e||l(b)%l(d)!==0)&&(m=!1),this.optional(c)||m},equalTo:function(b,c,d){var e=a(d);return this.settings.onfocusout&&e.not(".validate-equalTo-blur").length&&e.addClass("validate-equalTo-blur").on("blur.validate-equalTo",function(){a(c).valid()}),b===e.val()},remote:function(b,c,d,e){if(this.optional(c))return"dependency-mismatch";e="string"==typeof e&&e||"remote";var f,g,h,i=this.previousValue(c,e);return this.settings.messages[c.name]||(this.settings.messages[c.name]={}),i.originalMessage=i.originalMessage||this.settings.messages[c.name][e],this.settings.messages[c.name][e]=i.message,d="string"==typeof d&&{url:d}||d,h=a.param(a.extend({data:b},d.data)),i.old===h?i.valid:(i.old=h,f=this,this.startRequest(c),g={},g[c.name]=b,a.ajax(a.extend(!0,{mode:"abort",port:"validate"+c.name,dataType:"json",data:g,context:f.currentForm,success:function(a){var d,g,h,j=a===!0||"true"===a;f.settings.messages[c.name][e]=i.originalMessage,j?(h=f.formSubmitted,f.resetInternals(),f.toHide=f.errorsFor(c),f.formSubmitted=h,f.successList.push(c),f.invalid[c.name]=!1,f.showErrors()):(d={},g=a||f.defaultMessage(c,{method:e,parameters:b}),d[c.name]=i.message=g,f.invalid[c.name]=!0,f.showErrors(d)),i.valid=j,f.stopRequest(c,j)}},d)),"pending")}}});var b,c={};return a.ajaxPrefilter?a.ajaxPrefilter(function(a,b,d){var e=a.port;"abort"===a.mode&&(c[e]&&c[e].abort(),c[e]=d)}):(b=a.ajax,a.ajax=function(d){var e=("mode"in d?d:a.ajaxSettings).mode,f=("port"in d?d:a.ajaxSettings).port;return"abort"===e?(c[f]&&c[f].abort(),c[f]=b.apply(this,arguments),c[f]):b.apply(this,arguments)}),a}); /*! * jQuery Validation Plugin v1.17.0 * * https://jqueryvalidation.org/ * * Copyright (c) 2017 Jæžšrn Zaefferer * Released under the MIT license */ (function( factory ) { if ( typeof define === "function" && define.amd ) { define( ["jquery", "./jquery.validate"], factory ); } else if (typeof module === "object" && module.exports) { module.exports = factory( require( "jquery" ) ); } else { factory( jQuery ); } }(function( $ ) { ( function() { function stripHtml( value ) { // Remove html tags and space chars return value.replace( /<.[^<>]*?>/g, " " ).replace( / | /gi, " " ) // Remove punctuation .replace( /[.(),;:!?%#$'\"_+=\/\-鈥溾€濃€橾*/g, "" ); } $.validator.addMethod( "maxWords", function( value, element, params ) { return this.optional( element ) || stripHtml( value ).match( /\b\w+\b/g ).length <= params; }, $.validator.format( "Please enter {0} words or less." ) ); $.validator.addMethod( "minWords", function( value, element, params ) { return this.optional( element ) || stripHtml( value ).match( /\b\w+\b/g ).length >= params; }, $.validator.format( "Please enter at least {0} words." ) ); $.validator.addMethod( "rangeWords", function( value, element, params ) { var valueStripped = stripHtml( value ), regex = /\b\w+\b/g; return this.optional( element ) || valueStripped.match( regex ).length >= params[ 0 ] && valueStripped.match( regex ).length <= params[ 1 ]; }, $.validator.format( "Please enter between {0} and {1} words." ) ); }() ); // Accept a value from a file input based on a required mimetype $.validator.addMethod( "accept", function( value, element, param ) { // Split mime on commas in case we have multiple types we can accept var typeParam = typeof param === "string" ? param.replace( /\s/g, "" ) : "image/*", optionalValue = this.optional( element ), i, file, regex; // Element is optional if ( optionalValue ) { return optionalValue; } if ( $( element ).attr( "type" ) === "file" ) { // Escape string to be used in the regex // see: https://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex // Escape also "/*" as "/.*" as a wildcard typeParam = typeParam .replace( /[\-\[\]\/\{\}\(\)\+\?\.\\\^\$\|]/g, "\\$&" ) .replace( /,/g, "|" ) .replace( /\/\*/g, "/.*" ); // Check if the element has a FileList before checking each file if ( element.files && element.files.length ) { regex = new RegExp( ".?(" + typeParam + ")$", "i" ); for ( i = 0; i < element.files.length; i++ ) { file = element.files[ i ]; // Grab the mimetype from the loaded file, verify it matches if ( !file.type.match( regex ) ) { return false; } } } } // Either return true because we've validated each file, or because the // browser does not support element.files and the FileList feature return true; }, $.validator.format( "Please enter a value with a valid mimetype." ) ); $.validator.addMethod( "alphanumeric", function( value, element ) { return this.optional( element ) || /^\w+$/i.test( value ); }, "Letters, numbers, and underscores only please" ); /* * Dutch bank account numbers (not 'giro' numbers) have 9 digits * and pass the '11 check'. * We accept the notation with spaces, as that is common. * acceptable: 123456789 or 12 34 56 789 */ $.validator.addMethod( "bankaccountNL", function( value, element ) { if ( this.optional( element ) ) { return true; } if ( !( /^[0-9]{9}|([0-9]{2} ){3}[0-9]{3}$/.test( value ) ) ) { return false; } // Now '11 check' var account = value.replace( / /g, "" ), // Remove spaces sum = 0, len = account.length, pos, factor, digit; for ( pos = 0; pos < len; pos++ ) { factor = len - pos; digit = account.substring( pos, pos + 1 ); sum = sum + factor * digit; } return sum % 11 === 0; }, "Please specify a valid bank account number" ); $.validator.addMethod( "bankorgiroaccountNL", function( value, element ) { return this.optional( element ) || ( $.validator.methods.bankaccountNL.call( this, value, element ) ) || ( $.validator.methods.giroaccountNL.call( this, value, element ) ); }, "Please specify a valid bank or giro account number" ); /** * BIC is the business identifier code (ISO 9362). This BIC check is not a guarantee for authenticity. * * BIC pattern: BBBBCCLLbbb (8 or 11 characters long; bbb is optional) * * Validation is case-insensitive. Please make sure to normalize input yourself. * * BIC definition in detail: * - First 4 characters - bank code (only letters) * - Next 2 characters - ISO 3166-1 alpha-2 country code (only letters) * - Next 2 characters - location code (letters and digits) * a. shall not start with '0' or '1' * b. second character must be a letter ('O' is not allowed) or digit ('0' for test (therefore not allowed), '1' denoting passive participant, '2' typically reverse-billing) * - Last 3 characters - branch code, optional (shall not start with 'X' except in case of 'XXX' for primary office) (letters and digits) */ $.validator.addMethod( "bic", function( value, element ) { return this.optional( element ) || /^([A-Z]{6}[A-Z2-9][A-NP-Z1-9])(X{3}|[A-WY-Z0-9][A-Z0-9]{2})?$/.test( value.toUpperCase() ); }, "Please specify a valid BIC code" ); /* * Cè´¸digo de identificaciè´¸n fiscal ( CIF ) is the tax identification code for Spanish legal entities * Further rules can be found in Spanish on http://es.wikipedia.org/wiki/C%C3%B3digo_de_identificaci%C3%B3n_fiscal * * Spanish CIF structure: * * [ T ][ P ][ P ][ N ][ N ][ N ][ N ][ N ][ C ] * * Where: * * T: 1 character. Kind of Organization Letter: [ABCDEFGHJKLMNPQRSUVW] * P: 2 characters. Province. * N: 5 characters. Secuencial Number within the province. * C: 1 character. Control Digit: [0-9A-J]. * * [ T ]: Kind of Organizations. Possible values: * * A. Corporations * B. LLCs * C. General partnerships * D. Companies limited partnerships * E. Communities of goods * F. Cooperative Societies * G. Associations * H. Communities of homeowners in horizontal property regime * J. Civil Societies * K. Old format * L. Old format * M. Old format * N. Nonresident entities * P. Local authorities * Q. Autonomous bodies, state or not, and the like, and congregations and religious institutions * R. Congregations and religious institutions (since 2008 ORDER EHA/451/2008) * S. Organs of State Administration and regions * V. Agrarian Transformation * W. Permanent establishments of non-resident in Spain * * [ C ]: Control Digit. It can be a number or a letter depending on T value: * [ T ] --> [ C ] * ------ ---------- * A Number * B Number * E Number * H Number * K Letter * P Letter * Q Letter * S Letter * */ $.validator.addMethod( "cifES", function( value, element ) { "use strict"; if ( this.optional( element ) ) { return true; } var cifRegEx = new RegExp( /^([ABCDEFGHJKLMNPQRSUVW])(\d{7})([0-9A-J])$/gi ); var letter = value.substring( 0, 1 ), // [ T ] number = value.substring( 1, 8 ), // [ P ][ P ][ N ][ N ][ N ][ N ][ N ] control = value.substring( 8, 9 ), // [ C ] all_sum = 0, even_sum = 0, odd_sum = 0, i, n, control_digit, control_letter; function isOdd( n ) { return n % 2 === 0; } // Quick format test if ( value.length !== 9 || !cifRegEx.test( value ) ) { return false; } for ( i = 0; i < number.length; i++ ) { n = parseInt( number[ i ], 10 ); // Odd positions if ( isOdd( i ) ) { // Odd positions are multiplied first. n *= 2; // If the multiplication is bigger than 10 we need to adjust odd_sum += n < 10 ? n : n - 9; // Even positions // Just sum them } else { even_sum += n; } } all_sum = even_sum + odd_sum; control_digit = ( 10 - ( all_sum ).toString().substr( -1 ) ).toString(); control_digit = parseInt( control_digit, 10 ) > 9 ? "0" : control_digit; control_letter = "JABCDEFGHI".substr( control_digit, 1 ).toString(); // Control must be a digit if ( letter.match( /[ABEH]/ ) ) { return control === control_digit; // Control must be a letter } else if ( letter.match( /[KPQS]/ ) ) { return control === control_letter; } // Can be either return control === control_digit || control === control_letter; }, "Please specify a valid CIF number." ); /* * Brazillian CPF number (Cadastrado de Pessoas F铆sicas) is the equivalent of a Brazilian tax registration number. * CPF numbers have 11 digits in total: 9 numbers followed by 2 check numbers that are being used for validation. */ $.validator.addMethod( "cpfBR", function( value ) { // Removing special characters from value value = value.replace( /([~!@#$%^&*()_+=`{}\[\]\-|\\:;'<>,.\/? ])+/g, "" ); // Checking value to have 11 digits only if ( value.length !== 11 ) { return false; } var sum = 0, firstCN, secondCN, checkResult, i; firstCN = parseInt( value.substring( 9, 10 ), 10 ); secondCN = parseInt( value.substring( 10, 11 ), 10 ); checkResult = function( sum, cn ) { var result = ( sum * 10 ) % 11; if ( ( result === 10 ) || ( result === 11 ) ) { result = 0; } return ( result === cn ); }; // Checking for dump data if ( value === "" || value === "00000000000" || value === "11111111111" || value === "22222222222" || value === "33333333333" || value === "44444444444" || value === "55555555555" || value === "66666666666" || value === "77777777777" || value === "88888888888" || value === "99999999999" ) { return false; } // Step 1 - using first Check Number: for ( i = 1; i <= 9; i++ ) { sum = sum + parseInt( value.substring( i - 1, i ), 10 ) * ( 11 - i ); } // If first Check Number (CN) is valid, move to Step 2 - using second Check Number: if ( checkResult( sum, firstCN ) ) { sum = 0; for ( i = 1; i <= 10; i++ ) { sum = sum + parseInt( value.substring( i - 1, i ), 10 ) * ( 12 - i ); } return checkResult( sum, secondCN ); } return false; }, "Please specify a valid CPF number" ); // https://jqueryvalidation.org/creditcard-method/ // based on https://en.wikipedia.org/wiki/Luhn_algorithm $.validator.addMethod( "creditcard", function( value, element ) { if ( this.optional( element ) ) { return "dependency-mismatch"; } // Accept only spaces, digits and dashes if ( /[^0-9 \-]+/.test( value ) ) { return false; } var nCheck = 0, nDigit = 0, bEven = false, n, cDigit; value = value.replace( /\D/g, "" ); // Basing min and max length on // https://developer.ean.com/general_info/Valid_Credit_Card_Types if ( value.length < 13 || value.length > 19 ) { return false; } for ( n = value.length - 1; n >= 0; n-- ) { cDigit = value.charAt( n ); nDigit = parseInt( cDigit, 10 ); if ( bEven ) { if ( ( nDigit *= 2 ) > 9 ) { nDigit -= 9; } } nCheck += nDigit; bEven = !bEven; } return ( nCheck % 10 ) === 0; }, "Please enter a valid credit card number." ); /* NOTICE: Modified version of Castle.Components.Validator.CreditCardValidator * Redistributed under the the Apache License 2.0 at http://www.apache.org/licenses/LICENSE-2.0 * Valid Types: mastercard, visa, amex, dinersclub, enroute, discover, jcb, unknown, all (overrides all other settings) */ $.validator.addMethod( "creditcardtypes", function( value, element, param ) { if ( /[^0-9\-]+/.test( value ) ) { return false; } value = value.replace( /\D/g, "" ); var validTypes = 0x0000; if ( param.mastercard ) { validTypes |= 0x0001; } if ( param.visa ) { validTypes |= 0x0002; } if ( param.amex ) { validTypes |= 0x0004; } if ( param.dinersclub ) { validTypes |= 0x0008; } if ( param.enroute ) { validTypes |= 0x0010; } if ( param.discover ) { validTypes |= 0x0020; } if ( param.jcb ) { validTypes |= 0x0040; } if ( param.unknown ) { validTypes |= 0x0080; } if ( param.all ) { validTypes = 0x0001 | 0x0002 | 0x0004 | 0x0008 | 0x0010 | 0x0020 | 0x0040 | 0x0080; } if ( validTypes & 0x0001 && /^(5[12345])/.test( value ) ) { // Mastercard return value.length === 16; } if ( validTypes & 0x0002 && /^(4)/.test( value ) ) { // Visa return value.length === 16; } if ( validTypes & 0x0004 && /^(3[47])/.test( value ) ) { // Amex return value.length === 15; } if ( validTypes & 0x0008 && /^(3(0[012345]|[68]))/.test( value ) ) { // Dinersclub return value.length === 14; } if ( validTypes & 0x0010 && /^(2(014|149))/.test( value ) ) { // Enroute return value.length === 15; } if ( validTypes & 0x0020 && /^(6011)/.test( value ) ) { // Discover return value.length === 16; } if ( validTypes & 0x0040 && /^(3)/.test( value ) ) { // Jcb return value.length === 16; } if ( validTypes & 0x0040 && /^(2131|1800)/.test( value ) ) { // Jcb return value.length === 15; } if ( validTypes & 0x0080 ) { // Unknown return true; } return false; }, "Please enter a valid credit card number." ); /** * Validates currencies with any given symbols by @jameslouiz * Symbols can be optional or required. Symbols required by default * * Usage examples: * currency: ["æ‹¢", false] - Use false for soft currency validation * currency: ["$", false] * currency: ["RM", false] - also works with text based symbols such as "RM" - Malaysia Ringgit etc * * * * Soft symbol checking * currencyInput: { * currency: ["$", false] * } * * Strict symbol checking (default) * currencyInput: { * currency: "$" * //OR * currency: ["$", true] * } * * Multiple Symbols * currencyInput: { * currency: "$,æ‹¢,åž„" * } */ $.validator.addMethod( "currency", function( value, element, param ) { var isParamString = typeof param === "string", symbol = isParamString ? param : param[ 0 ], soft = isParamString ? true : param[ 1 ], regex; symbol = symbol.replace( /,/g, "" ); symbol = soft ? symbol + "]" : symbol + "]?"; regex = "^[" + symbol + "([1-9]{1}[0-9]{0,2}(\\,[0-9]{3})*(\\.[0-9]{0,2})?|[1-9]{1}[0-9]{0,}(\\.[0-9]{0,2})?|0(\\.[0-9]{0,2})?|(\\.[0-9]{1,2})?)$"; regex = new RegExp( regex ); return this.optional( element ) || regex.test( value ); }, "Please specify a valid currency" ); $.validator.addMethod( "dateFA", function( value, element ) { return this.optional( element ) || /^[1-4]\d{3}\/((0?[1-6]\/((3[0-1])|([1-2][0-9])|(0?[1-9])))|((1[0-2]|(0?[7-9]))\/(30|([1-2][0-9])|(0?[1-9]))))$/.test( value ); }, $.validator.messages.date ); /** * Return true, if the value is a valid date, also making this formal check dd/mm/yyyy. * * @example $.validator.methods.date("01/01/1900") * @result true * * @example $.validator.methods.date("01/13/1990") * @result false * * @example $.validator.methods.date("01.01.1900") * @result false * * @example * @desc Declares an optional input element whose value must be a valid date. * * @name $.validator.methods.dateITA * @type Boolean * @cat Plugins/Validate/Methods */ $.validator.addMethod( "dateITA", function( value, element ) { var check = false, re = /^\d{1,2}\/\d{1,2}\/\d{4}$/, adata, gg, mm, aaaa, xdata; if ( re.test( value ) ) { adata = value.split( "/" ); gg = parseInt( adata[ 0 ], 10 ); mm = parseInt( adata[ 1 ], 10 ); aaaa = parseInt( adata[ 2 ], 10 ); xdata = new Date( Date.UTC( aaaa, mm - 1, gg, 12, 0, 0, 0 ) ); if ( ( xdata.getUTCFullYear() === aaaa ) && ( xdata.getUTCMonth() === mm - 1 ) && ( xdata.getUTCDate() === gg ) ) { check = true; } else { check = false; } } else { check = false; } return this.optional( element ) || check; }, $.validator.messages.date ); $.validator.addMethod( "dateNL", function( value, element ) { return this.optional( element ) || /^(0?[1-9]|[12]\d|3[01])[\.\/\-](0?[1-9]|1[012])[\.\/\-]([12]\d)?(\d\d)$/.test( value ); }, $.validator.messages.date ); // Older "accept" file extension method. Old docs: http://docs.jquery.com/Plugins/Validation/Methods/accept $.validator.addMethod( "extension", function( value, element, param ) { param = typeof param === "string" ? param.replace( /,/g, "|" ) : "png|jpe?g|gif"; return this.optional( element ) || value.match( new RegExp( "\\.(" + param + ")$", "i" ) ); }, $.validator.format( "Please enter a value with a valid extension." ) ); /** * Dutch giro account numbers (not bank numbers) have max 7 digits */ $.validator.addMethod( "giroaccountNL", function( value, element ) { return this.optional( element ) || /^[0-9]{1,7}$/.test( value ); }, "Please specify a valid giro account number" ); /** * IBAN is the international bank account number. * It has a country - specific format, that is checked here too * * Validation is case-insensitive. Please make sure to normalize input yourself. */ $.validator.addMethod( "iban", function( value, element ) { // Some quick simple tests to prevent needless work if ( this.optional( element ) ) { return true; } // Remove spaces and to upper case var iban = value.replace( / /g, "" ).toUpperCase(), ibancheckdigits = "", leadingZeroes = true, cRest = "", cOperator = "", countrycode, ibancheck, charAt, cChar, bbanpattern, bbancountrypatterns, ibanregexp, i, p; // Check for IBAN code length. // It contains: // country code ISO 3166-1 - two letters, // two check digits, // Basic Bank Account Number (BBAN) - up to 30 chars var minimalIBANlength = 5; if ( iban.length < minimalIBANlength ) { return false; } // Check the country code and find the country specific format countrycode = iban.substring( 0, 2 ); bbancountrypatterns = { "AL": "\\d{8}[\\dA-Z]{16}", "AD": "\\d{8}[\\dA-Z]{12}", "AT": "\\d{16}", "AZ": "[\\dA-Z]{4}\\d{20}", "BE": "\\d{12}", "BH": "[A-Z]{4}[\\dA-Z]{14}", "BA": "\\d{16}", "BR": "\\d{23}[A-Z][\\dA-Z]", "BG": "[A-Z]{4}\\d{6}[\\dA-Z]{8}", "CR": "\\d{17}", "HR": "\\d{17}", "CY": "\\d{8}[\\dA-Z]{16}", "CZ": "\\d{20}", "DK": "\\d{14}", "DO": "[A-Z]{4}\\d{20}", "EE": "\\d{16}", "FO": "\\d{14}", "FI": "\\d{14}", "FR": "\\d{10}[\\dA-Z]{11}\\d{2}", "GE": "[\\dA-Z]{2}\\d{16}", "DE": "\\d{18}", "GI": "[A-Z]{4}[\\dA-Z]{15}", "GR": "\\d{7}[\\dA-Z]{16}", "GL": "\\d{14}", "GT": "[\\dA-Z]{4}[\\dA-Z]{20}", "HU": "\\d{24}", "IS": "\\d{22}", "IE": "[\\dA-Z]{4}\\d{14}", "IL": "\\d{19}", "IT": "[A-Z]\\d{10}[\\dA-Z]{12}", "KZ": "\\d{3}[\\dA-Z]{13}", "KW": "[A-Z]{4}[\\dA-Z]{22}", "LV": "[A-Z]{4}[\\dA-Z]{13}", "LB": "\\d{4}[\\dA-Z]{20}", "LI": "\\d{5}[\\dA-Z]{12}", "LT": "\\d{16}", "LU": "\\d{3}[\\dA-Z]{13}", "MK": "\\d{3}[\\dA-Z]{10}\\d{2}", "MT": "[A-Z]{4}\\d{5}[\\dA-Z]{18}", "MR": "\\d{23}", "MU": "[A-Z]{4}\\d{19}[A-Z]{3}", "MC": "\\d{10}[\\dA-Z]{11}\\d{2}", "MD": "[\\dA-Z]{2}\\d{18}", "ME": "\\d{18}", "NL": "[A-Z]{4}\\d{10}", "NO": "\\d{11}", "PK": "[\\dA-Z]{4}\\d{16}", "PS": "[\\dA-Z]{4}\\d{21}", "PL": "\\d{24}", "PT": "\\d{21}", "RO": "[A-Z]{4}[\\dA-Z]{16}", "SM": "[A-Z]\\d{10}[\\dA-Z]{12}", "SA": "\\d{2}[\\dA-Z]{18}", "RS": "\\d{18}", "SK": "\\d{20}", "SI": "\\d{15}", "ES": "\\d{20}", "SE": "\\d{20}", "CH": "\\d{5}[\\dA-Z]{12}", "TN": "\\d{20}", "TR": "\\d{5}[\\dA-Z]{17}", "AE": "\\d{3}\\d{16}", "GB": "[A-Z]{4}\\d{14}", "VG": "[\\dA-Z]{4}\\d{16}" }; bbanpattern = bbancountrypatterns[ countrycode ]; // As new countries will start using IBAN in the // future, we only check if the countrycode is known. // This prevents false negatives, while almost all // false positives introduced by this, will be caught // by the checksum validation below anyway. // Strict checking should return FALSE for unknown // countries. if ( typeof bbanpattern !== "undefined" ) { ibanregexp = new RegExp( "^[A-Z]{2}\\d{2}" + bbanpattern + "$", "" ); if ( !( ibanregexp.test( iban ) ) ) { return false; // Invalid country specific format } } // Now check the checksum, first convert to digits ibancheck = iban.substring( 4, iban.length ) + iban.substring( 0, 4 ); for ( i = 0; i < ibancheck.length; i++ ) { charAt = ibancheck.charAt( i ); if ( charAt !== "0" ) { leadingZeroes = false; } if ( !leadingZeroes ) { ibancheckdigits += "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf( charAt ); } } // Calculate the result of: ibancheckdigits % 97 for ( p = 0; p < ibancheckdigits.length; p++ ) { cChar = ibancheckdigits.charAt( p ); cOperator = "" + cRest + "" + cChar; cRest = cOperator % 97; } return cRest === 1; }, "Please specify a valid IBAN" ); $.validator.addMethod( "integer", function( value, element ) { return this.optional( element ) || /^-?\d+$/.test( value ); }, "A positive or negative non-decimal number please" ); $.validator.addMethod( "ipv4", function( value, element ) { return this.optional( element ) || /^(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)$/i.test( value ); }, "Please enter a valid IP v4 address." ); $.validator.addMethod( "ipv6", function( value, element ) { return this.optional( element ) || /^((([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|(([0-9A-Fa-f]{1,4}:){0,5}:((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|(::([0-9A-Fa-f]{1,4}:){0,5}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})|(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:))$/i.test( value ); }, "Please enter a valid IP v6 address." ); $.validator.addMethod( "lettersonly", function( value, element ) { return this.optional( element ) || /^[a-z]+$/i.test( value ); }, "Letters only please" ); $.validator.addMethod( "letterswithbasicpunc", function( value, element ) { return this.optional( element ) || /^[a-z\-.,()'"\s]+$/i.test( value ); }, "Letters or punctuation only please" ); $.validator.addMethod( "mobileNL", function( value, element ) { return this.optional( element ) || /^((\+|00(\s|\s?\-\s?)?)31(\s|\s?\-\s?)?(\(0\)[\-\s]?)?|0)6((\s|\s?\-\s?)?[0-9]){8}$/.test( value ); }, "Please specify a valid mobile number" ); /* For UK phone functions, do the following server side processing: * Compare original input with this RegEx pattern: * ^\(?(?:(?:00\)?[\s\-]?\(?|\+)(44)\)?[\s\-]?\(?(?:0\)?[\s\-]?\(?)?|0)([1-9]\d{1,4}\)?[\s\d\-]+)$ * Extract $1 and set $prefix to '+44' if $1 is '44', otherwise set $prefix to '0' * Extract $2 and remove hyphens, spaces and parentheses. Phone number is combined $prefix and $2. * A number of very detailed GB telephone number RegEx patterns can also be found at: * http://www.aa-asterisk.org.uk/index.php/Regular_Expressions_for_Validating_and_Formatting_GB_Telephone_Numbers */ $.validator.addMethod( "mobileUK", function( phone_number, element ) { phone_number = phone_number.replace( /\(|\)|\s+|-/g, "" ); return this.optional( element ) || phone_number.length > 9 && phone_number.match( /^(?:(?:(?:00\s?|\+)44\s?|0)7(?:[1345789]\d{2}|624)\s?\d{3}\s?\d{3})$/ ); }, "Please specify a valid mobile number" ); $.validator.addMethod( "netmask", function( value, element ) { return this.optional( element ) || /^(254|252|248|240|224|192|128)\.0\.0\.0|255\.(254|252|248|240|224|192|128|0)\.0\.0|255\.255\.(254|252|248|240|224|192|128|0)\.0|255\.255\.255\.(254|252|248|240|224|192|128|0)/i.test( value ); }, "Please enter a valid netmask." ); /* * The NIE (Nç…¤mero de Identificaciè´¸n de Extranjero) is a Spanish tax identification number assigned by the Spanish * authorities to any foreigner. * * The NIE is the equivalent of a Spaniards Nç…¤mero de Identificaciè´¸n Fiscal (NIF) which serves as a fiscal * identification number. The CIF number (Certificado de Identificaciè´¸n Fiscal) is equivalent to the NIF, but applies to * companies rather than individuals. The NIE consists of an 'X' or 'Y' followed by 7 or 8 digits then another letter. */ $.validator.addMethod( "nieES", function( value, element ) { "use strict"; if ( this.optional( element ) ) { return true; } var nieRegEx = new RegExp( /^[MXYZ]{1}[0-9]{7,8}[TRWAGMYFPDXBNJZSQVHLCKET]{1}$/gi ); var validChars = "TRWAGMYFPDXBNJZSQVHLCKET", letter = value.substr( value.length - 1 ).toUpperCase(), number; value = value.toString().toUpperCase(); // Quick format test if ( value.length > 10 || value.length < 9 || !nieRegEx.test( value ) ) { return false; } // X means same number // Y means number + 10000000 // Z means number + 20000000 value = value.replace( /^[X]/, "0" ) .replace( /^[Y]/, "1" ) .replace( /^[Z]/, "2" ); number = value.length === 9 ? value.substr( 0, 8 ) : value.substr( 0, 9 ); return validChars.charAt( parseInt( number, 10 ) % 23 ) === letter; }, "Please specify a valid NIE number." ); /* * The Nç…¤mero de Identificaciè´¸n Fiscal ( NIF ) is the way tax identification used in Spain for individuals */ $.validator.addMethod( "nifES", function( value, element ) { "use strict"; if ( this.optional( element ) ) { return true; } value = value.toUpperCase(); // Basic format test if ( !value.match( "((^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$|^[T]{1}[A-Z0-9]{8}$)|^[0-9]{8}[A-Z]{1}$)" ) ) { return false; } // Test NIF if ( /^[0-9]{8}[A-Z]{1}$/.test( value ) ) { return ( "TRWAGMYFPDXBNJZSQVHLCKE".charAt( value.substring( 8, 0 ) % 23 ) === value.charAt( 8 ) ); } // Test specials NIF (starts with K, L or M) if ( /^[KLM]{1}/.test( value ) ) { return ( value[ 8 ] === "TRWAGMYFPDXBNJZSQVHLCKE".charAt( value.substring( 8, 1 ) % 23 ) ); } return false; }, "Please specify a valid NIF number." ); /* * Numer identyfikacji podatkowej ( NIP ) is the way tax identification used in Poland for companies */ $.validator.addMethod( "nipPL", function( value ) { "use strict"; value = value.replace( /[^0-9]/g, "" ); if ( value.length !== 10 ) { return false; } var arrSteps = [ 6, 5, 7, 2, 3, 4, 5, 6, 7 ]; var intSum = 0; for ( var i = 0; i < 9; i++ ) { intSum += arrSteps[ i ] * value[ i ]; } var int2 = intSum % 11; var intControlNr = ( int2 === 10 ) ? 0 : int2; return ( intControlNr === parseInt( value[ 9 ], 10 ) ); }, "Please specify a valid NIP number." ); $.validator.addMethod( "notEqualTo", function( value, element, param ) { return this.optional( element ) || !$.validator.methods.equalTo.call( this, value, element, param ); }, "Please enter a different value, values must not be the same." ); $.validator.addMethod( "nowhitespace", function( value, element ) { return this.optional( element ) || /^\S+$/i.test( value ); }, "No white space please" ); /** * Return true if the field value matches the given format RegExp * * @example $.validator.methods.pattern("AR1004",element,/^AR\d{4}$/) * @result true * * @example $.validator.methods.pattern("BR1004",element,/^AR\d{4}$/) * @result false * * @name $.validator.methods.pattern * @type Boolean * @cat Plugins/Validate/Methods */ $.validator.addMethod( "pattern", function( value, element, param ) { if ( this.optional( element ) ) { return true; } if ( typeof param === "string" ) { param = new RegExp( "^(?:" + param + ")$" ); } return param.test( value ); }, "Invalid format." ); /** * Dutch phone numbers have 10 digits (or 11 and start with +31). */ $.validator.addMethod( "phoneNL", function( value, element ) { return this.optional( element ) || /^((\+|00(\s|\s?\-\s?)?)31(\s|\s?\-\s?)?(\(0\)[\-\s]?)?|0)[1-9]((\s|\s?\-\s?)?[0-9]){8}$/.test( value ); }, "Please specify a valid phone number." ); /* For UK phone functions, do the following server side processing: * Compare original input with this RegEx pattern: * ^\(?(?:(?:00\)?[\s\-]?\(?|\+)(44)\)?[\s\-]?\(?(?:0\)?[\s\-]?\(?)?|0)([1-9]\d{1,4}\)?[\s\d\-]+)$ * Extract $1 and set $prefix to '+44' if $1 is '44', otherwise set $prefix to '0' * Extract $2 and remove hyphens, spaces and parentheses. Phone number is combined $prefix and $2. * A number of very detailed GB telephone number RegEx patterns can also be found at: * http://www.aa-asterisk.org.uk/index.php/Regular_Expressions_for_Validating_and_Formatting_GB_Telephone_Numbers */ // Matches UK landline + mobile, accepting only 01-3 for landline or 07 for mobile to exclude many premium numbers $.validator.addMethod( "phonesUK", function( phone_number, element ) { phone_number = phone_number.replace( /\(|\)|\s+|-/g, "" ); return this.optional( element ) || phone_number.length > 9 && phone_number.match( /^(?:(?:(?:00\s?|\+)44\s?|0)(?:1\d{8,9}|[23]\d{9}|7(?:[1345789]\d{8}|624\d{6})))$/ ); }, "Please specify a valid uk phone number" ); /* For UK phone functions, do the following server side processing: * Compare original input with this RegEx pattern: * ^\(?(?:(?:00\)?[\s\-]?\(?|\+)(44)\)?[\s\-]?\(?(?:0\)?[\s\-]?\(?)?|0)([1-9]\d{1,4}\)?[\s\d\-]+)$ * Extract $1 and set $prefix to '+44' if $1 is '44', otherwise set $prefix to '0' * Extract $2 and remove hyphens, spaces and parentheses. Phone number is combined $prefix and $2. * A number of very detailed GB telephone number RegEx patterns can also be found at: * http://www.aa-asterisk.org.uk/index.php/Regular_Expressions_for_Validating_and_Formatting_GB_Telephone_Numbers */ $.validator.addMethod( "phoneUK", function( phone_number, element ) { phone_number = phone_number.replace( /\(|\)|\s+|-/g, "" ); return this.optional( element ) || phone_number.length > 9 && phone_number.match( /^(?:(?:(?:00\s?|\+)44\s?)|(?:\(?0))(?:\d{2}\)?\s?\d{4}\s?\d{4}|\d{3}\)?\s?\d{3}\s?\d{3,4}|\d{4}\)?\s?(?:\d{5}|\d{3}\s?\d{3})|\d{5}\)?\s?\d{4,5})$/ ); }, "Please specify a valid phone number" ); /** * Matches US phone number format * * where the area code may not start with 1 and the prefix may not start with 1 * allows '-' or ' ' as a separator and allows parens around area code * some people may want to put a '1' in front of their number * * 1(212)-999-2345 or * 212 999 2344 or * 212-999-0983 * * but not * 111-123-5434 * and not * 212 123 4567 */ $.validator.addMethod( "phoneUS", function( phone_number, element ) { phone_number = phone_number.replace( /\s+/g, "" ); return this.optional( element ) || phone_number.length > 9 && phone_number.match( /^(\+?1-?)?(\([2-9]([02-9]\d|1[02-9])\)|[2-9]([02-9]\d|1[02-9]))-?[2-9]([02-9]\d|1[02-9])-?\d{4}$/ ); }, "Please specify a valid phone number" ); /* * Valida CEPs do brasileiros: * * Formatos aceitos: * 99999-999 * 99.999-999 * 99999999 */ $.validator.addMethod( "postalcodeBR", function( cep_value, element ) { return this.optional( element ) || /^\d{2}.\d{3}-\d{3}?$|^\d{5}-?\d{3}?$/.test( cep_value ); }, "Informe um CEP vè°©lido." ); /** * Matches a valid Canadian Postal Code * * @example jQuery.validator.methods.postalCodeCA( "H0H 0H0", element ) * @result true * * @example jQuery.validator.methods.postalCodeCA( "H0H0H0", element ) * @result false * * @name jQuery.validator.methods.postalCodeCA * @type Boolean * @cat Plugins/Validate/Methods */ $.validator.addMethod( "postalCodeCA", function( value, element ) { return this.optional( element ) || /^[ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ] *\d[ABCEGHJKLMNPRSTVWXYZ]\d$/i.test( value ); }, "Please specify a valid postal code" ); /* Matches Italian postcode (CAP) */ $.validator.addMethod( "postalcodeIT", function( value, element ) { return this.optional( element ) || /^\d{5}$/.test( value ); }, "Please specify a valid postal code" ); $.validator.addMethod( "postalcodeNL", function( value, element ) { return this.optional( element ) || /^[1-9][0-9]{3}\s?[a-zA-Z]{2}$/.test( value ); }, "Please specify a valid postal code" ); // Matches UK postcode. Does not match to UK Channel Islands that have their own postcodes (non standard UK) $.validator.addMethod( "postcodeUK", function( value, element ) { return this.optional( element ) || /^((([A-PR-UWYZ][0-9])|([A-PR-UWYZ][0-9][0-9])|([A-PR-UWYZ][A-HK-Y][0-9])|([A-PR-UWYZ][A-HK-Y][0-9][0-9])|([A-PR-UWYZ][0-9][A-HJKSTUW])|([A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRVWXY]))\s?([0-9][ABD-HJLNP-UW-Z]{2})|(GIR)\s?(0AA))$/i.test( value ); }, "Please specify a valid UK postcode" ); /* * Lets you say "at least X inputs that match selector Y must be filled." * * The end result is that neither of these inputs: * * * * * ...will validate unless at least one of them is filled. * * partnumber: {require_from_group: [1,".productinfo"]}, * description: {require_from_group: [1,".productinfo"]} * * options[0]: number of fields that must be filled in the group * options[1]: CSS selector that defines the group of conditionally required fields */ $.validator.addMethod( "require_from_group", function( value, element, options ) { var $fields = $( options[ 1 ], element.form ), $fieldsFirst = $fields.eq( 0 ), validator = $fieldsFirst.data( "valid_req_grp" ) ? $fieldsFirst.data( "valid_req_grp" ) : $.extend( {}, this ), isValid = $fields.filter( function() { return validator.elementValue( this ); } ).length >= options[ 0 ]; // Store the cloned validator for future validation $fieldsFirst.data( "valid_req_grp", validator ); // If element isn't being validated, run each require_from_group field's validation rules if ( !$( element ).data( "being_validated" ) ) { $fields.data( "being_validated", true ); $fields.each( function() { validator.element( this ); } ); $fields.data( "being_validated", false ); } return isValid; }, $.validator.format( "Please fill at least {0} of these fields." ) ); /* * Lets you say "either at least X inputs that match selector Y must be filled, * OR they must all be skipped (left blank)." * * The end result, is that none of these inputs: * * * * * * ...will validate unless either at least two of them are filled, * OR none of them are. * * partnumber: {skip_or_fill_minimum: [2,".productinfo"]}, * description: {skip_or_fill_minimum: [2,".productinfo"]}, * color: {skip_or_fill_minimum: [2,".productinfo"]} * * options[0]: number of fields that must be filled in the group * options[1]: CSS selector that defines the group of conditionally required fields * */ $.validator.addMethod( "skip_or_fill_minimum", function( value, element, options ) { var $fields = $( options[ 1 ], element.form ), $fieldsFirst = $fields.eq( 0 ), validator = $fieldsFirst.data( "valid_skip" ) ? $fieldsFirst.data( "valid_skip" ) : $.extend( {}, this ), numberFilled = $fields.filter( function() { return validator.elementValue( this ); } ).length, isValid = numberFilled === 0 || numberFilled >= options[ 0 ]; // Store the cloned validator for future validation $fieldsFirst.data( "valid_skip", validator ); // If element isn't being validated, run each skip_or_fill_minimum field's validation rules if ( !$( element ).data( "being_validated" ) ) { $fields.data( "being_validated", true ); $fields.each( function() { validator.element( this ); } ); $fields.data( "being_validated", false ); } return isValid; }, $.validator.format( "Please either skip these fields or fill at least {0} of them." ) ); /* Validates US States and/or Territories by @jdforsythe * Can be case insensitive or require capitalization - default is case insensitive * Can include US Territories or not - default does not * Can include US Military postal abbreviations (AA, AE, AP) - default does not * * Note: "States" always includes DC (District of Colombia) * * Usage examples: * * This is the default - case insensitive, no territories, no military zones * stateInput: { * caseSensitive: false, * includeTerritories: false, * includeMilitary: false * } * * Only allow capital letters, no territories, no military zones * stateInput: { * caseSensitive: false * } * * Case insensitive, include territories but not military zones * stateInput: { * includeTerritories: true * } * * Only allow capital letters, include territories and military zones * stateInput: { * caseSensitive: true, * includeTerritories: true, * includeMilitary: true * } * */ $.validator.addMethod( "stateUS", function( value, element, options ) { var isDefault = typeof options === "undefined", caseSensitive = ( isDefault || typeof options.caseSensitive === "undefined" ) ? false : options.caseSensitive, includeTerritories = ( isDefault || typeof options.includeTerritories === "undefined" ) ? false : options.includeTerritories, includeMilitary = ( isDefault || typeof options.includeMilitary === "undefined" ) ? false : options.includeMilitary, regex; if ( !includeTerritories && !includeMilitary ) { regex = "^(A[KLRZ]|C[AOT]|D[CE]|FL|GA|HI|I[ADLN]|K[SY]|LA|M[ADEINOST]|N[CDEHJMVY]|O[HKR]|PA|RI|S[CD]|T[NX]|UT|V[AT]|W[AIVY])$"; } else if ( includeTerritories && includeMilitary ) { regex = "^(A[AEKLPRSZ]|C[AOT]|D[CE]|FL|G[AU]|HI|I[ADLN]|K[SY]|LA|M[ADEINOPST]|N[CDEHJMVY]|O[HKR]|P[AR]|RI|S[CD]|T[NX]|UT|V[AIT]|W[AIVY])$"; } else if ( includeTerritories ) { regex = "^(A[KLRSZ]|C[AOT]|D[CE]|FL|G[AU]|HI|I[ADLN]|K[SY]|LA|M[ADEINOPST]|N[CDEHJMVY]|O[HKR]|P[AR]|RI|S[CD]|T[NX]|UT|V[AIT]|W[AIVY])$"; } else { regex = "^(A[AEKLPRZ]|C[AOT]|D[CE]|FL|GA|HI|I[ADLN]|K[SY]|LA|M[ADEINOST]|N[CDEHJMVY]|O[HKR]|PA|RI|S[CD]|T[NX]|UT|V[AT]|W[AIVY])$"; } regex = caseSensitive ? new RegExp( regex ) : new RegExp( regex, "i" ); return this.optional( element ) || regex.test( value ); }, "Please specify a valid state" ); // TODO check if value starts with <, otherwise don't try stripping anything $.validator.addMethod( "strippedminlength", function( value, element, param ) { return $( value ).text().length >= param; }, $.validator.format( "Please enter at least {0} characters" ) ); $.validator.addMethod( "time", function( value, element ) { return this.optional( element ) || /^([01]\d|2[0-3]|[0-9])(:[0-5]\d){1,2}$/.test( value ); }, "Please enter a valid time, between 00:00 and 23:59" ); $.validator.addMethod( "time12h", function( value, element ) { return this.optional( element ) || /^((0?[1-9]|1[012])(:[0-5]\d){1,2}(\ ?[AP]M))$/i.test( value ); }, "Please enter a valid time in 12-hour am/pm format" ); // Same as url, but TLD is optional $.validator.addMethod( "url2", function( value, element ) { return this.optional( element ) || /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([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])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test( value ); }, $.validator.messages.url ); /** * Return true, if the value is a valid vehicle identification number (VIN). * * Works with all kind of text inputs. * * @example * @desc Declares a required input element whose value must be a valid vehicle identification number. * * @name $.validator.methods.vinUS * @type Boolean * @cat Plugins/Validate/Methods */ $.validator.addMethod( "vinUS", function( v ) { if ( v.length !== 17 ) { return false; } var LL = [ "A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" ], VL = [ 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 7, 9, 2, 3, 4, 5, 6, 7, 8, 9 ], FL = [ 8, 7, 6, 5, 4, 3, 2, 10, 0, 9, 8, 7, 6, 5, 4, 3, 2 ], rs = 0, i, n, d, f, cd, cdv; for ( i = 0; i < 17; i++ ) { f = FL[ i ]; d = v.slice( i, i + 1 ); if ( i === 8 ) { cdv = d; } if ( !isNaN( d ) ) { d *= f; } else { for ( n = 0; n < LL.length; n++ ) { if ( d.toUpperCase() === LL[ n ] ) { d = VL[ n ]; d *= f; if ( isNaN( cdv ) && n === 8 ) { cdv = LL[ n ]; } break; } } } rs += d; } cd = rs % 11; if ( cd === 10 ) { cd = "X"; } if ( cd === cdv ) { return true; } return false; }, "The specified vehicle identification number (VIN) is invalid." ); $.validator.addMethod( "zipcodeUS", function( value, element ) { return this.optional( element ) || /^\d{5}(-\d{4})?$/.test( value ); }, "The specified US ZIP Code is invalid" ); $.validator.addMethod( "ziprange", function( value, element ) { return this.optional( element ) || /^90[2-5]\d\{2\}-\d{4}$/.test( value ); }, "Your ZIP-code must be in the range 902xx-xxxx to 905xx-xxxx" ); return $; })); /** * Simple, lightweight, usable local autocomplete library for modern browsers * Because there weren鈥檛 enough autocomplete scripts in the world? Because I鈥檓 completely insane and have NIH syndrome? Probably both. :P * @author Lea Verou http://leaverou.github.io/awesomplete * MIT license */ (function () { var _ = function (input, o) { var me = this; // Setup this.isOpened = false; this.input = $(input); this.input.setAttribute("autocomplete", "off"); this.input.setAttribute("aria-autocomplete", "list"); o = o || {}; configure(this, { minChars: 2, maxItems: 10, autoFirst: false, data: _.DATA, filter: _.FILTER_CONTAINS, sort: o.sort === false ? false : _.SORT_BYLENGTH, item: _.ITEM, replace: _.REPLACE }, o); this.index = -1; // Create necessary elements this.container = $.create("div", { className: "awesomplete", around: input }); this.ul = $.create("ul", { hidden: "hidden", inside: this.container }); this.status = $.create("span", { className: "visually-hidden", role: "status", "aria-live": "assertive", "aria-relevant": "additions", inside: this.container }); // Bind events this._events = { input: { "input": this.evaluate.bind(this), "blur": this.close.bind(this, { reason: "blur" }), "keydown": function(evt) { var c = evt.keyCode; // If the dropdown `ul` is in view, then act on keydown for the following keys: // Enter / Esc / Up / Down if(me.opened) { if (c === 13 && me.selected) { // Enter evt.preventDefault(); me.select(); } else if (c === 27) { // Esc me.close({ reason: "esc" }); } else if (c === 38 || c === 40) { // Down/Up arrow evt.preventDefault(); me[c === 38? "previous" : "next"](); } } } }, form: { "submit": this.close.bind(this, { reason: "submit" }) }, ul: { "mousedown": function(evt) { var li = evt.target; if (li !== this) { while (li && !/li/i.test(li.nodeName)) { li = li.parentNode; } if (li && evt.button === 0) { // Only select on left click evt.preventDefault(); me.select(li, evt.target); } } } } }; $.bind(this.input, this._events.input); $.bind(this.input.form, this._events.form); $.bind(this.ul, this._events.ul); if (this.input.hasAttribute("list")) { this.list = "#" + this.input.getAttribute("list"); this.input.removeAttribute("list"); } else { this.list = this.input.getAttribute("data-list") || o.list || []; } _.all.push(this); }; _.prototype = { set list(list) { if (Array.isArray(list)) { this._list = list; } else if (typeof list === "string" && list.indexOf(",") > -1) { this._list = list.split(/\s*,\s*/); } else { // Element or CSS selector list = $(list); if (list && list.children) { var items = []; slice.apply(list.children).forEach(function (el) { if (!el.disabled) { var text = el.textContent.trim(); var value = el.value || text; var label = el.label || text; if (value !== "") { items.push({ label: label, value: value }); } } }); this._list = items; } } if (document.activeElement === this.input) { this.evaluate(); } }, get selected() { return this.index > -1; }, get opened() { return this.isOpened; }, close: function (o) { if (!this.opened) { return; } this.ul.setAttribute("hidden", ""); this.isOpened = false; this.index = -1; $.fire(this.input, "awesomplete-close", o || {}); }, open: function () { this.ul.removeAttribute("hidden"); this.isOpened = true; if (this.autoFirst && this.index === -1) { this.goto(0); } $.fire(this.input, "awesomplete-open"); }, destroy: function() { //remove events from the input and its form $.unbind(this.input, this._events.input); $.unbind(this.input.form, this._events.form); //move the input out of the awesomplete container and remove the container and its children var parentNode = this.container.parentNode; parentNode.insertBefore(this.input, this.container); parentNode.removeChild(this.container); //remove autocomplete and aria-autocomplete attributes this.input.removeAttribute("autocomplete"); this.input.removeAttribute("aria-autocomplete"); //remove this awesomeplete instance from the global array of instances var indexOfAwesomplete = _.all.indexOf(this); if (indexOfAwesomplete !== -1) { _.all.splice(indexOfAwesomplete, 1); } }, next: function () { var count = this.ul.children.length; this.goto(this.index < count - 1 ? this.index + 1 : (count ? 0 : -1) ); }, previous: function () { var count = this.ul.children.length; var pos = this.index - 1; this.goto(this.selected && pos !== -1 ? pos : count - 1); }, // Should not be used, highlights specific item without any checks! goto: function (i) { var lis = this.ul.children; if (this.selected) { lis[this.index].setAttribute("aria-selected", "false"); } this.index = i; if (i > -1 && lis.length > 0) { lis[i].setAttribute("aria-selected", "true"); this.status.textContent = lis[i].textContent; // scroll to highlighted element in case parent's height is fixed this.ul.scrollTop = lis[i].offsetTop - this.ul.clientHeight + lis[i].clientHeight; $.fire(this.input, "awesomplete-highlight", { text: this.suggestions[this.index] }); } }, select: function (selected, origin) { if (selected) { this.index = $.siblingIndex(selected); } else { selected = this.ul.children[this.index]; } if (selected) { var suggestion = this.suggestions[this.index]; var allowed = $.fire(this.input, "awesomplete-select", { text: suggestion, origin: origin || selected }); if (allowed) { this.replace(suggestion); this.close({ reason: "select" }); $.fire(this.input, "awesomplete-selectcomplete", { text: suggestion }); } } }, evaluate: function() { var me = this; var value = this.input.value; if (value.length >= this.minChars && this._list.length > 0) { this.index = -1; // Populate list with options that match this.ul.innerHTML = ""; this.suggestions = this._list .map(function(item) { return new Suggestion(me.data(item, value)); }) .filter(function(item) { return me.filter(item, value); }); if (this.sort !== false) { this.suggestions = this.suggestions.sort(this.sort); } this.suggestions = this.suggestions.slice(0, this.maxItems); this.suggestions.forEach(function(text) { me.ul.appendChild(me.item(text, value)); }); if (this.ul.children.length === 0) { //this.close({ reason: "nomatches" }); var z = document.createElement('li'); // is a node z.innerHTML = 'No Product matches'; me.ul.appendChild(z); } else { this.open(); } } else { // this.close({ reason: "nomatches" }); } } }; // Static methods/properties _.all = []; _.FILTER_CONTAINS = function (text, input) { return RegExp($.regExpEscape(input.trim()), "i").test(text); }; _.FILTER_STARTSWITH = function (text, input) { return RegExp("^" + $.regExpEscape(input.trim()), "i").test(text); }; _.SORT_BYLENGTH = function (a, b) { if (a.length !== b.length) { return a.length - b.length; } return a < b? -1 : 1; }; _.ITEM = function (text, input) { var html = input.trim() === "" ? text : text.replace(RegExp($.regExpEscape(input.trim()), "gi"), "$&"); return $.create("li", { innerHTML: html, "aria-selected": "false" }); }; _.REPLACE = function (text) { this.input.value = text.value; }; _.DATA = function (item/*, input*/) { return item; }; // Private functions function Suggestion(data) { var o = Array.isArray(data) ? { label: data[0], value: data[1] } : typeof data === "object" && "label" in data && "value" in data ? data : { label: data, value: data }; this.label = o.label || o.value; this.value = o.value; } Object.defineProperty(Suggestion.prototype = Object.create(String.prototype), "length", { get: function() { return this.label.length; } }); Suggestion.prototype.toString = Suggestion.prototype.valueOf = function () { return "" + this.label; }; function configure(instance, properties, o) { for (var i in properties) { var initial = properties[i], attrValue = instance.input.getAttribute("data-" + i.toLowerCase()); if (typeof initial === "number") { instance[i] = parseInt(attrValue); } else if (initial === false) { // Boolean options must be false by default anyway instance[i] = attrValue !== null; } else if (initial instanceof Function) { instance[i] = null; } else { instance[i] = attrValue; } if (!instance[i] && instance[i] !== 0) { instance[i] = (i in o)? o[i] : initial; } } } // Helpers var slice = Array.prototype.slice; function $(expr, con) { return typeof expr === "string"? (con || document).querySelector(expr) : expr || null; } function $$(expr, con) { return slice.call((con || document).querySelectorAll(expr)); } $.create = function(tag, o) { var element = document.createElement(tag); for (var i in o) { var val = o[i]; if (i === "inside") { $(val).appendChild(element); } else if (i === "around") { var ref = $(val); ref.parentNode.insertBefore(element, ref); element.appendChild(ref); } else if (i in element) { element[i] = val; } else { element.setAttribute(i, val); } } return element; }; $.bind = function(element, o) { if (element) { for (var event in o) { var callback = o[event]; event.split(/\s+/).forEach(function (event) { element.addEventListener(event, callback); }); } } }; $.unbind = function(element, o) { if (element) { for (var event in o) { var callback = o[event]; event.split(/\s+/).forEach(function(event) { element.removeEventListener(event, callback); }); } } }; $.fire = function(target, type, properties) { var evt = document.createEvent("HTMLEvents"); evt.initEvent(type, true, true ); for (var j in properties) { evt[j] = properties[j]; } return target.dispatchEvent(evt); }; $.regExpEscape = function (s) { return s.replace(/[-\\^$*+?.()|[\]{}]/g, "\\$&"); }; $.siblingIndex = function (el) { /* eslint-disable no-cond-assign */ for (var i = 0; el = el.previousElementSibling; i++); return i; }; // Initialization function init() { $$("input.awesomplete").forEach(function (input) { new _(input); }); } // Are we in a browser? Check for Document constructor if (typeof Document !== "undefined") { // DOM already loaded? if (document.readyState !== "loading") { init(); } else { // Wait for it document.addEventListener("DOMContentLoaded", init); } } _.$ = $; _.$$ = $$; // Make sure to export Awesomplete on self when in a browser if (typeof self !== "undefined") { self.Awesomplete = _; } // Expose Awesomplete as a CJS module if (typeof module === "object" && module.exports) { module.exports = _; } return _; }()); /** * lscache library * Copyright (c) 2011, Pamela Fox * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* jshint undef:true, browser:true, node:true */ /* global define */ (function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define([], factory); } else if (typeof module !== "undefined" && module.exports) { // CommonJS/Node module module.exports = factory(); } else { // Browser globals root.lscache = factory(); } }(this, function () { // Prefix for all lscache keys var CACHE_PREFIX = 'lscache-'; // Suffix for the key name on the expiration items in localStorage var CACHE_SUFFIX = '-cacheexpiration'; // expiration date radix (set to Base-36 for most space savings) var EXPIRY_RADIX = 10; // time resolution in milliseconds var expiryMilliseconds = 60 * 1000; // ECMAScript max Date (epoch + 1e8 days) var maxDate = calculateMaxDate(expiryMilliseconds); var cachedStorage; var cachedJSON; var cacheBucket = ''; var warnings = false; // Determines if localStorage is supported in the browser; // result is cached for better performance instead of being run each time. // Feature detection is based on how Modernizr does it; // it's not straightforward due to FF4 issues. // It's not run at parse-time as it takes 200ms in Android. function supportsStorage() { var key = '__lscachetest__'; var value = key; if (cachedStorage !== undefined) { return cachedStorage; } // some browsers will throw an error if you try to access local storage (e.g. brave browser) // hence check is inside a try/catch try { if (!localStorage) { return false; } } catch (ex) { return false; } try { setItem(key, value); removeItem(key); cachedStorage = true; } catch (e) { // If we hit the limit, and we don't have an empty localStorage then it means we have support if (isOutOfSpace(e) && localStorage.length) { cachedStorage = true; // just maxed it out and even the set test failed. } else { cachedStorage = false; } } return cachedStorage; } // Check to set if the error is us dealing with being out of space function isOutOfSpace(e) { return e && ( e.name === 'QUOTA_EXCEEDED_ERR' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED' || e.name === 'QuotaExceededError' ); } // Determines if native JSON (de-)serialization is supported in the browser. function supportsJSON() { /*jshint eqnull:true */ if (cachedJSON === undefined) { cachedJSON = (window.JSON != null); } return cachedJSON; } /** * Returns a string where all RegExp special characters are escaped with a \. * @param {String} text * @return {string} */ function escapeRegExpSpecialCharacters(text) { return text.replace(/[[\]{}()*+?.\\^$|]/g, '\\$&'); } /** * Returns the full string for the localStorage expiration item. * @param {String} key * @return {string} */ function expirationKey(key) { return key + CACHE_SUFFIX; } /** * Returns the number of minutes since the epoch. * @return {number} */ function currentTime() { return Math.floor((new Date().getTime())/expiryMilliseconds); } /** * Wrapper functions for localStorage methods */ function getItem(key) { return localStorage.getItem(CACHE_PREFIX + cacheBucket + key); } function setItem(key, value) { // Fix for iPad issue - sometimes throws QUOTA_EXCEEDED_ERR on setItem. localStorage.removeItem(CACHE_PREFIX + cacheBucket + key); localStorage.setItem(CACHE_PREFIX + cacheBucket + key, value); } function removeItem(key) { localStorage.removeItem(CACHE_PREFIX + cacheBucket + key); } function eachKey(fn) { var prefixRegExp = new RegExp('^' + CACHE_PREFIX + escapeRegExpSpecialCharacters(cacheBucket) + '(.*)'); // Loop in reverse as removing items will change indices of tail for (var i = localStorage.length-1; i >= 0 ; --i) { var key = localStorage.key(i); key = key && key.match(prefixRegExp); key = key && key[1]; if (key && key.indexOf(CACHE_SUFFIX) < 0) { fn(key, expirationKey(key)); } } } function flushItem(key) { var exprKey = expirationKey(key); removeItem(key); removeItem(exprKey); } function flushExpiredItem(key) { var exprKey = expirationKey(key); var expr = getItem(exprKey); if (expr) { var expirationTime = parseInt(expr, EXPIRY_RADIX); // Check if we should actually kick item out of storage if (currentTime() >= expirationTime) { removeItem(key); removeItem(exprKey); return true; } } } function warn(message, err) { if (!warnings) return; if (!('console' in window) || typeof window.console.warn !== 'function') return; window.console.warn("lscache - " + message); if (err) window.console.warn("lscache - The error was: " + err.message); } function calculateMaxDate(expiryMilliseconds) { return Math.floor(8.64e15/expiryMilliseconds); } var lscache = { /** * Stores the value in localStorage. Expires after specified number of minutes. * @param {string} key * @param {Object|string} value * @param {number} time */ set: function(key, value, time) { if (!supportsStorage()) return; // If we don't get a string value, try to stringify // In future, localStorage may properly support storing non-strings // and this can be removed. if (!supportsJSON()) return; try { value = JSON.stringify(value); } catch (e) { // Sometimes we can't stringify due to circular refs // in complex objects, so we won't bother storing then. return; } try { setItem(key, value); } catch (e) { if (isOutOfSpace(e)) { // If we exceeded the quota, then we will sort // by the expire time, and then remove the N oldest var storedKeys = []; var storedKey; eachKey(function(key, exprKey) { var expiration = getItem(exprKey); if (expiration) { expiration = parseInt(expiration, EXPIRY_RADIX); } else { // TODO: Store date added for non-expiring items for smarter removal expiration = maxDate; } storedKeys.push({ key: key, size: (getItem(key) || '').length, expiration: expiration }); }); // Sorts the keys with oldest expiration time last storedKeys.sort(function(a, b) { return (b.expiration-a.expiration); }); var targetSize = (value||'').length; while (storedKeys.length && targetSize > 0) { storedKey = storedKeys.pop(); warn("Cache is full, removing item with key '" + key + "'"); flushItem(storedKey.key); targetSize -= storedKey.size; } try { setItem(key, value); } catch (e) { // value may be larger than total quota warn("Could not add item with key '" + key + "', perhaps it's too big?", e); return; } } else { // If it was some other error, just give up. warn("Could not add item with key '" + key + "'", e); return; } } // If a time is specified, store expiration info in localStorage if (time) { setItem(expirationKey(key), (currentTime() + time).toString(EXPIRY_RADIX)); } else { // In case they previously set a time, remove that info from localStorage. removeItem(expirationKey(key)); } }, /** * Retrieves specified value from localStorage, if not expired. * @param {string} key * @return {string|Object} */ get: function(key) { if (!supportsStorage()) return null; // Return the de-serialized item if not expired if (flushExpiredItem(key)) { return null; } // Tries to de-serialize stored value if its an object, and returns the normal value otherwise. var value = getItem(key); if (!value || !supportsJSON()) { return value; } try { // We can't tell if its JSON or a string, so we try to parse return JSON.parse(value); } catch (e) { // If we can't parse, it's probably because it isn't an object return value; } }, /** * Removes a value from localStorage. * Equivalent to 'delete' in memcache, but that's a keyword in JS. * @param {string} key */ remove: function(key) { if (!supportsStorage()) return; flushItem(key); }, /** * Returns whether local storage is supported. * Currently exposed for testing purposes. * @return {boolean} */ supported: function() { return supportsStorage(); }, /** * Flushes all lscache items and expiry markers without affecting rest of localStorage */ flush: function() { if (!supportsStorage()) return; eachKey(function(key) { flushItem(key); }); }, /** * Flushes expired lscache items and expiry markers without affecting rest of localStorage */ flushExpired: function() { if (!supportsStorage()) return; eachKey(function(key) { flushExpiredItem(key); }); }, /** * Appends CACHE_PREFIX so lscache will partition data in to different buckets. * @param {string} bucket */ setBucket: function(bucket) { cacheBucket = bucket; }, /** * Resets the string being appended to CACHE_PREFIX so lscache will use the default storage behavior. */ resetBucket: function() { cacheBucket = ''; }, /** * @returns {number} The currently set number of milliseconds each time unit represents in * the set() function's "time" argument. */ getExpiryMilliseconds: function() { return expiryMilliseconds; }, /** * Sets the number of milliseconds each time unit represents in the set() function's * "time" argument. * Sample values: * 1: each time unit = 1 millisecond * 1000: each time unit = 1 second * 60000: each time unit = 1 minute (Default value) * 360000: each time unit = 1 hour * @param {number} milliseconds */ setExpiryMilliseconds: function(milliseconds) { expiryMilliseconds = milliseconds; maxDate = calculateMaxDate(expiryMilliseconds); }, /** * Sets whether to display warnings when an item is removed from the cache or not. */ enableWarnings: function(enabled) { warnings = enabled; } }; // Return the module return lscache; })); /*! picturefill - v3.0.2 - 2016-02-12 * https://scottjehl.github.io/picturefill/ * Copyright (c) 2016 https://github.com/scottjehl/picturefill/blob/master/Authors.txt; Licensed MIT */ /*! Gecko-Picture - v1.0 * https://github.com/scottjehl/picturefill/tree/3.0/src/plugins/gecko-picture * Firefox's early picture implementation (prior to FF41) is static and does * not react to viewport changes. This tiny module fixes this. */ (function(window) { /*jshint eqnull:true */ var ua = navigator.userAgent; if ( window.HTMLPictureElement && ((/ecko/).test(ua) && ua.match(/rv\:(\d+)/) && RegExp.$1 < 45) ) { addEventListener("resize", (function() { var timer; var dummySrc = document.createElement("source"); var fixRespimg = function(img) { var source, sizes; var picture = img.parentNode; if (picture.nodeName.toUpperCase() === "PICTURE") { source = dummySrc.cloneNode(); picture.insertBefore(source, picture.firstElementChild); setTimeout(function() { picture.removeChild(source); }); } else if (!img._pfLastSize || img.offsetWidth > img._pfLastSize) { img._pfLastSize = img.offsetWidth; sizes = img.sizes; img.sizes += ",100vw"; setTimeout(function() { img.sizes = sizes; }); } }; var findPictureImgs = function() { var i; var imgs = document.querySelectorAll("picture > img, img[srcset][sizes]"); for (i = 0; i < imgs.length; i++) { fixRespimg(imgs[i]); } }; var onResize = function() { clearTimeout(timer); timer = setTimeout(findPictureImgs, 99); }; var mq = window.matchMedia && matchMedia("(orientation: landscape)"); var init = function() { onResize(); if (mq && mq.addListener) { mq.addListener(onResize); } }; dummySrc.srcset = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; if (/^[c|i]|d$/.test(document.readyState || "")) { init(); } else { document.addEventListener("DOMContentLoaded", init); } return onResize; })()); } })(window); /*! Picturefill - v3.0.2 * http://scottjehl.github.io/picturefill * Copyright (c) 2015 https://github.com/scottjehl/picturefill/blob/master/Authors.txt; * License: MIT */ (function( window, document, undefined ) { // Enable strict mode "use strict"; // HTML shim|v it for old IE (IE9 will still need the HTML video tag workaround) document.createElement( "picture" ); var warn, eminpx, alwaysCheckWDescriptor, evalId; // local object for method references and testing exposure var pf = {}; var isSupportTestReady = false; var noop = function() {}; var image = document.createElement( "img" ); var getImgAttr = image.getAttribute; var setImgAttr = image.setAttribute; var removeImgAttr = image.removeAttribute; var docElem = document.documentElement; var types = {}; var cfg = { //resource selection: algorithm: "" }; var srcAttr = "data-pfsrc"; var srcsetAttr = srcAttr + "set"; // ua sniffing is done for undetectable img loading features, // to do some non crucial perf optimizations var ua = navigator.userAgent; var supportAbort = (/rident/).test(ua) || ((/ecko/).test(ua) && ua.match(/rv\:(\d+)/) && RegExp.$1 > 35 ); var curSrcProp = "currentSrc"; var regWDesc = /\s+\+?\d+(e\d+)?w/; var regSize = /(\([^)]+\))?\s*(.+)/; var setOptions = window.picturefillCFG; /** * Shortcut property for https://w3c.github.io/webappsec/specs/mixedcontent/#restricts-mixed-content ( for easy overriding in tests ) */ // baseStyle also used by getEmValue (i.e.: width: 1em is important) var baseStyle = "position:absolute;left:0;visibility:hidden;display:block;padding:0;border:none;font-size:1em;width:1em;overflow:hidden;clip:rect(0px, 0px, 0px, 0px)"; var fsCss = "font-size:100%!important;"; var isVwDirty = true; var cssCache = {}; var sizeLengthCache = {}; var DPR = window.devicePixelRatio; var units = { px: 1, "in": 96 }; var anchor = document.createElement( "a" ); /** * alreadyRun flag used for setOptions. is it true setOptions will reevaluate * @type {boolean} */ var alreadyRun = false; // Reusable, non-"g" Regexes // (Don't use \s, to avoid matching non-breaking space.) var regexLeadingSpaces = /^[ \t\n\r\u000c]+/, regexLeadingCommasOrSpaces = /^[, \t\n\r\u000c]+/, regexLeadingNotSpaces = /^[^ \t\n\r\u000c]+/, regexTrailingCommas = /[,]+$/, regexNonNegativeInteger = /^\d+$/, // ( Positive or negative or unsigned integers or decimals, without or without exponents. // Must include at least one digit. // According to spec tests any decimal point must be followed by a digit. // No leading plus sign is allowed.) // https://html.spec.whatwg.org/multipage/infrastructure.html#valid-floating-point-number regexFloatingPoint = /^-?(?:[0-9]+|[0-9]*\.[0-9]+)(?:[eE][+-]?[0-9]+)?$/; var on = function(obj, evt, fn, capture) { if ( obj.addEventListener ) { obj.addEventListener(evt, fn, capture || false); } else if ( obj.attachEvent ) { obj.attachEvent( "on" + evt, fn); } }; /** * simple memoize function: */ var memoize = function(fn) { var cache = {}; return function(input) { if ( !(input in cache) ) { cache[ input ] = fn(input); } return cache[ input ]; }; }; // UTILITY FUNCTIONS // Manual is faster than RegEx // http://jsperf.com/whitespace-character/5 function isSpace(c) { return (c === "\u0020" || // space c === "\u0009" || // horizontal tab c === "\u000A" || // new line c === "\u000C" || // form feed c === "\u000D"); // carriage return } /** * gets a mediaquery and returns a boolean or gets a css length and returns a number * @param css mediaqueries or css length * @returns {boolean|number} * * based on: https://gist.github.com/jonathantneal/db4f77009b155f083738 */ var evalCSS = (function() { var regLength = /^([\d\.]+)(em|vw|px)$/; var replace = function() { var args = arguments, index = 0, string = args[0]; while (++index in args) { string = string.replace(args[index], args[++index]); } return string; }; var buildStr = memoize(function(css) { return "return " + replace((css || "").toLowerCase(), // interpret `and` /\band\b/g, "&&", // interpret `,` /,/g, "||", // interpret `min-` as >= /min-([a-z-\s]+):/g, "e.$1>=", // interpret `max-` as <= /max-([a-z-\s]+):/g, "e.$1<=", //calc value /calc([^)]+)/g, "($1)", // interpret css values /(\d+[\.]*[\d]*)([a-z]+)/g, "($1 * e.$2)", //make eval less evil /^(?!(e.[a-z]|[0-9\.&=|><\+\-\*\(\)\/])).*/ig, "" ) + ";"; }); return function(css, length) { var parsedLength; if (!(css in cssCache)) { cssCache[css] = false; if (length && (parsedLength = css.match( regLength ))) { cssCache[css] = parsedLength[ 1 ] * units[parsedLength[ 2 ]]; } else { /*jshint evil:true */ try{ cssCache[css] = new Function("e", buildStr(css))(units); } catch(e) {} /*jshint evil:false */ } } return cssCache[css]; }; })(); var setResolution = function( candidate, sizesattr ) { if ( candidate.w ) { // h = means height: || descriptor.type === 'h' do not handle yet... candidate.cWidth = pf.calcListLength( sizesattr || "100vw" ); candidate.res = candidate.w / candidate.cWidth ; } else { candidate.res = candidate.d; } return candidate; }; /** * * @param opt */ var picturefill = function( opt ) { if (!isSupportTestReady) {return;} var elements, i, plen; var options = opt || {}; if ( options.elements && options.elements.nodeType === 1 ) { if ( options.elements.nodeName.toUpperCase() === "IMG" ) { options.elements = [ options.elements ]; } else { options.context = options.elements; options.elements = null; } } elements = options.elements || pf.qsa( (options.context || document), ( options.reevaluate || options.reselect ) ? pf.sel : pf.selShort ); if ( (plen = elements.length) ) { pf.setupRun( options ); alreadyRun = true; // Loop through all elements for ( i = 0; i < plen; i++ ) { pf.fillImg(elements[ i ], options); } pf.teardownRun( options ); } }; /** * outputs a warning for the developer * @param {message} * @type {Function} */ warn = ( window.console && console.warn ) ? function( message ) { console.warn( message ); } : noop ; if ( !(curSrcProp in image) ) { curSrcProp = "src"; } // Add support for standard mime types. types[ "image/jpeg" ] = true; types[ "image/gif" ] = true; types[ "image/png" ] = true; function detectTypeSupport( type, typeUri ) { // based on Modernizr's lossless img-webp test // note: asynchronous var image = new window.Image(); image.onerror = function() { types[ type ] = false; picturefill(); }; image.onload = function() { types[ type ] = image.width === 1; picturefill(); }; image.src = typeUri; return "pending"; } // test svg support types[ "image/svg+xml" ] = document.implementation.hasFeature( "http://www.w3.org/TR/SVG11/feature#Image", "1.1" ); /** * updates the internal vW property with the current viewport width in px */ function updateMetrics() { isVwDirty = false; DPR = window.devicePixelRatio; cssCache = {}; sizeLengthCache = {}; pf.DPR = DPR || 1; units.width = Math.max(window.innerWidth || 0, docElem.clientWidth); units.height = Math.max(window.innerHeight || 0, docElem.clientHeight); units.vw = units.width / 100; units.vh = units.height / 100; evalId = [ units.height, units.width, DPR ].join("-"); units.em = pf.getEmValue(); units.rem = units.em; } function chooseLowRes( lowerValue, higherValue, dprValue, isCached ) { var bonusFactor, tooMuch, bonus, meanDensity; //experimental if (cfg.algorithm === "saveData" ){ if ( lowerValue > 2.7 ) { meanDensity = dprValue + 1; } else { tooMuch = higherValue - dprValue; bonusFactor = Math.pow(lowerValue - 0.6, 1.5); bonus = tooMuch * bonusFactor; if (isCached) { bonus += 0.1 * bonusFactor; } meanDensity = lowerValue + bonus; } } else { meanDensity = (dprValue > 1) ? Math.sqrt(lowerValue * higherValue) : lowerValue; } return meanDensity > dprValue; } function applyBestCandidate( img ) { var srcSetCandidates; var matchingSet = pf.getSet( img ); var evaluated = false; if ( matchingSet !== "pending" ) { evaluated = evalId; if ( matchingSet ) { srcSetCandidates = pf.setRes( matchingSet ); pf.applySetCandidate( srcSetCandidates, img ); } } img[ pf.ns ].evaled = evaluated; } function ascendingSort( a, b ) { return a.res - b.res; } function setSrcToCur( img, src, set ) { var candidate; if ( !set && src ) { set = img[ pf.ns ].sets; set = set && set[set.length - 1]; } candidate = getCandidateForSrc(src, set); if ( candidate ) { src = pf.makeUrl(src); img[ pf.ns ].curSrc = src; img[ pf.ns ].curCan = candidate; if ( !candidate.res ) { setResolution( candidate, candidate.set.sizes ); } } return candidate; } function getCandidateForSrc( src, set ) { var i, candidate, candidates; if ( src && set ) { candidates = pf.parseSet( set ); src = pf.makeUrl(src); for ( i = 0; i < candidates.length; i++ ) { if ( src === pf.makeUrl(candidates[ i ].url) ) { candidate = candidates[ i ]; break; } } } return candidate; } function getAllSourceElements( picture, candidates ) { var i, len, source, srcset; // SPEC mismatch intended for size and perf: // actually only source elements preceding the img should be used // also note: don't use qsa here, because IE8 sometimes doesn't like source as the key part in a selector var sources = picture.getElementsByTagName( "source" ); for ( i = 0, len = sources.length; i < len; i++ ) { source = sources[ i ]; source[ pf.ns ] = true; srcset = source.getAttribute( "srcset" ); // if source does not have a srcset attribute, skip if ( srcset ) { candidates.push( { srcset: srcset, media: source.getAttribute( "media" ), type: source.getAttribute( "type" ), sizes: source.getAttribute( "sizes" ) } ); } } } /** * Srcset Parser * By Alex Bell | MIT License * * @returns Array [{url: _, d: _, w: _, h:_, set:_(????)}, ...] * * Based super duper closely on the reference algorithm at: * https://html.spec.whatwg.org/multipage/embedded-content.html#parse-a-srcset-attribute */ // 1. Let input be the value passed to this algorithm. // (TO-DO : Explain what "set" argument is here. Maybe choose a more // descriptive & more searchable name. Since passing the "set" in really has // nothing to do with parsing proper, I would prefer this assignment eventually // go in an external fn.) function parseSrcset(input, set) { function collectCharacters(regEx) { var chars, match = regEx.exec(input.substring(pos)); if (match) { chars = match[ 0 ]; pos += chars.length; return chars; } } var inputLength = input.length, url, descriptors, currentDescriptor, state, c, // 2. Let position be a pointer into input, initially pointing at the start // of the string. pos = 0, // 3. Let candidates be an initially empty source set. candidates = []; /** * Adds descriptor properties to a candidate, pushes to the candidates array * @return undefined */ // (Declared outside of the while loop so that it's only created once. // (This fn is defined before it is used, in order to pass JSHINT. // Unfortunately this breaks the sequencing of the spec comments. :/ ) function parseDescriptors() { // 9. Descriptor parser: Let error be no. var pError = false, // 10. Let width be absent. // 11. Let density be absent. // 12. Let future-compat-h be absent. (We're implementing it now as h) w, d, h, i, candidate = {}, desc, lastChar, value, intVal, floatVal; // 13. For each descriptor in descriptors, run the appropriate set of steps // from the following list: for (i = 0 ; i < descriptors.length; i++) { desc = descriptors[ i ]; lastChar = desc[ desc.length - 1 ]; value = desc.substring(0, desc.length - 1); intVal = parseInt(value, 10); floatVal = parseFloat(value); // If the descriptor consists of a valid non-negative integer followed by // a U+0077 LATIN SMALL LETTER W character if (regexNonNegativeInteger.test(value) && (lastChar === "w")) { // If width and density are not both absent, then let error be yes. if (w || d) {pError = true;} // Apply the rules for parsing non-negative integers to the descriptor. // If the result is zero, let error be yes. // Otherwise, let width be the result. if (intVal === 0) {pError = true;} else {w = intVal;} // If the descriptor consists of a valid floating-point number followed by // a U+0078 LATIN SMALL LETTER X character } else if (regexFloatingPoint.test(value) && (lastChar === "x")) { // If width, density and future-compat-h are not all absent, then let error // be yes. if (w || d || h) {pError = true;} // Apply the rules for parsing floating-point number values to the descriptor. // If the result is less than zero, let error be yes. Otherwise, let density // be the result. if (floatVal < 0) {pError = true;} else {d = floatVal;} // If the descriptor consists of a valid non-negative integer followed by // a U+0068 LATIN SMALL LETTER H character } else if (regexNonNegativeInteger.test(value) && (lastChar === "h")) { // If height and density are not both absent, then let error be yes. if (h || d) {pError = true;} // Apply the rules for parsing non-negative integers to the descriptor. // If the result is zero, let error be yes. Otherwise, let future-compat-h // be the result. if (intVal === 0) {pError = true;} else {h = intVal;} // Anything else, Let error be yes. } else {pError = true;} } // (close step 13 for loop) // 15. If error is still no, then append a new image source to candidates whose // URL is url, associated with a width width if not absent and a pixel // density density if not absent. Otherwise, there is a parse error. if (!pError) { candidate.url = url; if (w) { candidate.w = w;} if (d) { candidate.d = d;} if (h) { candidate.h = h;} if (!h && !d && !w) {candidate.d = 1;} if (candidate.d === 1) {set.has1x = true;} candidate.set = set; candidates.push(candidate); } } // (close parseDescriptors fn) /** * Tokenizes descriptor properties prior to parsing * Returns undefined. * (Again, this fn is defined before it is used, in order to pass JSHINT. * Unfortunately this breaks the logical sequencing of the spec comments. :/ ) */ function tokenize() { // 8.1. Descriptor tokeniser: Skip whitespace collectCharacters(regexLeadingSpaces); // 8.2. Let current descriptor be the empty string. currentDescriptor = ""; // 8.3. Let state be in descriptor. state = "in descriptor"; while (true) { // 8.4. Let c be the character at position. c = input.charAt(pos); // Do the following depending on the value of state. // For the purpose of this step, "EOF" is a special character representing // that position is past the end of input. // In descriptor if (state === "in descriptor") { // Do the following, depending on the value of c: // Space character // If current descriptor is not empty, append current descriptor to // descriptors and let current descriptor be the empty string. // Set state to after descriptor. if (isSpace(c)) { if (currentDescriptor) { descriptors.push(currentDescriptor); currentDescriptor = ""; state = "after descriptor"; } // U+002C COMMA (,) // Advance position to the next character in input. If current descriptor // is not empty, append current descriptor to descriptors. Jump to the step // labeled descriptor parser. } else if (c === ",") { pos += 1; if (currentDescriptor) { descriptors.push(currentDescriptor); } parseDescriptors(); return; // U+0028 LEFT PARENTHESIS (() // Append c to current descriptor. Set state to in parens. } else if (c === "\u0028") { currentDescriptor = currentDescriptor + c; state = "in parens"; // EOF // If current descriptor is not empty, append current descriptor to // descriptors. Jump to the step labeled descriptor parser. } else if (c === "") { if (currentDescriptor) { descriptors.push(currentDescriptor); } parseDescriptors(); return; // Anything else // Append c to current descriptor. } else { currentDescriptor = currentDescriptor + c; } // (end "in descriptor" // In parens } else if (state === "in parens") { // U+0029 RIGHT PARENTHESIS ()) // Append c to current descriptor. Set state to in descriptor. if (c === ")") { currentDescriptor = currentDescriptor + c; state = "in descriptor"; // EOF // Append current descriptor to descriptors. Jump to the step labeled // descriptor parser. } else if (c === "") { descriptors.push(currentDescriptor); parseDescriptors(); return; // Anything else // Append c to current descriptor. } else { currentDescriptor = currentDescriptor + c; } // After descriptor } else if (state === "after descriptor") { // Do the following, depending on the value of c: // Space character: Stay in this state. if (isSpace(c)) { // EOF: Jump to the step labeled descriptor parser. } else if (c === "") { parseDescriptors(); return; // Anything else // Set state to in descriptor. Set position to the previous character in input. } else { state = "in descriptor"; pos -= 1; } } // Advance position to the next character in input. pos += 1; // Repeat this step. } // (close while true loop) } // 4. Splitting loop: Collect a sequence of characters that are space // characters or U+002C COMMA characters. If any U+002C COMMA characters // were collected, that is a parse error. while (true) { collectCharacters(regexLeadingCommasOrSpaces); // 5. If position is past the end of input, return candidates and abort these steps. if (pos >= inputLength) { return candidates; // (we're done, this is the sole return path) } // 6. Collect a sequence of characters that are not space characters, // and let that be url. url = collectCharacters(regexLeadingNotSpaces); // 7. Let descriptors be a new empty list. descriptors = []; // 8. If url ends with a U+002C COMMA character (,), follow these substeps: // (1). Remove all trailing U+002C COMMA characters from url. If this removed // more than one character, that is a parse error. if (url.slice(-1) === ",") { url = url.replace(regexTrailingCommas, ""); // (Jump ahead to step 9 to skip tokenization and just push the candidate). parseDescriptors(); // Otherwise, follow these substeps: } else { tokenize(); } // (close else of step 8) // 16. Return to the step labeled splitting loop. } // (Close of big while loop.) } /* * Sizes Parser * * By Alex Bell | MIT License * * Non-strict but accurate and lightweight JS Parser for the string value * * Reference algorithm at: * https://html.spec.whatwg.org/multipage/embedded-content.html#parse-a-sizes-attribute * * Most comments are copied in directly from the spec * (except for comments in parens). * * Grammar is: * = # [ , ]? | * = * = * http://www.w3.org/html/wg/drafts/html/master/embedded-content.html#attr-img-sizes * * E.g. "(max-width: 30em) 100vw, (max-width: 50em) 70vw, 100vw" * or "(min-width: 30em), calc(30vw - 15px)" or just "30vw" * * Returns the first valid with a media condition that evaluates to true, * or "100vw" if all valid media conditions evaluate to false. * */ function parseSizes(strValue) { // (Percentage CSS lengths are not allowed in this case, to avoid confusion: // https://html.spec.whatwg.org/multipage/embedded-content.html#valid-source-size-list // CSS allows a single optional plus or minus sign: // http://www.w3.org/TR/CSS2/syndata.html#numbers // CSS is ASCII case-insensitive: // http://www.w3.org/TR/CSS2/syndata.html#characters ) // Spec allows exponential notation for type: // http://dev.w3.org/csswg/css-values/#numbers var regexCssLengthWithUnits = /^(?:[+-]?[0-9]+|[0-9]*\.[0-9]+)(?:[eE][+-]?[0-9]+)?(?:ch|cm|em|ex|in|mm|pc|pt|px|rem|vh|vmin|vmax|vw)$/i; // (This is a quick and lenient test. Because of optional unlimited-depth internal // grouping parens and strict spacing rules, this could get very complicated.) var regexCssCalc = /^calc\((?:[0-9a-z \.\+\-\*\/\(\)]+)\)$/i; var i; var unparsedSizesList; var unparsedSizesListLength; var unparsedSize; var lastComponentValue; var size; // UTILITY FUNCTIONS // (Toy CSS parser. The goals here are: // 1) expansive test coverage without the weight of a full CSS parser. // 2) Avoiding regex wherever convenient. // Quick tests: http://jsfiddle.net/gtntL4gr/3/ // Returns an array of arrays.) function parseComponentValues(str) { var chrctr; var component = ""; var componentArray = []; var listArray = []; var parenDepth = 0; var pos = 0; var inComment = false; function pushComponent() { if (component) { componentArray.push(component); component = ""; } } function pushComponentArray() { if (componentArray[0]) { listArray.push(componentArray); componentArray = []; } } // (Loop forwards from the beginning of the string.) while (true) { chrctr = str.charAt(pos); if (chrctr === "") { // ( End of string reached.) pushComponent(); pushComponentArray(); return listArray; } else if (inComment) { if ((chrctr === "*") && (str[pos + 1] === "/")) { // (At end of a comment.) inComment = false; pos += 2; pushComponent(); continue; } else { pos += 1; // (Skip all characters inside comments.) continue; } } else if (isSpace(chrctr)) { // (If previous character in loop was also a space, or if // at the beginning of the string, do not add space char to // component.) if ( (str.charAt(pos - 1) && isSpace( str.charAt(pos - 1) ) ) || !component ) { pos += 1; continue; } else if (parenDepth === 0) { pushComponent(); pos +=1; continue; } else { // (Replace any space character with a plain space for legibility.) chrctr = " "; } } else if (chrctr === "(") { parenDepth += 1; } else if (chrctr === ")") { parenDepth -= 1; } else if (chrctr === ",") { pushComponent(); pushComponentArray(); pos += 1; continue; } else if ( (chrctr === "/") && (str.charAt(pos + 1) === "*") ) { inComment = true; pos += 2; continue; } component = component + chrctr; pos += 1; } } function isValidNonNegativeSourceSizeValue(s) { if (regexCssLengthWithUnits.test(s) && (parseFloat(s) >= 0)) {return true;} if (regexCssCalc.test(s)) {return true;} // ( http://www.w3.org/TR/CSS2/syndata.html#numbers says: // "-0 is equivalent to 0 and is not a negative number." which means that // unitless zero and unitless negative zero must be accepted as special cases.) if ((s === "0") || (s === "-0") || (s === "+0")) {return true;} return false; } // When asked to parse a sizes attribute from an element, parse a // comma-separated list of component values from the value of the element's // sizes attribute (or the empty string, if the attribute is absent), and let // unparsed sizes list be the result. // http://dev.w3.org/csswg/css-syntax/#parse-comma-separated-list-of-component-values unparsedSizesList = parseComponentValues(strValue); unparsedSizesListLength = unparsedSizesList.length; // For each unparsed size in unparsed sizes list: for (i = 0; i < unparsedSizesListLength; i++) { unparsedSize = unparsedSizesList[i]; // 1. Remove all consecutive s from the end of unparsed size. // ( parseComponentValues() already omits spaces outside of parens. ) // If unparsed size is now empty, that is a parse error; continue to the next // iteration of this algorithm. // ( parseComponentValues() won't push an empty array. ) // 2. If the last component value in unparsed size is a valid non-negative // , let size be its value and remove the component value // from unparsed size. Any CSS function other than the calc() function is // invalid. Otherwise, there is a parse error; continue to the next iteration // of this algorithm. // http://dev.w3.org/csswg/css-syntax/#parse-component-value lastComponentValue = unparsedSize[unparsedSize.length - 1]; if (isValidNonNegativeSourceSizeValue(lastComponentValue)) { size = lastComponentValue; unparsedSize.pop(); } else { continue; } // 3. Remove all consecutive s from the end of unparsed // size. If unparsed size is now empty, return size and exit this algorithm. // If this was not the last item in unparsed sizes list, that is a parse error. if (unparsedSize.length === 0) { return size; } // 4. Parse the remaining component values in unparsed size as a // . If it does not parse correctly, or it does parse // correctly but the evaluates to false, continue to the // next iteration of this algorithm. // (Parsing all possible compound media conditions in JS is heavy, complicated, // and the payoff is unclear. Is there ever an situation where the // media condition parses incorrectly but still somehow evaluates to true? // Can we just rely on the browser/polyfill to do it?) unparsedSize = unparsedSize.join(" "); if (!(pf.matchesMedia( unparsedSize ) ) ) { continue; } // 5. Return size and exit this algorithm. return size; } // If the above algorithm exhausts unparsed sizes list without returning a // size value, return 100vw. return "100vw"; } // namespace pf.ns = ("pf" + new Date().getTime()).substr(0, 9); // srcset support test pf.supSrcset = "srcset" in image; pf.supSizes = "sizes" in image; pf.supPicture = !!window.HTMLPictureElement; // UC browser does claim to support srcset and picture, but not sizes, // this extended test reveals the browser does support nothing if (pf.supSrcset && pf.supPicture && !pf.supSizes) { (function(image2) { image.srcset = "data:,a"; image2.src = "data:,a"; pf.supSrcset = image.complete === image2.complete; pf.supPicture = pf.supSrcset && pf.supPicture; })(document.createElement("img")); } // Safari9 has basic support for sizes, but does't expose the `sizes` idl attribute if (pf.supSrcset && !pf.supSizes) { (function() { var width2 = "data:image/gif;base64,R0lGODlhAgABAPAAAP///wAAACH5BAAAAAAALAAAAAACAAEAAAICBAoAOw=="; var width1 = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; var img = document.createElement("img"); var test = function() { var width = img.width; if (width === 2) { pf.supSizes = true; } alwaysCheckWDescriptor = pf.supSrcset && !pf.supSizes; isSupportTestReady = true; // force async setTimeout(picturefill); }; img.onload = test; img.onerror = test; img.setAttribute("sizes", "9px"); img.srcset = width1 + " 1w," + width2 + " 9w"; img.src = width1; })(); } else { isSupportTestReady = true; } // using pf.qsa instead of dom traversing does scale much better, // especially on sites mixing responsive and non-responsive images pf.selShort = "picture>img,img[srcset]"; pf.sel = pf.selShort; pf.cfg = cfg; /** * Shortcut property for `devicePixelRatio` ( for easy overriding in tests ) */ pf.DPR = (DPR || 1 ); pf.u = units; // container of supported mime types that one might need to qualify before using pf.types = types; pf.setSize = noop; /** * Gets a string and returns the absolute URL * @param src * @returns {String} absolute URL */ pf.makeUrl = memoize(function(src) { anchor.href = src; return anchor.href; }); /** * Gets a DOM element or document and a selctor and returns the found matches * Can be extended with jQuery/Sizzle for IE7 support * @param context * @param sel * @returns {NodeList|Array} */ pf.qsa = function(context, sel) { return ( "querySelector" in context ) ? context.querySelectorAll(sel) : []; }; /** * Shortcut method for matchMedia ( for easy overriding in tests ) * wether native or pf.mMQ is used will be decided lazy on first call * @returns {boolean} */ pf.matchesMedia = function() { if ( window.matchMedia && (matchMedia( "(min-width: 0.1em)" ) || {}).matches ) { pf.matchesMedia = function( media ) { return !media || ( matchMedia( media ).matches ); }; } else { pf.matchesMedia = pf.mMQ; } return pf.matchesMedia.apply( this, arguments ); }; /** * A simplified matchMedia implementation for IE8 and IE9 * handles only min-width/max-width with px or em values * @param media * @returns {boolean} */ pf.mMQ = function( media ) { return media ? evalCSS(media) : true; }; /** * Returns the calculated length in css pixel from the given sourceSizeValue * http://dev.w3.org/csswg/css-values-3/#length-value * intended Spec mismatches: * * Does not check for invalid use of CSS functions * * Does handle a computed length of 0 the same as a negative and therefore invalid value * @param sourceSizeValue * @returns {Number} */ pf.calcLength = function( sourceSizeValue ) { var value = evalCSS(sourceSizeValue, true) || false; if (value < 0) { value = false; } return value; }; /** * Takes a type string and checks if its supported */ pf.supportsType = function( type ) { return ( type ) ? types[ type ] : true; }; /** * Parses a sourceSize into mediaCondition (media) and sourceSizeValue (length) * @param sourceSizeStr * @returns {*} */ pf.parseSize = memoize(function( sourceSizeStr ) { var match = ( sourceSizeStr || "" ).match(regSize); return { media: match && match[1], length: match && match[2] }; }); pf.parseSet = function( set ) { if ( !set.cands ) { set.cands = parseSrcset(set.srcset, set); } return set.cands; }; /** * returns 1em in css px for html/body default size * function taken from respondjs * @returns {*|number} */ pf.getEmValue = function() { var body; if ( !eminpx && (body = document.body) ) { var div = document.createElement( "div" ), originalHTMLCSS = docElem.style.cssText, originalBodyCSS = body.style.cssText; div.style.cssText = baseStyle; // 1em in a media query is the value of the default font size of the browser // reset docElem and body to ensure the correct value is returned docElem.style.cssText = fsCss; body.style.cssText = fsCss; body.appendChild( div ); eminpx = div.offsetWidth; body.removeChild( div ); //also update eminpx before returning eminpx = parseFloat( eminpx, 10 ); // restore the original values docElem.style.cssText = originalHTMLCSS; body.style.cssText = originalBodyCSS; } return eminpx || 16; }; /** * Takes a string of sizes and returns the width in pixels as a number */ pf.calcListLength = function( sourceSizeListStr ) { // Split up source size list, ie ( max-width: 30em ) 100%, ( max-width: 50em ) 50%, 33% // // or (min-width:30em) calc(30% - 15px) if ( !(sourceSizeListStr in sizeLengthCache) || cfg.uT ) { var winningLength = pf.calcLength( parseSizes( sourceSizeListStr ) ); sizeLengthCache[ sourceSizeListStr ] = !winningLength ? units.width : winningLength; } return sizeLengthCache[ sourceSizeListStr ]; }; /** * Takes a candidate object with a srcset property in the form of url/ * ex. "images/pic-medium.png 1x, images/pic-medium-2x.png 2x" or * "images/pic-medium.png 400w, images/pic-medium-2x.png 800w" or * "images/pic-small.png" * Get an array of image candidates in the form of * {url: "/foo/bar.png", resolution: 1} * where resolution is http://dev.w3.org/csswg/css-values-3/#resolution-value * If sizes is specified, res is calculated */ pf.setRes = function( set ) { var candidates; if ( set ) { candidates = pf.parseSet( set ); for ( var i = 0, len = candidates.length; i < len; i++ ) { setResolution( candidates[ i ], set.sizes ); } } return candidates; }; pf.setRes.res = setResolution; pf.applySetCandidate = function( candidates, img ) { if ( !candidates.length ) {return;} var candidate, i, j, length, bestCandidate, curSrc, curCan, candidateSrc, abortCurSrc; var imageData = img[ pf.ns ]; var dpr = pf.DPR; curSrc = imageData.curSrc || img[curSrcProp]; curCan = imageData.curCan || setSrcToCur(img, curSrc, candidates[0].set); // if we have a current source, we might either become lazy or give this source some advantage if ( curCan && curCan.set === candidates[ 0 ].set ) { // if browser can abort image request and the image has a higher pixel density than needed // and this image isn't downloaded yet, we skip next part and try to save bandwidth abortCurSrc = (supportAbort && !img.complete && curCan.res - 0.1 > dpr); if ( !abortCurSrc ) { curCan.cached = true; // if current candidate is "best", "better" or "okay", // set it to bestCandidate if ( curCan.res >= dpr ) { bestCandidate = curCan; } } } if ( !bestCandidate ) { candidates.sort( ascendingSort ); length = candidates.length; bestCandidate = candidates[ length - 1 ]; for ( i = 0; i < length; i++ ) { candidate = candidates[ i ]; if ( candidate.res >= dpr ) { j = i - 1; // we have found the perfect candidate, // but let's improve this a little bit with some assumptions ;-) if (candidates[ j ] && (abortCurSrc || curSrc !== pf.makeUrl( candidate.url )) && chooseLowRes(candidates[ j ].res, candidate.res, dpr, candidates[ j ].cached)) { bestCandidate = candidates[ j ]; } else { bestCandidate = candidate; } break; } } } if ( bestCandidate ) { candidateSrc = pf.makeUrl( bestCandidate.url ); imageData.curSrc = candidateSrc; imageData.curCan = bestCandidate; if ( candidateSrc !== curSrc ) { pf.setSrc( img, bestCandidate ); } pf.setSize( img ); } }; pf.setSrc = function( img, bestCandidate ) { var origWidth; img.src = bestCandidate.url; // although this is a specific Safari issue, we don't want to take too much different code paths if ( bestCandidate.set.type === "image/svg+xml" ) { origWidth = img.style.width; img.style.width = (img.offsetWidth + 1) + "px"; // next line only should trigger a repaint // if... is only done to trick dead code removal if ( img.offsetWidth + 1 ) { img.style.width = origWidth; } } }; pf.getSet = function( img ) { var i, set, supportsType; var match = false; var sets = img [ pf.ns ].sets; for ( i = 0; i < sets.length && !match; i++ ) { set = sets[i]; if ( !set.srcset || !pf.matchesMedia( set.media ) || !(supportsType = pf.supportsType( set.type )) ) { continue; } if ( supportsType === "pending" ) { set = supportsType; } match = set; break; } return match; }; pf.parseSets = function( element, parent, options ) { var srcsetAttribute, imageSet, isWDescripor, srcsetParsed; var hasPicture = parent && parent.nodeName.toUpperCase() === "PICTURE"; var imageData = element[ pf.ns ]; if ( imageData.src === undefined || options.src ) { imageData.src = getImgAttr.call( element, "src" ); if ( imageData.src ) { setImgAttr.call( element, srcAttr, imageData.src ); } else { removeImgAttr.call( element, srcAttr ); } } if ( imageData.srcset === undefined || options.srcset || !pf.supSrcset || element.srcset ) { srcsetAttribute = getImgAttr.call( element, "srcset" ); imageData.srcset = srcsetAttribute; srcsetParsed = true; } imageData.sets = []; if ( hasPicture ) { imageData.pic = true; getAllSourceElements( parent, imageData.sets ); } if ( imageData.srcset ) { imageSet = { srcset: imageData.srcset, sizes: getImgAttr.call( element, "sizes" ) }; imageData.sets.push( imageSet ); isWDescripor = (alwaysCheckWDescriptor || imageData.src) && regWDesc.test(imageData.srcset || ""); // add normal src as candidate, if source has no w descriptor if ( !isWDescripor && imageData.src && !getCandidateForSrc(imageData.src, imageSet) && !imageSet.has1x ) { imageSet.srcset += ", " + imageData.src; imageSet.cands.push({ url: imageData.src, d: 1, set: imageSet }); } } else if ( imageData.src ) { imageData.sets.push( { srcset: imageData.src, sizes: null } ); } imageData.curCan = null; imageData.curSrc = undefined; // if img has picture or the srcset was removed or has a srcset and does not support srcset at all // or has a w descriptor (and does not support sizes) set support to false to evaluate imageData.supported = !( hasPicture || ( imageSet && !pf.supSrcset ) || (isWDescripor && !pf.supSizes) ); if ( srcsetParsed && pf.supSrcset && !imageData.supported ) { if ( srcsetAttribute ) { setImgAttr.call( element, srcsetAttr, srcsetAttribute ); element.srcset = ""; } else { removeImgAttr.call( element, srcsetAttr ); } } if (imageData.supported && !imageData.srcset && ((!imageData.src && element.src) || element.src !== pf.makeUrl(imageData.src))) { if (imageData.src === null) { element.removeAttribute("src"); } else { element.src = imageData.src; } } imageData.parsed = true; }; pf.fillImg = function(element, options) { var imageData; var extreme = options.reselect || options.reevaluate; // expando for caching data on the img if ( !element[ pf.ns ] ) { element[ pf.ns ] = {}; } imageData = element[ pf.ns ]; // if the element has already been evaluated, skip it // unless `options.reevaluate` is set to true ( this, for example, // is set to true when running `picturefill` on `resize` ). if ( !extreme && imageData.evaled === evalId ) { return; } if ( !imageData.parsed || options.reevaluate ) { pf.parseSets( element, element.parentNode, options ); } if ( !imageData.supported ) { applyBestCandidate( element ); } else { imageData.evaled = evalId; } }; pf.setupRun = function() { if ( !alreadyRun || isVwDirty || (DPR !== window.devicePixelRatio) ) { updateMetrics(); } }; // If picture is supported, well, that's awesome. if ( pf.supPicture ) { picturefill = noop; pf.fillImg = noop; } else { // Set up picture polyfill by polling the document (function() { var isDomReady; var regReady = window.attachEvent ? /d$|^c/ : /d$|^c|^i/; var run = function() { var readyState = document.readyState || ""; timerId = setTimeout(run, readyState === "loading" ? 200 : 999); if ( document.body ) { pf.fillImgs(); isDomReady = isDomReady || regReady.test(readyState); if ( isDomReady ) { clearTimeout( timerId ); } } }; var timerId = setTimeout(run, document.body ? 9 : 99); // Also attach picturefill on resize and readystatechange // http://modernjavascript.blogspot.com/2013/08/building-better-debounce.html var debounce = function(func, wait) { var timeout, timestamp; var later = function() { var last = (new Date()) - timestamp; if (last < wait) { timeout = setTimeout(later, wait - last); } else { timeout = null; func(); } }; return function() { timestamp = new Date(); if (!timeout) { timeout = setTimeout(later, wait); } }; }; var lastClientWidth = docElem.clientHeight; var onResize = function() { isVwDirty = Math.max(window.innerWidth || 0, docElem.clientWidth) !== units.width || docElem.clientHeight !== lastClientWidth; lastClientWidth = docElem.clientHeight; if ( isVwDirty ) { pf.fillImgs(); } }; on( window, "resize", debounce(onResize, 99 ) ); on( document, "readystatechange", run ); })(); } pf.picturefill = picturefill; //use this internally for easy monkey patching/performance testing pf.fillImgs = picturefill; pf.teardownRun = noop; /* expose methods for testing */ picturefill._ = pf; window.picturefillCFG = { pf: pf, push: function(args) { var name = args.shift(); if (typeof pf[name] === "function") { pf[name].apply(pf, args); } else { cfg[name] = args[0]; if (alreadyRun) { pf.fillImgs( { reselect: true } ); } } } }; while (setOptions && setOptions.length) { window.picturefillCFG.push(setOptions.shift()); } /* expose picturefill */ window.picturefill = picturefill; /* expose picturefill */ if ( typeof module === "object" && typeof module.exports === "object" ) { // CommonJS, just export module.exports = picturefill; } else if ( typeof define === "function" && define.amd ) { // AMD support define( "picturefill", function() { return picturefill; } ); } // IE8 evals this sync, so it must be the last thing we do if ( !pf.supPicture ) { types[ "image/webp" ] = detectTypeSupport("image/webp", "data:image/webp;base64,UklGRkoAAABXRUJQVlA4WAoAAAAQAAAAAAAAAAAAQUxQSAwAAAABBxAR/Q9ERP8DAABWUDggGAAAADABAJ0BKgEAAQADADQlpAADcAD++/1QAA==" ); } } )( window, document ); /*! Hammer.JS - v2.0.7 - 2016-04-22 * http://hammerjs.github.io/ * * Copyright (c) 2016 Jorik Tangelder; * Licensed under the MIT license */ (function(window, document, exportName, undefined) { 'use strict'; var VENDOR_PREFIXES = ['', 'webkit', 'Moz', 'MS', 'ms', 'o']; var TEST_ELEMENT = document.createElement('div'); var TYPE_FUNCTION = 'function'; var round = Math.round; var abs = Math.abs; var now = Date.now; /** * set a timeout with a given scope * @param {Function} fn * @param {Number} timeout * @param {Object} context * @returns {number} */ function setTimeoutContext(fn, timeout, context) { return setTimeout(bindFn(fn, context), timeout); } /** * if the argument is an array, we want to execute the fn on each entry * if it aint an array we don't want to do a thing. * this is used by all the methods that accept a single and array argument. * @param {*|Array} arg * @param {String} fn * @param {Object} [context] * @returns {Boolean} */ function invokeArrayArg(arg, fn, context) { if (Array.isArray(arg)) { each(arg, context[fn], context); return true; } return false; } /** * walk objects and arrays * @param {Object} obj * @param {Function} iterator * @param {Object} context */ function each(obj, iterator, context) { var i; if (!obj) { return; } if (obj.forEach) { obj.forEach(iterator, context); } else if (obj.length !== undefined) { i = 0; while (i < obj.length) { iterator.call(context, obj[i], i, obj); i++; } } else { for (i in obj) { obj.hasOwnProperty(i) && iterator.call(context, obj[i], i, obj); } } } /** * wrap a method with a deprecation warning and stack trace * @param {Function} method * @param {String} name * @param {String} message * @returns {Function} A new function wrapping the supplied method. */ function deprecate(method, name, message) { var deprecationMessage = 'DEPRECATED METHOD: ' + name + '\n' + message + ' AT \n'; return function() { var e = new Error('get-stack-trace'); var stack = e && e.stack ? e.stack.replace(/^[^\(]+?[\n$]/gm, '') .replace(/^\s+at\s+/gm, '') .replace(/^Object.\s*\(/gm, '{anonymous}()@') : 'Unknown Stack Trace'; var log = window.console && (window.console.warn || window.console.log); if (log) { log.call(window.console, deprecationMessage, stack); } return method.apply(this, arguments); }; } /** * extend object. * means that properties in dest will be overwritten by the ones in src. * @param {Object} target * @param {...Object} objects_to_assign * @returns {Object} target */ var assign; if (typeof Object.assign !== 'function') { assign = function assign(target) { if (target === undefined || target === null) { throw new TypeError('Cannot convert undefined or null to object'); } var output = Object(target); for (var index = 1; index < arguments.length; index++) { var source = arguments[index]; if (source !== undefined && source !== null) { for (var nextKey in source) { if (source.hasOwnProperty(nextKey)) { output[nextKey] = source[nextKey]; } } } } return output; }; } else { assign = Object.assign; } /** * extend object. * means that properties in dest will be overwritten by the ones in src. * @param {Object} dest * @param {Object} src * @param {Boolean} [merge=false] * @returns {Object} dest */ var extend = deprecate(function extend(dest, src, merge) { var keys = Object.keys(src); var i = 0; while (i < keys.length) { if (!merge || (merge && dest[keys[i]] === undefined)) { dest[keys[i]] = src[keys[i]]; } i++; } return dest; }, 'extend', 'Use `assign`.'); /** * merge the values from src in the dest. * means that properties that exist in dest will not be overwritten by src * @param {Object} dest * @param {Object} src * @returns {Object} dest */ var merge = deprecate(function merge(dest, src) { return extend(dest, src, true); }, 'merge', 'Use `assign`.'); /** * simple class inheritance * @param {Function} child * @param {Function} base * @param {Object} [properties] */ function inherit(child, base, properties) { var baseP = base.prototype, childP; childP = child.prototype = Object.create(baseP); childP.constructor = child; childP._super = baseP; if (properties) { assign(childP, properties); } } /** * simple function bind * @param {Function} fn * @param {Object} context * @returns {Function} */ function bindFn(fn, context) { return function boundFn() { return fn.apply(context, arguments); }; } /** * let a boolean value also be a function that must return a boolean * this first item in args will be used as the context * @param {Boolean|Function} val * @param {Array} [args] * @returns {Boolean} */ function boolOrFn(val, args) { if (typeof val == TYPE_FUNCTION) { return val.apply(args ? args[0] || undefined : undefined, args); } return val; } /** * use the val2 when val1 is undefined * @param {*} val1 * @param {*} val2 * @returns {*} */ function ifUndefined(val1, val2) { return (val1 === undefined) ? val2 : val1; } /** * addEventListener with multiple events at once * @param {EventTarget} target * @param {String} types * @param {Function} handler */ function addEventListeners(target, types, handler) { each(splitStr(types), function(type) { target.addEventListener(type, handler, false); }); } /** * removeEventListener with multiple events at once * @param {EventTarget} target * @param {String} types * @param {Function} handler */ function removeEventListeners(target, types, handler) { each(splitStr(types), function(type) { target.removeEventListener(type, handler, false); }); } /** * find if a node is in the given parent * @method hasParent * @param {HTMLElement} node * @param {HTMLElement} parent * @return {Boolean} found */ function hasParent(node, parent) { while (node) { if (node == parent) { return true; } node = node.parentNode; } return false; } /** * small indexOf wrapper * @param {String} str * @param {String} find * @returns {Boolean} found */ function inStr(str, find) { return str.indexOf(find) > -1; } /** * split string on whitespace * @param {String} str * @returns {Array} words */ function splitStr(str) { return str.trim().split(/\s+/g); } /** * find if a array contains the object using indexOf or a simple polyFill * @param {Array} src * @param {String} find * @param {String} [findByKey] * @return {Boolean|Number} false when not found, or the index */ function inArray(src, find, findByKey) { if (src.indexOf && !findByKey) { return src.indexOf(find); } else { var i = 0; while (i < src.length) { if ((findByKey && src[i][findByKey] == find) || (!findByKey && src[i] === find)) { return i; } i++; } return -1; } } /** * convert array-like objects to real arrays * @param {Object} obj * @returns {Array} */ function toArray(obj) { return Array.prototype.slice.call(obj, 0); } /** * unique array with objects based on a key (like 'id') or just by the array's value * @param {Array} src [{id:1},{id:2},{id:1}] * @param {String} [key] * @param {Boolean} [sort=False] * @returns {Array} [{id:1},{id:2}] */ function uniqueArray(src, key, sort) { var results = []; var values = []; var i = 0; while (i < src.length) { var val = key ? src[i][key] : src[i]; if (inArray(values, val) < 0) { results.push(src[i]); } values[i] = val; i++; } if (sort) { if (!key) { results = results.sort(); } else { results = results.sort(function sortUniqueArray(a, b) { return a[key] > b[key]; }); } } return results; } /** * get the prefixed property * @param {Object} obj * @param {String} property * @returns {String|Undefined} prefixed */ function prefixed(obj, property) { var prefix, prop; var camelProp = property[0].toUpperCase() + property.slice(1); var i = 0; while (i < VENDOR_PREFIXES.length) { prefix = VENDOR_PREFIXES[i]; prop = (prefix) ? prefix + camelProp : property; if (prop in obj) { return prop; } i++; } return undefined; } /** * get a unique id * @returns {number} uniqueId */ var _uniqueId = 1; function uniqueId() { return _uniqueId++; } /** * get the window object of an element * @param {HTMLElement} element * @returns {DocumentView|Window} */ function getWindowForElement(element) { var doc = element.ownerDocument || element; return (doc.defaultView || doc.parentWindow || window); } var MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i; var SUPPORT_TOUCH = ('ontouchstart' in window); var SUPPORT_POINTER_EVENTS = prefixed(window, 'PointerEvent') !== undefined; var SUPPORT_ONLY_TOUCH = SUPPORT_TOUCH && MOBILE_REGEX.test(navigator.userAgent); var INPUT_TYPE_TOUCH = 'touch'; var INPUT_TYPE_PEN = 'pen'; var INPUT_TYPE_MOUSE = 'mouse'; var INPUT_TYPE_KINECT = 'kinect'; var COMPUTE_INTERVAL = 25; var INPUT_START = 1; var INPUT_MOVE = 2; var INPUT_END = 4; var INPUT_CANCEL = 8; var DIRECTION_NONE = 1; var DIRECTION_LEFT = 2; var DIRECTION_RIGHT = 4; var DIRECTION_UP = 8; var DIRECTION_DOWN = 16; var DIRECTION_HORIZONTAL = DIRECTION_LEFT | DIRECTION_RIGHT; var DIRECTION_VERTICAL = DIRECTION_UP | DIRECTION_DOWN; var DIRECTION_ALL = DIRECTION_HORIZONTAL | DIRECTION_VERTICAL; var PROPS_XY = ['x', 'y']; var PROPS_CLIENT_XY = ['clientX', 'clientY']; /** * create new input type manager * @param {Manager} manager * @param {Function} callback * @returns {Input} * @constructor */ function Input(manager, callback) { var self = this; this.manager = manager; this.callback = callback; this.element = manager.element; this.target = manager.options.inputTarget; // smaller wrapper around the handler, for the scope and the enabled state of the manager, // so when disabled the input events are completely bypassed. this.domHandler = function(ev) { if (boolOrFn(manager.options.enable, [manager])) { self.handler(ev); } }; this.init(); } Input.prototype = { /** * should handle the inputEvent data and trigger the callback * @virtual */ handler: function() { }, /** * bind the events */ init: function() { this.evEl && addEventListeners(this.element, this.evEl, this.domHandler); this.evTarget && addEventListeners(this.target, this.evTarget, this.domHandler); this.evWin && addEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler); }, /** * unbind the events */ destroy: function() { this.evEl && removeEventListeners(this.element, this.evEl, this.domHandler); this.evTarget && removeEventListeners(this.target, this.evTarget, this.domHandler); this.evWin && removeEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler); } }; /** * create new input type manager * called by the Manager constructor * @param {Hammer} manager * @returns {Input} */ function createInputInstance(manager) { var Type; var inputClass = manager.options.inputClass; if (inputClass) { Type = inputClass; } else if (SUPPORT_POINTER_EVENTS) { Type = PointerEventInput; } else if (SUPPORT_ONLY_TOUCH) { Type = TouchInput; } else if (!SUPPORT_TOUCH) { Type = MouseInput; } else { Type = TouchMouseInput; } return new (Type)(manager, inputHandler); } /** * handle input events * @param {Manager} manager * @param {String} eventType * @param {Object} input */ function inputHandler(manager, eventType, input) { var pointersLen = input.pointers.length; var changedPointersLen = input.changedPointers.length; var isFirst = (eventType & INPUT_START && (pointersLen - changedPointersLen === 0)); var isFinal = (eventType & (INPUT_END | INPUT_CANCEL) && (pointersLen - changedPointersLen === 0)); input.isFirst = !!isFirst; input.isFinal = !!isFinal; if (isFirst) { manager.session = {}; } // source event is the normalized value of the domEvents // like 'touchstart, mouseup, pointerdown' input.eventType = eventType; // compute scale, rotation etc computeInputData(manager, input); // emit secret event manager.emit('hammer.input', input); manager.recognize(input); manager.session.prevInput = input; } /** * extend the data with some usable properties like scale, rotate, velocity etc * @param {Object} manager * @param {Object} input */ function computeInputData(manager, input) { var session = manager.session; var pointers = input.pointers; var pointersLength = pointers.length; // store the first input to calculate the distance and direction if (!session.firstInput) { session.firstInput = simpleCloneInputData(input); } // to compute scale and rotation we need to store the multiple touches if (pointersLength > 1 && !session.firstMultiple) { session.firstMultiple = simpleCloneInputData(input); } else if (pointersLength === 1) { session.firstMultiple = false; } var firstInput = session.firstInput; var firstMultiple = session.firstMultiple; var offsetCenter = firstMultiple ? firstMultiple.center : firstInput.center; var center = input.center = getCenter(pointers); input.timeStamp = now(); input.deltaTime = input.timeStamp - firstInput.timeStamp; input.angle = getAngle(offsetCenter, center); input.distance = getDistance(offsetCenter, center); computeDeltaXY(session, input); input.offsetDirection = getDirection(input.deltaX, input.deltaY); var overallVelocity = getVelocity(input.deltaTime, input.deltaX, input.deltaY); input.overallVelocityX = overallVelocity.x; input.overallVelocityY = overallVelocity.y; input.overallVelocity = (abs(overallVelocity.x) > abs(overallVelocity.y)) ? overallVelocity.x : overallVelocity.y; input.scale = firstMultiple ? getScale(firstMultiple.pointers, pointers) : 1; input.rotation = firstMultiple ? getRotation(firstMultiple.pointers, pointers) : 0; input.maxPointers = !session.prevInput ? input.pointers.length : ((input.pointers.length > session.prevInput.maxPointers) ? input.pointers.length : session.prevInput.maxPointers); computeIntervalInputData(session, input); // find the correct target var target = manager.element; if (hasParent(input.srcEvent.target, target)) { target = input.srcEvent.target; } input.target = target; } function computeDeltaXY(session, input) { var center = input.center; var offset = session.offsetDelta || {}; var prevDelta = session.prevDelta || {}; var prevInput = session.prevInput || {}; if (input.eventType === INPUT_START || prevInput.eventType === INPUT_END) { prevDelta = session.prevDelta = { x: prevInput.deltaX || 0, y: prevInput.deltaY || 0 }; offset = session.offsetDelta = { x: center.x, y: center.y }; } input.deltaX = prevDelta.x + (center.x - offset.x); input.deltaY = prevDelta.y + (center.y - offset.y); } /** * velocity is calculated every x ms * @param {Object} session * @param {Object} input */ function computeIntervalInputData(session, input) { var last = session.lastInterval || input, deltaTime = input.timeStamp - last.timeStamp, velocity, velocityX, velocityY, direction; if (input.eventType != INPUT_CANCEL && (deltaTime > COMPUTE_INTERVAL || last.velocity === undefined)) { var deltaX = input.deltaX - last.deltaX; var deltaY = input.deltaY - last.deltaY; var v = getVelocity(deltaTime, deltaX, deltaY); velocityX = v.x; velocityY = v.y; velocity = (abs(v.x) > abs(v.y)) ? v.x : v.y; direction = getDirection(deltaX, deltaY); session.lastInterval = input; } else { // use latest velocity info if it doesn't overtake a minimum period velocity = last.velocity; velocityX = last.velocityX; velocityY = last.velocityY; direction = last.direction; } input.velocity = velocity; input.velocityX = velocityX; input.velocityY = velocityY; input.direction = direction; } /** * create a simple clone from the input used for storage of firstInput and firstMultiple * @param {Object} input * @returns {Object} clonedInputData */ function simpleCloneInputData(input) { // make a simple copy of the pointers because we will get a reference if we don't // we only need clientXY for the calculations var pointers = []; var i = 0; while (i < input.pointers.length) { pointers[i] = { clientX: round(input.pointers[i].clientX), clientY: round(input.pointers[i].clientY) }; i++; } return { timeStamp: now(), pointers: pointers, center: getCenter(pointers), deltaX: input.deltaX, deltaY: input.deltaY }; } /** * get the center of all the pointers * @param {Array} pointers * @return {Object} center contains `x` and `y` properties */ function getCenter(pointers) { var pointersLength = pointers.length; // no need to loop when only one touch if (pointersLength === 1) { return { x: round(pointers[0].clientX), y: round(pointers[0].clientY) }; } var x = 0, y = 0, i = 0; while (i < pointersLength) { x += pointers[i].clientX; y += pointers[i].clientY; i++; } return { x: round(x / pointersLength), y: round(y / pointersLength) }; } /** * calculate the velocity between two points. unit is in px per ms. * @param {Number} deltaTime * @param {Number} x * @param {Number} y * @return {Object} velocity `x` and `y` */ function getVelocity(deltaTime, x, y) { return { x: x / deltaTime || 0, y: y / deltaTime || 0 }; } /** * get the direction between two points * @param {Number} x * @param {Number} y * @return {Number} direction */ function getDirection(x, y) { if (x === y) { return DIRECTION_NONE; } if (abs(x) >= abs(y)) { return x < 0 ? DIRECTION_LEFT : DIRECTION_RIGHT; } return y < 0 ? DIRECTION_UP : DIRECTION_DOWN; } /** * calculate the absolute distance between two points * @param {Object} p1 {x, y} * @param {Object} p2 {x, y} * @param {Array} [props] containing x and y keys * @return {Number} distance */ function getDistance(p1, p2, props) { if (!props) { props = PROPS_XY; } var x = p2[props[0]] - p1[props[0]], y = p2[props[1]] - p1[props[1]]; return Math.sqrt((x * x) + (y * y)); } /** * calculate the angle between two coordinates * @param {Object} p1 * @param {Object} p2 * @param {Array} [props] containing x and y keys * @return {Number} angle */ function getAngle(p1, p2, props) { if (!props) { props = PROPS_XY; } var x = p2[props[0]] - p1[props[0]], y = p2[props[1]] - p1[props[1]]; return Math.atan2(y, x) * 180 / Math.PI; } /** * calculate the rotation degrees between two pointersets * @param {Array} start array of pointers * @param {Array} end array of pointers * @return {Number} rotation */ function getRotation(start, end) { return getAngle(end[1], end[0], PROPS_CLIENT_XY) + getAngle(start[1], start[0], PROPS_CLIENT_XY); } /** * calculate the scale factor between two pointersets * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out * @param {Array} start array of pointers * @param {Array} end array of pointers * @return {Number} scale */ function getScale(start, end) { return getDistance(end[0], end[1], PROPS_CLIENT_XY) / getDistance(start[0], start[1], PROPS_CLIENT_XY); } var MOUSE_INPUT_MAP = { mousedown: INPUT_START, mousemove: INPUT_MOVE, mouseup: INPUT_END }; var MOUSE_ELEMENT_EVENTS = 'mousedown'; var MOUSE_WINDOW_EVENTS = 'mousemove mouseup'; /** * Mouse events input * @constructor * @extends Input */ function MouseInput() { this.evEl = MOUSE_ELEMENT_EVENTS; this.evWin = MOUSE_WINDOW_EVENTS; this.pressed = false; // mousedown state Input.apply(this, arguments); } inherit(MouseInput, Input, { /** * handle mouse events * @param {Object} ev */ handler: function MEhandler(ev) { var eventType = MOUSE_INPUT_MAP[ev.type]; // on start we want to have the left mouse button down if (eventType & INPUT_START && ev.button === 0) { this.pressed = true; } if (eventType & INPUT_MOVE && ev.which !== 1) { eventType = INPUT_END; } // mouse must be down if (!this.pressed) { return; } if (eventType & INPUT_END) { this.pressed = false; } this.callback(this.manager, eventType, { pointers: [ev], changedPointers: [ev], pointerType: INPUT_TYPE_MOUSE, srcEvent: ev }); } }); var POINTER_INPUT_MAP = { pointerdown: INPUT_START, pointermove: INPUT_MOVE, pointerup: INPUT_END, pointercancel: INPUT_CANCEL, pointerout: INPUT_CANCEL }; // in IE10 the pointer types is defined as an enum var IE10_POINTER_TYPE_ENUM = { 2: INPUT_TYPE_TOUCH, 3: INPUT_TYPE_PEN, 4: INPUT_TYPE_MOUSE, 5: INPUT_TYPE_KINECT // see https://twitter.com/jacobrossi/status/480596438489890816 }; var POINTER_ELEMENT_EVENTS = 'pointerdown'; var POINTER_WINDOW_EVENTS = 'pointermove pointerup pointercancel'; // IE10 has prefixed support, and case-sensitive if (window.MSPointerEvent && !window.PointerEvent) { POINTER_ELEMENT_EVENTS = 'MSPointerDown'; POINTER_WINDOW_EVENTS = 'MSPointerMove MSPointerUp MSPointerCancel'; } /** * Pointer events input * @constructor * @extends Input */ function PointerEventInput() { this.evEl = POINTER_ELEMENT_EVENTS; this.evWin = POINTER_WINDOW_EVENTS; Input.apply(this, arguments); this.store = (this.manager.session.pointerEvents = []); } inherit(PointerEventInput, Input, { /** * handle mouse events * @param {Object} ev */ handler: function PEhandler(ev) { var store = this.store; var removePointer = false; var eventTypeNormalized = ev.type.toLowerCase().replace('ms', ''); var eventType = POINTER_INPUT_MAP[eventTypeNormalized]; var pointerType = IE10_POINTER_TYPE_ENUM[ev.pointerType] || ev.pointerType; var isTouch = (pointerType == INPUT_TYPE_TOUCH); // get index of the event in the store var storeIndex = inArray(store, ev.pointerId, 'pointerId'); // start and mouse must be down if (eventType & INPUT_START && (ev.button === 0 || isTouch)) { if (storeIndex < 0) { store.push(ev); storeIndex = store.length - 1; } } else if (eventType & (INPUT_END | INPUT_CANCEL)) { removePointer = true; } // it not found, so the pointer hasn't been down (so it's probably a hover) if (storeIndex < 0) { return; } // update the event in the store store[storeIndex] = ev; this.callback(this.manager, eventType, { pointers: store, changedPointers: [ev], pointerType: pointerType, srcEvent: ev }); if (removePointer) { // remove from the store store.splice(storeIndex, 1); } } }); var SINGLE_TOUCH_INPUT_MAP = { touchstart: INPUT_START, touchmove: INPUT_MOVE, touchend: INPUT_END, touchcancel: INPUT_CANCEL }; var SINGLE_TOUCH_TARGET_EVENTS = 'touchstart'; var SINGLE_TOUCH_WINDOW_EVENTS = 'touchstart touchmove touchend touchcancel'; /** * Touch events input * @constructor * @extends Input */ function SingleTouchInput() { this.evTarget = SINGLE_TOUCH_TARGET_EVENTS; this.evWin = SINGLE_TOUCH_WINDOW_EVENTS; this.started = false; Input.apply(this, arguments); } inherit(SingleTouchInput, Input, { handler: function TEhandler(ev) { var type = SINGLE_TOUCH_INPUT_MAP[ev.type]; // should we handle the touch events? if (type === INPUT_START) { this.started = true; } if (!this.started) { return; } var touches = normalizeSingleTouches.call(this, ev, type); // when done, reset the started state if (type & (INPUT_END | INPUT_CANCEL) && touches[0].length - touches[1].length === 0) { this.started = false; } this.callback(this.manager, type, { pointers: touches[0], changedPointers: touches[1], pointerType: INPUT_TYPE_TOUCH, srcEvent: ev }); } }); /** * @this {TouchInput} * @param {Object} ev * @param {Number} type flag * @returns {undefined|Array} [all, changed] */ function normalizeSingleTouches(ev, type) { var all = toArray(ev.touches); var changed = toArray(ev.changedTouches); if (type & (INPUT_END | INPUT_CANCEL)) { all = uniqueArray(all.concat(changed), 'identifier', true); } return [all, changed]; } var TOUCH_INPUT_MAP = { touchstart: INPUT_START, touchmove: INPUT_MOVE, touchend: INPUT_END, touchcancel: INPUT_CANCEL }; var TOUCH_TARGET_EVENTS = 'touchstart touchmove touchend touchcancel'; /** * Multi-user touch events input * @constructor * @extends Input */ function TouchInput() { this.evTarget = TOUCH_TARGET_EVENTS; this.targetIds = {}; Input.apply(this, arguments); } inherit(TouchInput, Input, { handler: function MTEhandler(ev) { var type = TOUCH_INPUT_MAP[ev.type]; var touches = getTouches.call(this, ev, type); if (!touches) { return; } this.callback(this.manager, type, { pointers: touches[0], changedPointers: touches[1], pointerType: INPUT_TYPE_TOUCH, srcEvent: ev }); } }); /** * @this {TouchInput} * @param {Object} ev * @param {Number} type flag * @returns {undefined|Array} [all, changed] */ function getTouches(ev, type) { var allTouches = toArray(ev.touches); var targetIds = this.targetIds; // when there is only one touch, the process can be simplified if (type & (INPUT_START | INPUT_MOVE) && allTouches.length === 1) { targetIds[allTouches[0].identifier] = true; return [allTouches, allTouches]; } var i, targetTouches, changedTouches = toArray(ev.changedTouches), changedTargetTouches = [], target = this.target; // get target touches from touches targetTouches = allTouches.filter(function(touch) { return hasParent(touch.target, target); }); // collect touches if (type === INPUT_START) { i = 0; while (i < targetTouches.length) { targetIds[targetTouches[i].identifier] = true; i++; } } // filter changed touches to only contain touches that exist in the collected target ids i = 0; while (i < changedTouches.length) { if (targetIds[changedTouches[i].identifier]) { changedTargetTouches.push(changedTouches[i]); } // cleanup removed touches if (type & (INPUT_END | INPUT_CANCEL)) { delete targetIds[changedTouches[i].identifier]; } i++; } if (!changedTargetTouches.length) { return; } return [ // merge targetTouches with changedTargetTouches so it contains ALL touches, including 'end' and 'cancel' uniqueArray(targetTouches.concat(changedTargetTouches), 'identifier', true), changedTargetTouches ]; } /** * Combined touch and mouse input * * Touch has a higher priority then mouse, and while touching no mouse events are allowed. * This because touch devices also emit mouse events while doing a touch. * * @constructor * @extends Input */ var DEDUP_TIMEOUT = 2500; var DEDUP_DISTANCE = 25; function TouchMouseInput() { Input.apply(this, arguments); var handler = bindFn(this.handler, this); this.touch = new TouchInput(this.manager, handler); this.mouse = new MouseInput(this.manager, handler); this.primaryTouch = null; this.lastTouches = []; } inherit(TouchMouseInput, Input, { /** * handle mouse and touch events * @param {Hammer} manager * @param {String} inputEvent * @param {Object} inputData */ handler: function TMEhandler(manager, inputEvent, inputData) { var isTouch = (inputData.pointerType == INPUT_TYPE_TOUCH), isMouse = (inputData.pointerType == INPUT_TYPE_MOUSE); if (isMouse && inputData.sourceCapabilities && inputData.sourceCapabilities.firesTouchEvents) { return; } // when we're in a touch event, record touches to de-dupe synthetic mouse event if (isTouch) { recordTouches.call(this, inputEvent, inputData); } else if (isMouse && isSyntheticEvent.call(this, inputData)) { return; } this.callback(manager, inputEvent, inputData); }, /** * remove the event listeners */ destroy: function destroy() { this.touch.destroy(); this.mouse.destroy(); } }); function recordTouches(eventType, eventData) { if (eventType & INPUT_START) { this.primaryTouch = eventData.changedPointers[0].identifier; setLastTouch.call(this, eventData); } else if (eventType & (INPUT_END | INPUT_CANCEL)) { setLastTouch.call(this, eventData); } } function setLastTouch(eventData) { var touch = eventData.changedPointers[0]; if (touch.identifier === this.primaryTouch) { var lastTouch = {x: touch.clientX, y: touch.clientY}; this.lastTouches.push(lastTouch); var lts = this.lastTouches; var removeLastTouch = function() { var i = lts.indexOf(lastTouch); if (i > -1) { lts.splice(i, 1); } }; setTimeout(removeLastTouch, DEDUP_TIMEOUT); } } function isSyntheticEvent(eventData) { var x = eventData.srcEvent.clientX, y = eventData.srcEvent.clientY; for (var i = 0; i < this.lastTouches.length; i++) { var t = this.lastTouches[i]; var dx = Math.abs(x - t.x), dy = Math.abs(y - t.y); if (dx <= DEDUP_DISTANCE && dy <= DEDUP_DISTANCE) { return true; } } return false; } var PREFIXED_TOUCH_ACTION = prefixed(TEST_ELEMENT.style, 'touchAction'); var NATIVE_TOUCH_ACTION = PREFIXED_TOUCH_ACTION !== undefined; // magical touchAction value var TOUCH_ACTION_COMPUTE = 'compute'; var TOUCH_ACTION_AUTO = 'auto'; var TOUCH_ACTION_MANIPULATION = 'manipulation'; // not implemented var TOUCH_ACTION_NONE = 'none'; var TOUCH_ACTION_PAN_X = 'pan-x'; var TOUCH_ACTION_PAN_Y = 'pan-y'; var TOUCH_ACTION_MAP = getTouchActionProps(); /** * Touch Action * sets the touchAction property or uses the js alternative * @param {Manager} manager * @param {String} value * @constructor */ function TouchAction(manager, value) { this.manager = manager; this.set(value); } TouchAction.prototype = { /** * set the touchAction value on the element or enable the polyfill * @param {String} value */ set: function(value) { // find out the touch-action by the event handlers if (value == TOUCH_ACTION_COMPUTE) { value = this.compute(); } if (NATIVE_TOUCH_ACTION && this.manager.element.style && TOUCH_ACTION_MAP[value]) { this.manager.element.style[PREFIXED_TOUCH_ACTION] = value; } this.actions = value.toLowerCase().trim(); }, /** * just re-set the touchAction value */ update: function() { this.set(this.manager.options.touchAction); }, /** * compute the value for the touchAction property based on the recognizer's settings * @returns {String} value */ compute: function() { var actions = []; each(this.manager.recognizers, function(recognizer) { if (boolOrFn(recognizer.options.enable, [recognizer])) { actions = actions.concat(recognizer.getTouchAction()); } }); return cleanTouchActions(actions.join(' ')); }, /** * this method is called on each input cycle and provides the preventing of the browser behavior * @param {Object} input */ preventDefaults: function(input) { var srcEvent = input.srcEvent; var direction = input.offsetDirection; // if the touch action did prevented once this session if (this.manager.session.prevented) { srcEvent.preventDefault(); return; } var actions = this.actions; var hasNone = inStr(actions, TOUCH_ACTION_NONE) && !TOUCH_ACTION_MAP[TOUCH_ACTION_NONE]; var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y) && !TOUCH_ACTION_MAP[TOUCH_ACTION_PAN_Y]; var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X) && !TOUCH_ACTION_MAP[TOUCH_ACTION_PAN_X]; if (hasNone) { //do not prevent defaults if this is a tap gesture var isTapPointer = input.pointers.length === 1; var isTapMovement = input.distance < 2; var isTapTouchTime = input.deltaTime < 250; if (isTapPointer && isTapMovement && isTapTouchTime) { return; } } if (hasPanX && hasPanY) { // `pan-x pan-y` means browser handles all scrolling/panning, do not prevent return; } if (hasNone || (hasPanY && direction & DIRECTION_HORIZONTAL) || (hasPanX && direction & DIRECTION_VERTICAL)) { return this.preventSrc(srcEvent); } }, /** * call preventDefault to prevent the browser's default behavior (scrolling in most cases) * @param {Object} srcEvent */ preventSrc: function(srcEvent) { this.manager.session.prevented = true; srcEvent.preventDefault(); } }; /** * when the touchActions are collected they are not a valid value, so we need to clean things up. * * @param {String} actions * @returns {*} */ function cleanTouchActions(actions) { // none if (inStr(actions, TOUCH_ACTION_NONE)) { return TOUCH_ACTION_NONE; } var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X); var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y); // if both pan-x and pan-y are set (different recognizers // for different directions, e.g. horizontal pan but vertical swipe?) // we need none (as otherwise with pan-x pan-y combined none of these // recognizers will work, since the browser would handle all panning if (hasPanX && hasPanY) { return TOUCH_ACTION_NONE; } // pan-x OR pan-y if (hasPanX || hasPanY) { return hasPanX ? TOUCH_ACTION_PAN_X : TOUCH_ACTION_PAN_Y; } // manipulation if (inStr(actions, TOUCH_ACTION_MANIPULATION)) { return TOUCH_ACTION_MANIPULATION; } return TOUCH_ACTION_AUTO; } function getTouchActionProps() { if (!NATIVE_TOUCH_ACTION) { return false; } var touchMap = {}; var cssSupports = window.CSS && window.CSS.supports; ['auto', 'manipulation', 'pan-y', 'pan-x', 'pan-x pan-y', 'none'].forEach(function(val) { // If css.supports is not supported but there is native touch-action assume it supports // all values. This is the case for IE 10 and 11. touchMap[val] = cssSupports ? window.CSS.supports('touch-action', val) : true; }); return touchMap; } /** * Recognizer flow explained; * * All recognizers have the initial state of POSSIBLE when a input session starts. * The definition of a input session is from the first input until the last input, with all it's movement in it. * * Example session for mouse-input: mousedown -> mousemove -> mouseup * * On each recognizing cycle (see Manager.recognize) the .recognize() method is executed * which determines with state it should be. * * If the recognizer has the state FAILED, CANCELLED or RECOGNIZED (equals ENDED), it is reset to * POSSIBLE to give it another change on the next cycle. * * Possible * | * +-----+---------------+ * | | * +-----+-----+ | * | | | * Failed Cancelled | * +-------+------+ * | | * Recognized Began * | * Changed * | * Ended/Recognized */ var STATE_POSSIBLE = 1; var STATE_BEGAN = 2; var STATE_CHANGED = 4; var STATE_ENDED = 8; var STATE_RECOGNIZED = STATE_ENDED; var STATE_CANCELLED = 16; var STATE_FAILED = 32; /** * Recognizer * Every recognizer needs to extend from this class. * @constructor * @param {Object} options */ function Recognizer(options) { this.options = assign({}, this.defaults, options || {}); this.id = uniqueId(); this.manager = null; // default is enable true this.options.enable = ifUndefined(this.options.enable, true); this.state = STATE_POSSIBLE; this.simultaneous = {}; this.requireFail = []; } Recognizer.prototype = { /** * @virtual * @type {Object} */ defaults: {}, /** * set options * @param {Object} options * @return {Recognizer} */ set: function(options) { assign(this.options, options); // also update the touchAction, in case something changed about the directions/enabled state this.manager && this.manager.touchAction.update(); return this; }, /** * recognize simultaneous with an other recognizer. * @param {Recognizer} otherRecognizer * @returns {Recognizer} this */ recognizeWith: function(otherRecognizer) { if (invokeArrayArg(otherRecognizer, 'recognizeWith', this)) { return this; } var simultaneous = this.simultaneous; otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this); if (!simultaneous[otherRecognizer.id]) { simultaneous[otherRecognizer.id] = otherRecognizer; otherRecognizer.recognizeWith(this); } return this; }, /** * drop the simultaneous link. it doesnt remove the link on the other recognizer. * @param {Recognizer} otherRecognizer * @returns {Recognizer} this */ dropRecognizeWith: function(otherRecognizer) { if (invokeArrayArg(otherRecognizer, 'dropRecognizeWith', this)) { return this; } otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this); delete this.simultaneous[otherRecognizer.id]; return this; }, /** * recognizer can only run when an other is failing * @param {Recognizer} otherRecognizer * @returns {Recognizer} this */ requireFailure: function(otherRecognizer) { if (invokeArrayArg(otherRecognizer, 'requireFailure', this)) { return this; } var requireFail = this.requireFail; otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this); if (inArray(requireFail, otherRecognizer) === -1) { requireFail.push(otherRecognizer); otherRecognizer.requireFailure(this); } return this; }, /** * drop the requireFailure link. it does not remove the link on the other recognizer. * @param {Recognizer} otherRecognizer * @returns {Recognizer} this */ dropRequireFailure: function(otherRecognizer) { if (invokeArrayArg(otherRecognizer, 'dropRequireFailure', this)) { return this; } otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this); var index = inArray(this.requireFail, otherRecognizer); if (index > -1) { this.requireFail.splice(index, 1); } return this; }, /** * has require failures boolean * @returns {boolean} */ hasRequireFailures: function() { return this.requireFail.length > 0; }, /** * if the recognizer can recognize simultaneous with an other recognizer * @param {Recognizer} otherRecognizer * @returns {Boolean} */ canRecognizeWith: function(otherRecognizer) { return !!this.simultaneous[otherRecognizer.id]; }, /** * You should use `tryEmit` instead of `emit` directly to check * that all the needed recognizers has failed before emitting. * @param {Object} input */ emit: function(input) { var self = this; var state = this.state; function emit(event) { self.manager.emit(event, input); } // 'panstart' and 'panmove' if (state < STATE_ENDED) { emit(self.options.event + stateStr(state)); } emit(self.options.event); // simple 'eventName' events if (input.additionalEvent) { // additional event(panleft, panright, pinchin, pinchout...) emit(input.additionalEvent); } // panend and pancancel if (state >= STATE_ENDED) { emit(self.options.event + stateStr(state)); } }, /** * Check that all the require failure recognizers has failed, * if true, it emits a gesture event, * otherwise, setup the state to FAILED. * @param {Object} input */ tryEmit: function(input) { if (this.canEmit()) { return this.emit(input); } // it's failing anyway this.state = STATE_FAILED; }, /** * can we emit? * @returns {boolean} */ canEmit: function() { var i = 0; while (i < this.requireFail.length) { if (!(this.requireFail[i].state & (STATE_FAILED | STATE_POSSIBLE))) { return false; } i++; } return true; }, /** * update the recognizer * @param {Object} inputData */ recognize: function(inputData) { // make a new copy of the inputData // so we can change the inputData without messing up the other recognizers var inputDataClone = assign({}, inputData); // is is enabled and allow recognizing? if (!boolOrFn(this.options.enable, [this, inputDataClone])) { this.reset(); this.state = STATE_FAILED; return; } // reset when we've reached the end if (this.state & (STATE_RECOGNIZED | STATE_CANCELLED | STATE_FAILED)) { this.state = STATE_POSSIBLE; } this.state = this.process(inputDataClone); // the recognizer has recognized a gesture // so trigger an event if (this.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED | STATE_CANCELLED)) { this.tryEmit(inputDataClone); } }, /** * return the state of the recognizer * the actual recognizing happens in this method * @virtual * @param {Object} inputData * @returns {Const} STATE */ process: function(inputData) { }, // jshint ignore:line /** * return the preferred touch-action * @virtual * @returns {Array} */ getTouchAction: function() { }, /** * called when the gesture isn't allowed to recognize * like when another is being recognized or it is disabled * @virtual */ reset: function() { } }; /** * get a usable string, used as event postfix * @param {Const} state * @returns {String} state */ function stateStr(state) { if (state & STATE_CANCELLED) { return 'cancel'; } else if (state & STATE_ENDED) { return 'end'; } else if (state & STATE_CHANGED) { return 'move'; } else if (state & STATE_BEGAN) { return 'start'; } return ''; } /** * direction cons to string * @param {Const} direction * @returns {String} */ function directionStr(direction) { if (direction == DIRECTION_DOWN) { return 'down'; } else if (direction == DIRECTION_UP) { return 'up'; } else if (direction == DIRECTION_LEFT) { return 'left'; } else if (direction == DIRECTION_RIGHT) { return 'right'; } return ''; } /** * get a recognizer by name if it is bound to a manager * @param {Recognizer|String} otherRecognizer * @param {Recognizer} recognizer * @returns {Recognizer} */ function getRecognizerByNameIfManager(otherRecognizer, recognizer) { var manager = recognizer.manager; if (manager) { return manager.get(otherRecognizer); } return otherRecognizer; } /** * This recognizer is just used as a base for the simple attribute recognizers. * @constructor * @extends Recognizer */ function AttrRecognizer() { Recognizer.apply(this, arguments); } inherit(AttrRecognizer, Recognizer, { /** * @namespace * @memberof AttrRecognizer */ defaults: { /** * @type {Number} * @default 1 */ pointers: 1 }, /** * Used to check if it the recognizer receives valid input, like input.distance > 10. * @memberof AttrRecognizer * @param {Object} input * @returns {Boolean} recognized */ attrTest: function(input) { var optionPointers = this.options.pointers; return optionPointers === 0 || input.pointers.length === optionPointers; }, /** * Process the input and return the state for the recognizer * @memberof AttrRecognizer * @param {Object} input * @returns {*} State */ process: function(input) { var state = this.state; var eventType = input.eventType; var isRecognized = state & (STATE_BEGAN | STATE_CHANGED); var isValid = this.attrTest(input); // on cancel input and we've recognized before, return STATE_CANCELLED if (isRecognized && (eventType & INPUT_CANCEL || !isValid)) { return state | STATE_CANCELLED; } else if (isRecognized || isValid) { if (eventType & INPUT_END) { return state | STATE_ENDED; } else if (!(state & STATE_BEGAN)) { return STATE_BEGAN; } return state | STATE_CHANGED; } return STATE_FAILED; } }); /** * Pan * Recognized when the pointer is down and moved in the allowed direction. * @constructor * @extends AttrRecognizer */ function PanRecognizer() { AttrRecognizer.apply(this, arguments); this.pX = null; this.pY = null; } inherit(PanRecognizer, AttrRecognizer, { /** * @namespace * @memberof PanRecognizer */ defaults: { event: 'pan', threshold: 10, pointers: 1, direction: DIRECTION_ALL }, getTouchAction: function() { var direction = this.options.direction; var actions = []; if (direction & DIRECTION_HORIZONTAL) { actions.push(TOUCH_ACTION_PAN_Y); } if (direction & DIRECTION_VERTICAL) { actions.push(TOUCH_ACTION_PAN_X); } return actions; }, directionTest: function(input) { var options = this.options; var hasMoved = true; var distance = input.distance; var direction = input.direction; var x = input.deltaX; var y = input.deltaY; // lock to axis? if (!(direction & options.direction)) { if (options.direction & DIRECTION_HORIZONTAL) { direction = (x === 0) ? DIRECTION_NONE : (x < 0) ? DIRECTION_LEFT : DIRECTION_RIGHT; hasMoved = x != this.pX; distance = Math.abs(input.deltaX); } else { direction = (y === 0) ? DIRECTION_NONE : (y < 0) ? DIRECTION_UP : DIRECTION_DOWN; hasMoved = y != this.pY; distance = Math.abs(input.deltaY); } } input.direction = direction; return hasMoved && distance > options.threshold && direction & options.direction; }, attrTest: function(input) { return AttrRecognizer.prototype.attrTest.call(this, input) && (this.state & STATE_BEGAN || (!(this.state & STATE_BEGAN) && this.directionTest(input))); }, emit: function(input) { this.pX = input.deltaX; this.pY = input.deltaY; var direction = directionStr(input.direction); if (direction) { input.additionalEvent = this.options.event + direction; } this._super.emit.call(this, input); } }); /** * Pinch * Recognized when two or more pointers are moving toward (zoom-in) or away from each other (zoom-out). * @constructor * @extends AttrRecognizer */ function PinchRecognizer() { AttrRecognizer.apply(this, arguments); } inherit(PinchRecognizer, AttrRecognizer, { /** * @namespace * @memberof PinchRecognizer */ defaults: { event: 'pinch', threshold: 0, pointers: 2 }, getTouchAction: function() { return [TOUCH_ACTION_NONE]; }, attrTest: function(input) { return this._super.attrTest.call(this, input) && (Math.abs(input.scale - 1) > this.options.threshold || this.state & STATE_BEGAN); }, emit: function(input) { if (input.scale !== 1) { var inOut = input.scale < 1 ? 'in' : 'out'; input.additionalEvent = this.options.event + inOut; } this._super.emit.call(this, input); } }); /** * Press * Recognized when the pointer is down for x ms without any movement. * @constructor * @extends Recognizer */ function PressRecognizer() { Recognizer.apply(this, arguments); this._timer = null; this._input = null; } inherit(PressRecognizer, Recognizer, { /** * @namespace * @memberof PressRecognizer */ defaults: { event: 'press', pointers: 1, time: 251, // minimal time of the pointer to be pressed threshold: 9 // a minimal movement is ok, but keep it low }, getTouchAction: function() { return [TOUCH_ACTION_AUTO]; }, process: function(input) { var options = this.options; var validPointers = input.pointers.length === options.pointers; var validMovement = input.distance < options.threshold; var validTime = input.deltaTime > options.time; this._input = input; // we only allow little movement // and we've reached an end event, so a tap is possible if (!validMovement || !validPointers || (input.eventType & (INPUT_END | INPUT_CANCEL) && !validTime)) { this.reset(); } else if (input.eventType & INPUT_START) { this.reset(); this._timer = setTimeoutContext(function() { this.state = STATE_RECOGNIZED; this.tryEmit(); }, options.time, this); } else if (input.eventType & INPUT_END) { return STATE_RECOGNIZED; } return STATE_FAILED; }, reset: function() { clearTimeout(this._timer); }, emit: function(input) { if (this.state !== STATE_RECOGNIZED) { return; } if (input && (input.eventType & INPUT_END)) { this.manager.emit(this.options.event + 'up', input); } else { this._input.timeStamp = now(); this.manager.emit(this.options.event, this._input); } } }); /** * Rotate * Recognized when two or more pointer are moving in a circular motion. * @constructor * @extends AttrRecognizer */ function RotateRecognizer() { AttrRecognizer.apply(this, arguments); } inherit(RotateRecognizer, AttrRecognizer, { /** * @namespace * @memberof RotateRecognizer */ defaults: { event: 'rotate', threshold: 0, pointers: 2 }, getTouchAction: function() { return [TOUCH_ACTION_NONE]; }, attrTest: function(input) { return this._super.attrTest.call(this, input) && (Math.abs(input.rotation) > this.options.threshold || this.state & STATE_BEGAN); } }); /** * Swipe * Recognized when the pointer is moving fast (velocity), with enough distance in the allowed direction. * @constructor * @extends AttrRecognizer */ function SwipeRecognizer() { AttrRecognizer.apply(this, arguments); } inherit(SwipeRecognizer, AttrRecognizer, { /** * @namespace * @memberof SwipeRecognizer */ defaults: { event: 'swipe', threshold: 10, velocity: 0.3, direction: DIRECTION_HORIZONTAL | DIRECTION_VERTICAL, pointers: 1 }, getTouchAction: function() { return PanRecognizer.prototype.getTouchAction.call(this); }, attrTest: function(input) { var direction = this.options.direction; var velocity; if (direction & (DIRECTION_HORIZONTAL | DIRECTION_VERTICAL)) { velocity = input.overallVelocity; } else if (direction & DIRECTION_HORIZONTAL) { velocity = input.overallVelocityX; } else if (direction & DIRECTION_VERTICAL) { velocity = input.overallVelocityY; } return this._super.attrTest.call(this, input) && direction & input.offsetDirection && input.distance > this.options.threshold && input.maxPointers == this.options.pointers && abs(velocity) > this.options.velocity && input.eventType & INPUT_END; }, emit: function(input) { var direction = directionStr(input.offsetDirection); if (direction) { this.manager.emit(this.options.event + direction, input); } this.manager.emit(this.options.event, input); } }); /** * A tap is ecognized when the pointer is doing a small tap/click. Multiple taps are recognized if they occur * between the given interval and position. The delay option can be used to recognize multi-taps without firing * a single tap. * * The eventData from the emitted event contains the property `tapCount`, which contains the amount of * multi-taps being recognized. * @constructor * @extends Recognizer */ function TapRecognizer() { Recognizer.apply(this, arguments); // previous time and center, // used for tap counting this.pTime = false; this.pCenter = false; this._timer = null; this._input = null; this.count = 0; } inherit(TapRecognizer, Recognizer, { /** * @namespace * @memberof PinchRecognizer */ defaults: { event: 'tap', pointers: 1, taps: 1, interval: 300, // max time between the multi-tap taps time: 250, // max time of the pointer to be down (like finger on the screen) threshold: 9, // a minimal movement is ok, but keep it low posThreshold: 10 // a multi-tap can be a bit off the initial position }, getTouchAction: function() { return [TOUCH_ACTION_MANIPULATION]; }, process: function(input) { var options = this.options; var validPointers = input.pointers.length === options.pointers; var validMovement = input.distance < options.threshold; var validTouchTime = input.deltaTime < options.time; this.reset(); if ((input.eventType & INPUT_START) && (this.count === 0)) { return this.failTimeout(); } // we only allow little movement // and we've reached an end event, so a tap is possible if (validMovement && validTouchTime && validPointers) { if (input.eventType != INPUT_END) { return this.failTimeout(); } var validInterval = this.pTime ? (input.timeStamp - this.pTime < options.interval) : true; var validMultiTap = !this.pCenter || getDistance(this.pCenter, input.center) < options.posThreshold; this.pTime = input.timeStamp; this.pCenter = input.center; if (!validMultiTap || !validInterval) { this.count = 1; } else { this.count += 1; } this._input = input; // if tap count matches we have recognized it, // else it has began recognizing... var tapCount = this.count % options.taps; if (tapCount === 0) { // no failing requirements, immediately trigger the tap event // or wait as long as the multitap interval to trigger if (!this.hasRequireFailures()) { return STATE_RECOGNIZED; } else { this._timer = setTimeoutContext(function() { this.state = STATE_RECOGNIZED; this.tryEmit(); }, options.interval, this); return STATE_BEGAN; } } } return STATE_FAILED; }, failTimeout: function() { this._timer = setTimeoutContext(function() { this.state = STATE_FAILED; }, this.options.interval, this); return STATE_FAILED; }, reset: function() { clearTimeout(this._timer); }, emit: function() { if (this.state == STATE_RECOGNIZED) { this._input.tapCount = this.count; this.manager.emit(this.options.event, this._input); } } }); /** * Simple way to create a manager with a default set of recognizers. * @param {HTMLElement} element * @param {Object} [options] * @constructor */ function Hammer(element, options) { options = options || {}; options.recognizers = ifUndefined(options.recognizers, Hammer.defaults.preset); return new Manager(element, options); } /** * @const {string} */ Hammer.VERSION = '2.0.7'; /** * default settings * @namespace */ Hammer.defaults = { /** * set if DOM events are being triggered. * But this is slower and unused by simple implementations, so disabled by default. * @type {Boolean} * @default false */ domEvents: false, /** * The value for the touchAction property/fallback. * When set to `compute` it will magically set the correct value based on the added recognizers. * @type {String} * @default compute */ touchAction: TOUCH_ACTION_COMPUTE, /** * @type {Boolean} * @default true */ enable: true, /** * EXPERIMENTAL FEATURE -- can be removed/changed * Change the parent input target element. * If Null, then it is being set the to main element. * @type {Null|EventTarget} * @default null */ inputTarget: null, /** * force an input class * @type {Null|Function} * @default null */ inputClass: null, /** * Default recognizer setup when calling `Hammer()` * When creating a new Manager these will be skipped. * @type {Array} */ preset: [ // RecognizerClass, options, [recognizeWith, ...], [requireFailure, ...] [RotateRecognizer, {enable: false}], [PinchRecognizer, {enable: false}, ['rotate']], [SwipeRecognizer, {direction: DIRECTION_HORIZONTAL}], [PanRecognizer, {direction: DIRECTION_HORIZONTAL}, ['swipe']], [TapRecognizer], [TapRecognizer, {event: 'doubletap', taps: 2}, ['tap']], [PressRecognizer] ], /** * Some CSS properties can be used to improve the working of Hammer. * Add them to this method and they will be set when creating a new Manager. * @namespace */ cssProps: { /** * Disables text selection to improve the dragging gesture. Mainly for desktop browsers. * @type {String} * @default 'none' */ userSelect: 'none', /** * Disable the Windows Phone grippers when pressing an element. * @type {String} * @default 'none' */ touchSelect: 'none', /** * Disables the default callout shown when you touch and hold a touch target. * On iOS, when you touch and hold a touch target such as a link, Safari displays * a callout containing information about the link. This property allows you to disable that callout. * @type {String} * @default 'none' */ touchCallout: 'none', /** * Specifies whether zooming is enabled. Used by IE10> * @type {String} * @default 'none' */ contentZooming: 'none', /** * Specifies that an entire element should be draggable instead of its contents. Mainly for desktop browsers. * @type {String} * @default 'none' */ userDrag: 'none', /** * Overrides the highlight color shown when the user taps a link or a JavaScript * clickable element in iOS. This property obeys the alpha value, if specified. * @type {String} * @default 'rgba(0,0,0,0)' */ tapHighlightColor: 'rgba(0,0,0,0)' } }; var STOP = 1; var FORCED_STOP = 2; /** * Manager * @param {HTMLElement} element * @param {Object} [options] * @constructor */ function Manager(element, options) { this.options = assign({}, Hammer.defaults, options || {}); this.options.inputTarget = this.options.inputTarget || element; this.handlers = {}; this.session = {}; this.recognizers = []; this.oldCssProps = {}; this.element = element; this.input = createInputInstance(this); this.touchAction = new TouchAction(this, this.options.touchAction); toggleCssProps(this, true); each(this.options.recognizers, function(item) { var recognizer = this.add(new (item[0])(item[1])); item[2] && recognizer.recognizeWith(item[2]); item[3] && recognizer.requireFailure(item[3]); }, this); } Manager.prototype = { /** * set options * @param {Object} options * @returns {Manager} */ set: function(options) { assign(this.options, options); // Options that need a little more setup if (options.touchAction) { this.touchAction.update(); } if (options.inputTarget) { // Clean up existing event listeners and reinitialize this.input.destroy(); this.input.target = options.inputTarget; this.input.init(); } return this; }, /** * stop recognizing for this session. * This session will be discarded, when a new [input]start event is fired. * When forced, the recognizer cycle is stopped immediately. * @param {Boolean} [force] */ stop: function(force) { this.session.stopped = force ? FORCED_STOP : STOP; }, /** * run the recognizers! * called by the inputHandler function on every movement of the pointers (touches) * it walks through all the recognizers and tries to detect the gesture that is being made * @param {Object} inputData */ recognize: function(inputData) { var session = this.session; if (session.stopped) { return; } // run the touch-action polyfill this.touchAction.preventDefaults(inputData); var recognizer; var recognizers = this.recognizers; // this holds the recognizer that is being recognized. // so the recognizer's state needs to be BEGAN, CHANGED, ENDED or RECOGNIZED // if no recognizer is detecting a thing, it is set to `null` var curRecognizer = session.curRecognizer; // reset when the last recognizer is recognized // or when we're in a new session if (!curRecognizer || (curRecognizer && curRecognizer.state & STATE_RECOGNIZED)) { curRecognizer = session.curRecognizer = null; } var i = 0; while (i < recognizers.length) { recognizer = recognizers[i]; // find out if we are allowed try to recognize the input for this one. // 1. allow if the session is NOT forced stopped (see the .stop() method) // 2. allow if we still haven't recognized a gesture in this session, or the this recognizer is the one // that is being recognized. // 3. allow if the recognizer is allowed to run simultaneous with the current recognized recognizer. // this can be setup with the `recognizeWith()` method on the recognizer. if (session.stopped !== FORCED_STOP && ( // 1 !curRecognizer || recognizer == curRecognizer || // 2 recognizer.canRecognizeWith(curRecognizer))) { // 3 recognizer.recognize(inputData); } else { recognizer.reset(); } // if the recognizer has been recognizing the input as a valid gesture, we want to store this one as the // current active recognizer. but only if we don't already have an active recognizer if (!curRecognizer && recognizer.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED)) { curRecognizer = session.curRecognizer = recognizer; } i++; } }, /** * get a recognizer by its event name. * @param {Recognizer|String} recognizer * @returns {Recognizer|Null} */ get: function(recognizer) { if (recognizer instanceof Recognizer) { return recognizer; } var recognizers = this.recognizers; for (var i = 0; i < recognizers.length; i++) { if (recognizers[i].options.event == recognizer) { return recognizers[i]; } } return null; }, /** * add a recognizer to the manager * existing recognizers with the same event name will be removed * @param {Recognizer} recognizer * @returns {Recognizer|Manager} */ add: function(recognizer) { if (invokeArrayArg(recognizer, 'add', this)) { return this; } // remove existing var existing = this.get(recognizer.options.event); if (existing) { this.remove(existing); } this.recognizers.push(recognizer); recognizer.manager = this; this.touchAction.update(); return recognizer; }, /** * remove a recognizer by name or instance * @param {Recognizer|String} recognizer * @returns {Manager} */ remove: function(recognizer) { if (invokeArrayArg(recognizer, 'remove', this)) { return this; } recognizer = this.get(recognizer); // let's make sure this recognizer exists if (recognizer) { var recognizers = this.recognizers; var index = inArray(recognizers, recognizer); if (index !== -1) { recognizers.splice(index, 1); this.touchAction.update(); } } return this; }, /** * bind event * @param {String} events * @param {Function} handler * @returns {EventEmitter} this */ on: function(events, handler) { if (events === undefined) { return; } if (handler === undefined) { return; } var handlers = this.handlers; each(splitStr(events), function(event) { handlers[event] = handlers[event] || []; handlers[event].push(handler); }); return this; }, /** * unbind event, leave emit blank to remove all handlers * @param {String} events * @param {Function} [handler] * @returns {EventEmitter} this */ off: function(events, handler) { if (events === undefined) { return; } var handlers = this.handlers; each(splitStr(events), function(event) { if (!handler) { delete handlers[event]; } else { handlers[event] && handlers[event].splice(inArray(handlers[event], handler), 1); } }); return this; }, /** * emit event to the listeners * @param {String} event * @param {Object} data */ emit: function(event, data) { // we also want to trigger dom events if (this.options.domEvents) { triggerDomEvent(event, data); } // no handlers, so skip it all var handlers = this.handlers[event] && this.handlers[event].slice(); if (!handlers || !handlers.length) { return; } data.type = event; data.preventDefault = function() { data.srcEvent.preventDefault(); }; var i = 0; while (i < handlers.length) { handlers[i](data); i++; } }, /** * destroy the manager and unbinds all events * it doesn't unbind dom events, that is the user own responsibility */ destroy: function() { this.element && toggleCssProps(this, false); this.handlers = {}; this.session = {}; this.input.destroy(); this.element = null; } }; /** * add/remove the css properties as defined in manager.options.cssProps * @param {Manager} manager * @param {Boolean} add */ function toggleCssProps(manager, add) { var element = manager.element; if (!element.style) { return; } var prop; each(manager.options.cssProps, function(value, name) { prop = prefixed(element.style, name); if (add) { manager.oldCssProps[prop] = element.style[prop]; element.style[prop] = value; } else { element.style[prop] = manager.oldCssProps[prop] || ''; } }); if (!add) { manager.oldCssProps = {}; } } /** * trigger dom event * @param {String} event * @param {Object} data */ function triggerDomEvent(event, data) { var gestureEvent = document.createEvent('Event'); gestureEvent.initEvent(event, true, true); gestureEvent.gesture = data; data.target.dispatchEvent(gestureEvent); } assign(Hammer, { INPUT_START: INPUT_START, INPUT_MOVE: INPUT_MOVE, INPUT_END: INPUT_END, INPUT_CANCEL: INPUT_CANCEL, STATE_POSSIBLE: STATE_POSSIBLE, STATE_BEGAN: STATE_BEGAN, STATE_CHANGED: STATE_CHANGED, STATE_ENDED: STATE_ENDED, STATE_RECOGNIZED: STATE_RECOGNIZED, STATE_CANCELLED: STATE_CANCELLED, STATE_FAILED: STATE_FAILED, DIRECTION_NONE: DIRECTION_NONE, DIRECTION_LEFT: DIRECTION_LEFT, DIRECTION_RIGHT: DIRECTION_RIGHT, DIRECTION_UP: DIRECTION_UP, DIRECTION_DOWN: DIRECTION_DOWN, DIRECTION_HORIZONTAL: DIRECTION_HORIZONTAL, DIRECTION_VERTICAL: DIRECTION_VERTICAL, DIRECTION_ALL: DIRECTION_ALL, Manager: Manager, Input: Input, TouchAction: TouchAction, TouchInput: TouchInput, MouseInput: MouseInput, PointerEventInput: PointerEventInput, TouchMouseInput: TouchMouseInput, SingleTouchInput: SingleTouchInput, Recognizer: Recognizer, AttrRecognizer: AttrRecognizer, Tap: TapRecognizer, Pan: PanRecognizer, Swipe: SwipeRecognizer, Pinch: PinchRecognizer, Rotate: RotateRecognizer, Press: PressRecognizer, on: addEventListeners, off: removeEventListeners, each: each, merge: merge, extend: extend, assign: assign, inherit: inherit, bindFn: bindFn, prefixed: prefixed }); // this prevents errors when Hammer is loaded in the presence of an AMD // style loader but by script tag, not by the loader. var freeGlobal = (typeof window !== 'undefined' ? window : (typeof self !== 'undefined' ? self : {})); // jshint ignore:line freeGlobal.Hammer = Hammer; if (typeof define === 'function' && define.amd) { define(function() { return Hammer; }); } else if (typeof module != 'undefined' && module.exports) { module.exports = Hammer; } else { window[exportName] = Hammer; } })(window, document, 'Hammer'); //# sourceMappingURL=vendor.js.map