; (()=>{const e=document.querySelectorAll(".coblocks-animate");if("IntersectionObserver"in window){const t=new IntersectionObserver((e=>{e.forEach((e=>{e.isIntersecting&&(e.target.classList.add(e.target.dataset.coblocksAnimation),t.unobserve(e.target))}))}),{threshold:[.15]});e.forEach((e=>{t.observe(e)}))}else e.forEach((e=>{e.classList.remove("coblocks-animate"),delete e.dataset.coblocksAnimation}))})();; (()=>{var e={2590:function(e){e.exports=function(){"use strict";function e(){return e=Object.assign||function(e){for(var t=1;te.longSwipesMs?c(r+h*(m>0?-1:1)):c(m>0?r-v:r+v),w(n,i)}}}}(r,e,t,o),u=c.preheat,l=c.move,f=c.stop;function p(e){var t=a?e.changedTouches[0]:e;return{x:t.pageX,y:t.pageY}}function d(t){for(var n=0;n0||navigator.msMaxTouchPoints>0||window.DocumentTouch&&document instanceof DocumentTouch);Object.assign(n,{touchable:o,element:e,measure:i,limitation:r})}return n.update=i,i(e),n}var T="data-shallow-slider",P="data-slider";function E(e,n){function i(i){var r=e.element.$wrapper,o=i.index;r.querySelectorAll("["+P+"]").forEach((function(e){var i,r,a=~~e.getAttribute(P);i=e,void 0===(r=[n.slidePrevClass,n.slideNextClass,n.slideActiveClass])&&(r=[]),Array.isArray(r)||(r=[r]),r.forEach((function(e){return i.classList.contains(e)&&i.classList.remove(e)})),a===o&&t(e,n.slideActiveClass),a===o-1&&t(e,n.slidePrevClass),a===o+1&&t(e,n.slideNextClass)}))}function a(){e.element.$wrapper.querySelectorAll("["+T+"]").forEach((function(t){return e.element.$wrapper.removeChild(t)}))}function s(){e.element.$list.forEach((function(e,t){return r(e,P,t)})),a(),function(){if(n.loop){var t=e.element,i=e.limitation,o=t.$list,a=t.$wrapper,s=i.expand,c=o.slice(-s).map((function(e){return e.cloneNode(!0)})),u=o.slice(0,s).map((function(e){return e.cloneNode(!0)}));c.forEach((function(e,t){a.appendChild(r(u[t],T)),a.insertBefore(r(c[t],T),o[0])}))}}()}function c(){var t,i=e.element,r=e.measure,a=i.$wrapper,s={display:"flex",willChange:"transform",flexDirection:n.isHorizontal?"row":"column"},c=((t={})[n.isHorizontal?"width":"height"]=r.slideSize+"px",t[n.isHorizontal?"margin-right":"margin-bottom"]=n.spaceBetween+"px",t);o(a,s),a.querySelectorAll("["+P+"]").forEach((function(e){return o(e,c)}))}return{init:function(){s(),c()},render:function(t,r,o,a){var s=e.element.$wrapper,c=void 0===r?n.speed:r;n.injections.translate(t,e,n,c),t.isStart||i(t),a&&getComputedStyle(s).transform,o&&setTimeout(o,c)},destroy:function(){var t=e.element,i=t.$list,r=t.$wrapper,o=n.isHorizontal?"margin-right":"margin-bottom";["display","will-change","flex-direction"].forEach((function(e){r.style.removeProperty(e)})),i.forEach((function(e){return e.style.removeProperty(o)})),a()},updateSize:c}}function M(e,t){var n=e-t.max,i=e-t.min;return n>0?n:i<0?i:0}function A(t,n,i,r,o){function a(e){var n=t.measure;return Math.ceil(Math.abs(e)/n.boxSize-i.longSwipesRatio)}function s(e,t,i){r.render(n,e,t,i)}function c(r){var a,s=t.limitation,c=s.min,u=s.max,f=u-c+(i.loop?t.measure.boxSize:0),p=f+1;n.transforms=r,i.loop?(a=(u-r)%p/f,n.progress=a<0?1+a:a>1?a-1:a):(a=(u-r)/f,n.progress=a<0?0:a>1?1:a),o.emit(l,e({},n))}function p(e,r){var l=t.measure,p=t.limitation,d=p.maxIndex-p.minIndex+1,m=i.loop?(e%d+d)%d:e>p.maxIndex?p.maxIndex:e0?1:-1)*(n.minIndex-r-1)+t-e;return Math.abs(i)>Math.abs(o)?o:i}(n.index,m,p,x);g===x||h?n.index===m&&c(h>0?p.min-l.boxSize+h:p.max+l.boxSize+h):c(g<0?p.min-l.boxSize:p.max+l.boxSize),s(0,void 0,!0)}o.emit(u,n.index,n,m),n.index=m,c(v),s(r,(function(){o.emit(f,m,n)}))}return{update:function(){p(n.index,0),r.updateSize()},render:s,transform:c,slideTo:p,scrollPixel:function(e){var r=n.transforms,o=t.measure,a=t.limitation,s=Number(e.toExponential().split("e")[1]),u=s<=0?Math.pow(10,-(s-1)):1,l=r;if(i.resistance&&!i.loop&&(e>0&&r>=a.max?e-=Math.pow(e*u,i.resistanceRatio)/u:e<0&&r<=a.min&&(e+=Math.pow(-e*u,i.resistanceRatio)/u)),l+=e,i.loop){var f=n.tracker.vector(),p=i.isHorizontal?f.velocityX:f.velocityY,d=M(r,a);d&&function(e,t,n){return e>0&&t>n.max||e<0&&t0?a.min-o.boxSize+d:a.max+o.boxSize+d)}c(l)},initStatus:function(e){void 0===e&&(e=0),n.startTransform=e,n.isStart=!1,n.isScrolling=!1,n.isTouching=!1},initLayout:function(e){c(e)},getOffsetSteps:a}}function C(e,t){var n="string"==typeof e?document.body.querySelector(e):e,i=n.querySelector("."+t.wrapperClass),r=[].slice.call(n.getElementsByClassName(t.slideClass));return{$el:n,$wrapper:i,$list:r=r.filter((function(e){return null===e.getAttribute("data-shallow-slider")}))}}var $=function t(n,i){var r,o=function(t){var n=e({},a,t);return e({},n,{isHorizontal:"horizontal"===n.direction})}(i),u=(r={},{on:function(e,t){r[e]?r[e].push(t):r[e]=[t]},off:function(e,t){if(r[e]){var n=r[e].indexOf(t);n>-1&&r[e].splice(n,1)}},emit:function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i{var e={7152:function(e){e.exports=function(){"use strict";function e(){return(e=Object.assign||function(e){for(var t=1;te.longSwipesMs?l(p+m*(0h.maxIndex?h.maxIndex:eMath.abs(f)?f:v)===p||l?n.index===b&&d(0=s.max?e-=Math.pow(e*l,i.resistanceRatio)/l:e<0&&r<=s.min&&(e+=Math.pow(-e*l,i.resistanceRatio)/l)),c+=e,i.loop&&(o=n.tracker.vector(),l=i.isHorizontal?o.velocityX:o.velocityY,(e=w(r,s))&&(o=r,r=s,0r.max||l<0&&o{var t=e&&e.__esModule?()=>e.default:()=>e;return n.d(t,{a:t}),t},n.d=(e,t)=>{for(var i in t)n.o(t,i)&&!n.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),(()=>{"use strict";var e=n(7152),t=n.n(e),i=n(3266),o=n.n(i);!function(){const e=document.querySelectorAll(".wp-block-coblocks-gallery-carousel");for(let n=0;n{const t=s.querySelector(`.wp-block-coblocks-gallery-carousel-thumbnail-${r}`);if(t){t.classList.remove("is-active");const n=s.querySelector(`.wp-block-coblocks-gallery-carousel-thumbnail-${e}`);n&&n.classList.add("is-active")}},c=e=>{i?.slideTo(e),l(e),r=e},u=e=>{e!==r&&(l(e),r=e)},d=s.querySelector(".swiper-container");if(d){const e=d.getAttribute("data-swiper");if(e){const n=JSON.parse(e),r=s.querySelector(".nav-button__prev"),l=s.querySelector(".nav-button__next");r&&r.setAttribute("aria-label",coblocksTinyswiper.carouselPrevButtonAriaLabel),l&&l.setAttribute("aria-label",coblocksTinyswiper.carouselNextButtonAriaLabel);const p=s.querySelectorAll("img");for(let e=0;e{i.update()})).observe(d),n.thumbnails){const e=s.querySelectorAll(".wp-block-coblocks-gallery-carousel-thumbnail");for(const[t,n]of Object.entries(e))n.addEventListener("click",(()=>c(t)));const t=s.querySelector(".wp-block-coblocks-gallery-carousel-thumbnail-0");t&&t.classList.add("is-active")}if(!n.thumbnails&&n.pageDots){const e=s.querySelectorAll(".wp-block-coblocks-gallery-carousel-page-dot-pagination");for(const[t,n]of Object.entries(e))n.addEventListener("click",(()=>c(t)));const t=s.querySelector(".wp-block-coblocks-gallery-carousel-page-dot--0");t&&t.classList.add("is-active")}if(!0!==n.draggable){const e=s.querySelector(".swiper-wrapper");e?.addEventListener("mousedown",(e=>{e.stopPropagation()}))}!0===n.autoPlay&&n.autoPlaySpeed&&(!0===n.pauseHover&&(d.addEventListener("mouseenter",(()=>{a=!0})),d.addEventListener("mouseleave",(()=>{a=!1}))),setInterval((()=>{!0===n.pauseHover&&!0===a||i?.slideTo(i.state.index+1)}),n.autoPlaySpeed)),i.on("after-slide",u)}}}}()})()})();; /* global document */ /* global jQuery */ (function ($) { 'use strict'; var loadYoutube = function() { $('.mace-youtube').each(function() { var $youtube = $(this); if($youtube.is('.mace-youtube-loaded')) { return; } var videoUrl = $youtube.attr('data-mace-video'); var thumbUrl = $youtube.attr('data-mace-video-thumb'); var image = $(''); image.attr('src', thumbUrl); // Lazy loading. image.attr({ 'width': 1600, 'height': 900, 'src': 'data:image/svg+xml;charset=utf-8,%3Csvg xmlns%3D\'http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg\' viewBox%3D\'0 0 1600 900\'%2F%3E', 'data-src': thumbUrl, 'data-expand': 600 }); image.addClass('lazyload'); image.on('load', function() { $youtube.append( image ); }()); // Click to play YT. $youtube.on('click', function() { $youtube.find('iframe').remove(); var $iframe = $('',srcAction:"iframe_src",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(){b.types.push(P),w("BeforeChange",function(a,b,c){b!==c&&(b===P?R():c===P&&R(!0))}),w(h+"."+P,function(){R()})},getIframe:function(c,d){var e=c.src,f=b.st.iframe;a.each(f.patterns,function(){return e.indexOf(this.index)>-1?(this.id&&(e="string"==typeof this.id?e.substr(e.lastIndexOf(this.id)+this.id.length,e.length):this.id.call(this,e)),e=this.src.replace("%id%",e),!1):void 0});var g={};return f.srcAction&&(g[f.srcAction]=e),b._parseMarkup(d,g,c),b.updateStatus("ready"),d}}});var S=function(a){var c=b.items.length;return a>c-1?a-c:0>a?c+a:a},T=function(a,b,c){return a.replace(/%curr%/gi,b+1).replace(/%total%/gi,c)};a.magnificPopup.registerModule("gallery",{options:{enabled:!1,arrowMarkup:'',preload:[0,2],navigateByImgClick:!0,arrows:!0,tPrev:"Previous (Left arrow key)",tNext:"Next (Right arrow key)",tCounter:"%curr% of %total%"},proto:{initGallery:function(){var c=b.st.gallery,e=".mfp-gallery";return b.direction=!0,c&&c.enabled?(f+=" mfp-gallery",w(m+e,function(){c.navigateByImgClick&&b.wrap.on("click"+e,".mfp-img",function(){return b.items.length>1?(b.next(),!1):void 0}),d.on("keydown"+e,function(a){37===a.keyCode?b.prev():39===a.keyCode&&b.next()})}),w("UpdateStatus"+e,function(a,c){c.text&&(c.text=T(c.text,b.currItem.index,b.items.length))}),w(l+e,function(a,d,e,f){var g=b.items.length;e.counter=g>1?T(c.tCounter,f.index,g):""}),w("BuildControls"+e,function(){if(b.items.length>1&&c.arrows&&!b.arrowLeft){var d=c.arrowMarkup,e=b.arrowLeft=a(d.replace(/%title%/gi,c.tPrev).replace(/%dir%/gi,"left")).addClass(s),f=b.arrowRight=a(d.replace(/%title%/gi,c.tNext).replace(/%dir%/gi,"right")).addClass(s);e.click(function(){b.prev()}),f.click(function(){b.next()}),b.container.append(e.add(f))}}),w(n+e,function(){b._preloadTimeout&&clearTimeout(b._preloadTimeout),b._preloadTimeout=setTimeout(function(){b.preloadNearbyImages(),b._preloadTimeout=null},16)}),void w(h+e,function(){d.off(e),b.wrap.off("click"+e),b.arrowRight=b.arrowLeft=null})):!1},next:function(){b.direction=!0,b.index=S(b.index+1),b.updateItemHTML()},prev:function(){b.direction=!1,b.index=S(b.index-1),b.updateItemHTML()},goTo:function(a){b.direction=a>=b.index,b.index=a,b.updateItemHTML()},preloadNearbyImages:function(){var a,c=b.st.gallery.preload,d=Math.min(c[0],b.items.length),e=Math.min(c[1],b.items.length);for(a=1;a<=(b.direction?e:d);a++)b._preloadItem(b.index+a);for(a=1;a<=(b.direction?d:e);a++)b._preloadItem(b.index-a)},_preloadItem:function(c){if(c=S(c),!b.items[c].preloaded){var d=b.items[c];d.parsed||(d=b.parseEl(c)),y("LazyLoad",d),"image"===d.type&&(d.img=a('').on("load.mfploader",function(){d.hasSize=!0}).on("error.mfploader",function(){d.hasSize=!0,d.loadError=!0,y("LazyLoadError",d)}).attr("src",d.src)),d.preloaded=!0}}}});var U="retina";a.magnificPopup.registerModule(U,{options:{replaceSrc:function(a){return a.src.replace(/\.\w+$/,function(a){return"@2x"+a})},ratio:1},proto:{initRetina:function(){if(window.devicePixelRatio>1){var a=b.st.retina,c=a.ratio;c=isNaN(c)?c():c,c>1&&(w("ImageHasSize."+U,function(a,b){b.img.css({"max-width":b.img[0].naturalWidth/c,width:"100%"})}),w("ElementParse."+U,function(b,d){d.src=a.replaceSrc(d,c)}))}}}}),A()});; /** * Timeago is a jQuery plugin that makes it easy to support automatically * updating fuzzy timestamps (e.g. "4 minutes ago" or "about 1 day ago"). * * @name timeago * @version 1.5.2 * @requires jQuery v1.2.3+ * @author Ryan McGeary * @license MIT License - http://www.opensource.org/licenses/mit-license.php * * For usage and examples, visit: * http://timeago.yarp.com/ * * Copyright (c) 2008-2015, Ryan McGeary (ryan -[at]- mcgeary [*dot*] org) */ (function (factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['jquery'], factory); } else if (typeof module === 'object' && typeof module.exports === 'object') { factory(require('jquery')); } else { // Browser globals factory(jQuery); } }(function ($) { $.timeago = function(timestamp) { if (timestamp instanceof Date) { return inWords(timestamp); } else if (typeof timestamp === "string") { return inWords($.timeago.parse(timestamp)); } else if (typeof timestamp === "number") { return inWords(new Date(timestamp)); } else { return inWords($.timeago.datetime(timestamp)); } }; var $t = $.timeago; $.extend($.timeago, { settings: { refreshMillis: 60000, allowPast: true, allowFuture: false, localeTitle: false, cutoff: 0, autoDispose: true, strings: { prefixAgo: null, prefixFromNow: null, suffixAgo: "ago", suffixFromNow: "from now", inPast: 'any moment now', seconds: "less than a minute", minute: "about a minute", minutes: "%d minutes", hour: "about an hour", hours: "about %d hours", day: "a day", days: "%d days", month: "about a month", months: "%d months", year: "about a year", years: "%d years", wordSeparator: " ", numbers: [] } }, inWords: function(distanceMillis) { if (!this.settings.allowPast && ! this.settings.allowFuture) { throw 'timeago allowPast and allowFuture settings can not both be set to false.'; } var $l = this.settings.strings; var prefix = $l.prefixAgo; var suffix = $l.suffixAgo; if (this.settings.allowFuture) { if (distanceMillis < 0) { prefix = $l.prefixFromNow; suffix = $l.suffixFromNow; } } if (!this.settings.allowPast && distanceMillis >= 0) { return this.settings.strings.inPast; } var seconds = Math.abs(distanceMillis) / 1000; var minutes = seconds / 60; var hours = minutes / 60; var days = hours / 24; var years = days / 365; function substitute(stringOrFunction, number) { var string = $.isFunction(stringOrFunction) ? stringOrFunction(number, distanceMillis) : stringOrFunction; var value = ($l.numbers && $l.numbers[number]) || number; return string.replace(/%d/i, value); } var words = seconds < 45 && substitute($l.seconds, Math.round(seconds)) || seconds < 90 && substitute($l.minute, 1) || minutes < 45 && substitute($l.minutes, Math.round(minutes)) || minutes < 90 && substitute($l.hour, 1) || hours < 24 && substitute($l.hours, Math.round(hours)) || hours < 42 && substitute($l.day, 1) || days < 30 && substitute($l.days, Math.round(days)) || days < 45 && substitute($l.month, 1) || days < 365 && substitute($l.months, Math.round(days / 30)) || years < 1.5 && substitute($l.year, 1) || substitute($l.years, Math.round(years)); var separator = $l.wordSeparator || ""; if ($l.wordSeparator === undefined) { separator = " "; } return $.trim([prefix, words, suffix].join(separator)); }, parse: function(iso8601) { var s = $.trim(iso8601); s = s.replace(/\.\d+/,""); // remove milliseconds s = s.replace(/-/,"/").replace(/-/,"/"); s = s.replace(/T/," ").replace(/Z/," UTC"); s = s.replace(/([\+\-]\d\d)\:?(\d\d)/," $1$2"); // -04:00 -> -0400 s = s.replace(/([\+\-]\d\d)$/," $100"); // +09 -> +0900 return new Date(s); }, datetime: function(elem) { var iso8601 = $t.isTime(elem) ? $(elem).attr("datetime") : $(elem).attr("title"); return $t.parse(iso8601); }, isTime: function(elem) { // jQuery's `is()` doesn't play well with HTML5 in IE return $(elem).get(0).tagName.toLowerCase() === "time"; // $(elem).is("time"); } }); // functions that can be called via $(el).timeago('action') // init is default when no action is given // functions are called with context of a single element var functions = { init: function() { var refresh_el = $.proxy(refresh, this); refresh_el(); var $s = $t.settings; if ($s.refreshMillis > 0) { this._timeagoInterval = setInterval(refresh_el, $s.refreshMillis); } }, update: function(timestamp) { var date = (timestamp instanceof Date) ? timestamp : $t.parse(timestamp); $(this).data('timeago', { datetime: date }); if ($t.settings.localeTitle) $(this).attr("title", date.toLocaleString()); refresh.apply(this); }, updateFromDOM: function() { $(this).data('timeago', { datetime: $t.parse( $t.isTime(this) ? $(this).attr("datetime") : $(this).attr("title") ) }); refresh.apply(this); }, dispose: function () { if (this._timeagoInterval) { window.clearInterval(this._timeagoInterval); this._timeagoInterval = null; } } }; $.fn.timeago = function(action, options) { var fn = action ? functions[action] : functions.init; if (!fn) { throw new Error("Unknown function name '"+ action +"' for timeago"); } // each over objects here and call the requested function this.each(function() { fn.call(this, options); }); return this; }; function refresh() { var $s = $t.settings; //check if it's still visible if ($s.autoDispose && !$.contains(document.documentElement,this)) { //stop if it has been removed $(this).timeago("dispose"); return this; } var data = prepareData(this); if (!isNaN(data.datetime)) { if ( $s.cutoff == 0 || Math.abs(distance(data.datetime)) < $s.cutoff) { $(this).text(inWords(data.datetime)); } } return this; } function prepareData(element) { element = $(element); if (!element.data("timeago")) { element.data("timeago", { datetime: $t.datetime(element) }); var text = $.trim(element.text()); if ($t.settings.localeTitle) { element.attr("title", element.data('timeago').datetime.toLocaleString()); } else if (text.length > 0 && !($t.isTime(element) && element.attr("title"))) { element.attr("title", text); } } return element.data("timeago"); } function inWords(date) { return $t.inWords(distance(date)); } function distance(date) { return (new Date().getTime() - date.getTime()); } // fix for IE6 suckage document.createElement("abbr"); document.createElement("time"); }));; // English (Template) jQuery.timeago.settings.strings = { prefixAgo: null, prefixFromNow: null, suffixAgo: "ago", suffixFromNow: "from now", seconds: "less than a minute", minute: "about a minute", minutes: "%d minutes", hour: "about an hour", hours: "about %d hours", day: "a day", days: "%d days", month: "about a month", months: "%d months", year: "about a year", years: "%d years", wordSeparator: " ", numbers: [] }; ; /* global document */ /* global jQuery */ /* global snax */ /* global alert */ /* global confirm */ /* global console */ /* global grecaptcha */ // globa namespace if ( typeof window.snax === 'undefined' ) { window.snax = {}; } /******** * * Core * *******/ (function ($, ctx) { 'use strict'; /** VARS *************************/ ctx.config = $.parseJSON(window.snax_front_config); if (!ctx.config) { throw 'Snax Error: Global config is not defined!'; } /** FUNCTIONS ********************/ ctx.log = function(msg) { if (typeof console !== 'undefined') { console.log(msg); } }; ctx.inDebugMode = function() { return (typeof ctx.config.debug_mode !== 'undefined' && ctx.config.debug_mode); }; ctx.isTouchDevice = function () { return ('ontouchstart' in window) || navigator.msMaxTouchPoints; }; ctx.createCookie = function (name, value, hours) { var expires; if (hours) { var date = new Date(); date.setTime(date.getTime() + (hours * 60 * 60 * 1000)); expires = '; expires=' + date.toUTCString(); } else { expires = ''; } document.cookie = name.concat('=', value, expires, '; path=/'); }; ctx.readCookie = function (name) { var nameEQ = name + '='; var ca = document.cookie.split(';'); for(var i = 0; i < ca.length; i += 1) { var c = ca[i]; while (c.charAt(0) === ' ') { c = c.substring(1,c.length); } if (c.indexOf(nameEQ) === 0) { return c.substring(nameEQ.length,c.length); } } return null; }; ctx.deleteCookie = function (name) { ctx.createCookie(name, '', -1); }; ctx.getUrlParameter = function (param) { var sPageURL = decodeURIComponent(window.location.search.substring(1)), sURLVariables = sPageURL.split('&'), sParameterName, i; for (i = 0; i < sURLVariables.length; i++) { sParameterName = sURLVariables[i].split('='); if (sParameterName[0] === param) { return sParameterName[1] === undefined ? true : sParameterName[1]; } } }; })(jQuery, snax); /*********** * * Helpers * ***********/ (function ($, ctx) { /* Media Item Class (image, audio, video) */ ctx.MediaItem = function (data) { // Public scope. var instance = {}; // Constructor. function init() { data = data || {}; data = $.extend({ 'type': 'image', 'title': '', 'source': '', 'refLink': '', 'description': '', 'mediaId': '', 'postId': 0, 'authorId': '', 'status': '', 'parentFormat': 'list', 'origin': 'post', 'legal': false, 'memeTemplate': '' }, data); return instance; } instance.save = function(callback) { callback = callback || function() {}; var ajaxData = { 'action': 'snax_add_media_item', 'security': $('input[name=snax-add-media-item-nonce]').val(), 'snax_title': data.title, 'snax_source': data.source, 'snax_ref_link': data.refLink, 'snax_description': data.description, 'snax_media_id': data.mediaId, 'snax_post_id': data.postId, 'snax_author_id': data.authorId, 'snax_status': data.status, 'snax_parent_format': data.parentFormat, 'snax_origin': data.origin, 'snax_legal': data.legal ? 'accepted' : '', 'snax_type': data.type, 'snax_meme_template': data.memeTemplate }; if (typeof ctx.saveItemImageDataFilter === 'function') { ajaxData = ctx.saveItemImageDataFilter(ajaxData, data); } var xhr = $.ajax({ 'type': 'POST', 'url': ctx.config.ajax_url, 'dataType': 'json', 'data': ajaxData }); xhr.done(function (res) { callback(res); }); }; return init(); }; /* Embed Item Class */ ctx.EmbedItem = function (data) { // Public scope. var instance = {}; // Constructor. function init() { data = data || {}; data = $.extend({ 'type': 'embed', 'title': '', 'source': '', 'refLink': '', 'description': '', 'embedCode': '', 'postId': 0, 'authorId': '', 'status': '', 'parentFormat': 'list', 'origin': 'post', 'legal': false }, data); return instance; } instance.save = function(callback) { callback = callback || function() {}; var ajaxData = { 'action': 'snax_add_embed_item', 'security': $('input[name=snax-add-embed-item-nonce]').val(), 'snax_title': data.title, 'snax_source': data.source, 'snax_ref_link': data.refLink, 'snax_embed_code': data.embedCode, 'snax_description': data.description, 'snax_post_id': data.postId, 'snax_author_id': data.authorId, 'snax_status': data.status, 'snax_parent_format': data.parentFormat, 'snax_origin': data.origin, 'snax_legal': data.legal ? 'accepted' : '' }; if (typeof ctx.saveItemEmbedDataFilter === 'function') { ajaxData = ctx.saveItemEmbedDataFilter(ajaxData, data); } var xhr = $.ajax({ 'type': 'POST', 'url': ctx.config.ajax_url, 'dataType': 'json', 'data': ajaxData }); xhr.done(function (res) { callback(res); }); }; return init(); }; /* Embed Item Class */ ctx.TextItem = function (data) { // Public scope. var instance = {}; // Constructor. function init() { data = data || {}; data = $.extend({ 'type': 'text', 'title': '', 'refLink': '', 'description': '', 'postId': 0, 'authorId': '', 'status': '', 'parentFormat': 'list', 'origin': 'post', 'legal': false }, data); return instance; } instance.save = function(callback) { callback = callback || function() {}; var ajaxData = { 'action': 'snax_add_text_item', 'security': $('input[name=snax-add-text-item-nonce]').val(), 'snax_title': data.title, 'snax_ref_link': data.refLink, 'snax_description': data.description, 'snax_post_id': data.postId, 'snax_author_id': data.authorId, 'snax_status': data.status, 'snax_parent_format': data.parentFormat, 'snax_origin': data.origin, 'snax_legal': data.legal ? 'accepted' : '' }; if (typeof ctx.saveItemTextDataFilter === 'function') { ajaxData = ctx.saveItemTextDataFilter(ajaxData, data); } var xhr = $.ajax({ 'type': 'POST', 'url': ctx.config.ajax_url, 'dataType': 'json', 'data': ajaxData }); xhr.done(function (res) { callback(res); }); }; return init(); }; ctx.deleteItem = function($link, callback) { callback = callback || function() {}; var nonce = $.trim($link.attr('data-snax-nonce')); var itemId = parseInt($link.attr('data-snax-item-id'), 10); var userId = snax.currentUserId; var xhr = $.ajax({ 'type': 'POST', 'url': ctx.config.ajax_url, 'dataType': 'json', 'data': { 'action': 'snax_delete_item', 'security': nonce, 'snax_item_id': itemId, 'snax_user_id': userId } }); xhr.done(function (res) { callback(res); }); }; ctx.setItemAsFeatured = function($link, callback) { callback = callback || function() {}; var nonce = $.trim($link.attr('data-snax-nonce')); var itemId = parseInt($link.attr('data-snax-item-id'), 10); var userId = snax.currentUserId; var xhr = $.ajax({ 'type': 'POST', 'url': ctx.config.ajax_url, 'dataType': 'json', 'data': { 'action': 'snax_set_item_as_featured', 'security': nonce, 'snax_item_id': itemId, 'snax_user_id': userId } }); xhr.done(function (res) { callback(res); }); }; ctx.updateItems = function(items, callback) { callback = callback || function() {}; var xhr = $.ajax({ 'type': 'POST', 'url': ctx.config.ajax_url, 'dataType': 'json', 'data': { 'action': 'snax_update_items', 'security': $('input[name=snax-frontend-submission-nonce]').val(), 'snax_items': items } }); xhr.done(function (res) { callback(res); }); }; ctx.deletePost = function($link, callback) { callback = callback || function() {}; var nonce = $.trim($link.attr('data-snax-nonce')); var postId = parseInt($link.attr('data-snax-post-id'), 10); var xhr = $.ajax({ 'type': 'POST', 'url': ctx.config.ajax_url, 'dataType': 'json', 'data': { 'action': 'snax_delete_post', 'security': nonce, 'snax_post_id': postId } }); xhr.done(function (res) { callback(res); }); }; ctx.loginRequired = function(blocked) { $('body').trigger('snaxLoginRequired', [blocked]); }; ctx.getMediaHtmlTag = function(data, callback) { var xhr = $.ajax({ 'type': 'GET', 'url': ctx.config.ajax_url, 'dataType': 'json', 'data': { 'action': 'snax_load_media_tpl', 'snax_media_id': data.mediaId, 'snax_post_id': data.postId, 'snax_type': data.type } }); xhr.done(function (res) { callback(res); }); }; ctx.deleteMedia = function(data, callback) { callback = callback || function() {}; var xhr = $.ajax({ 'type': 'POST', 'url': ctx.config.ajax_url, 'dataType': 'json', 'data': { 'action': 'snax_delete_media', 'security': $('input[name=snax-delete-media-nonce]').val(), 'snax_media_id': data.mediaId, 'snax_author_id': data.authorId } }); xhr.done(function (res) { callback(res); }); }; ctx.updateMediaMetadata = function(data, callback) { callback = callback || function() {}; var xhr = $.ajax({ 'type': 'POST', 'url': ctx.config.ajax_url, 'dataType': 'json', 'data': { 'action': 'snax_update_media_meta', // @todo - use separate nonce or use generic one. 'security': $('input[name=snax-delete-media-nonce]').val(), 'snax_media_id': data.mediaId, 'snax_parent_format': data.parentFormat } }); xhr.done(function (res) { callback(res); }); }; ctx.getEmbedPreview = function(embed_code, callback) { var xhr = $.ajax({ 'type': 'POST', 'url': ctx.config.ajax_url, 'dataType': 'json', 'data': { 'action': 'snax_load_embed_tpl', 'snax_embed_code': embed_code } }); xhr.done(function (res) { callback(res); }); }; ctx.displayFeedback = function(type) { var feedbackTypeClass = 'snax-feedback-' + type; // Try to get type specific feedback first. var $feedback = $('.' + feedbackTypeClass); if ($feedback.length === 0) { return; } ctx.hideFeedback(); // Activate. $feedback.toggleClass('snax-feedback-off snax-feedback-on'); // Show. $('body').addClass('snax-show-feedback'); }; ctx.hideFeedback = function() { // Deactivate all. $('.snax-feedback-on').toggleClass('snax-feedback-on snax-feedback-off'); // Hide all. $('body').removeClass('snax-show-feedback'); }; ctx.isValidUrl = function(url) { return url.match(/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)/); }; })(jQuery, snax); /********* * * Common * *********/ (function ($, ctx) { 'use strict'; var selectors = { 'feedbackCloseButton': '.snax-close-button' }; // fire $(document).ready(function () { /* * Close feedback button. */ $(selectors.feedbackCloseButton).on('click', function(e) { e.preventDefault(); snax.hideFeedback(); }); }); })(jQuery, snax); /**************** * * Facebook SDK * ****************/ (function ($, ctx) { 'use strict'; ctx.resetFacebookSDK = function () { $('script#facebook-jssdk').remove(); $('#fb-root').remove(); if (window.FB) { delete window.FB; } }; $('body').on( 'snaxBeforeNewContentReady', function ( e, $newContent ) { if ($newContent.find('.fb-video')) { ctx.resetFacebookSDK(); } } ); })(jQuery, snax); /**************************** * * Module: Media upload form * ***************************/ (function ($, ctx) { 'use strict'; var selectors = { 'form': '.snax-media-upload-form', 'pluploadForm': '.snax-plupload-upload-ui', 'loadFormButton': '.snax-load-form-button' }; ctx.mediaUploadForm = function () { if (typeof snaxPlupload === 'undefined') { return; } $(selectors.form).each(function() { var $form = $(this); var formInsideInactiveTab = $form.parents('.snax-tab-content:not(.snax-tab-content-current)').length > 0; if (!formInsideInactiveTab) { snaxPlupload.initUploader($form); } }); $('body').on('snaxTabContentActive', function (e, $tabContent) { $tabContent.find(selectors.form).each(function () { snaxPlupload.initUploader($(this)); }); } ); $(selectors.loadFormButton).on('click',function() { var $link = $(this); var $form = $link.parents(selectors.form); var formClass = $link.attr('data-snax-rel-class'); $form.find('.' + formClass).toggle(); var $pluploadForm = $form.find(selectors.pluploadForm); $pluploadForm.toggle(); if ($pluploadForm.is(':visible')) { $form.removeClass('snax-custom-form'); } else { $form.addClass('snax-custom-form'); } }); }; // fire $(document).ready(function () { ctx.mediaUploadForm(); }); })(jQuery, snax); /************************* * * Module: Date > Time ago * *************************/ (function ($, ctx) { 'use strict'; var selectors = { 'wrapper': '.snax-time-left', 'dateWrapper': '> .snax-date-wrapper', 'date': '> .snax-date', 'timeWrapper': '> .snax-time-wrapper', 'time': '> .snax-time' }; ctx.timeagoSelectors = selectors; ctx.dateConstans = { 'day_ms': 1000 * 60 * 60 * 24, 'month_ms': 1000 * 60 * 60 * 24 * 30, 'year_ms': 1000 * 60 * 60 * 24 * 356 }; ctx.dateToTimeago = function () { if (!$.fn.timeago) { return; } // store current settings, thanks to $.extend we have a copy without reference to original object var origSettings = $.extend(true, {} , $.timeago.settings); // override $.extend($.timeago.settings, { cutoff: ctx.dateConstans.year_ms, allowFuture: true }); $.extend($.timeago.settings.strings, { suffixFromNow: '' }); // apply $(selectors.wrapper).each(function () { var $wrapper = $(this); var $dateWrapper = $wrapper.find(selectors.dateWrapper); var $date = $dateWrapper.find(selectors.date); var $timeWrapper = $wrapper.find(selectors.timeWrapper); var $time = $timeWrapper.find(selectors.time); var timeLeftText = $.timeago($date.text()); $time.text(timeLeftText); $dateWrapper.removeClass( '.snax-date-wrapper-unfriendly' ); $timeWrapper.removeClass( 'snax-time-wrapper-unfriendly' ); }); // restore $.timeago.settings = origSettings; }; // fire $(document).ready(function () { ctx.dateToTimeago(); }); })(jQuery, snax); /************************** * * Module: Upvote/Downvote * *************************/ (function ($, ctx) { 'use strict'; var locked = false; var selectors = { 'wrapper': '.snax-voting', 'upvoteLink': '.snax-voting-upvote', 'downvoteLink': '.snax-voting-downvote', 'guestVoting': '.snax-guest-voting', 'voted': '.snax-user-voted', 'scoreWrapper': '.snax-voting-score', 'scoreValue': '.snax-voting-score strong' }; var classes = { 'voted': 'snax-user-voted' }; ctx.votesSelectors = selectors; ctx.votesClasses = classes; ctx.votes = function () { // Catch event on wrapper to keep it working after box content reloading $('body').on('click', selectors.upvoteLink + ', ' + selectors.downvoteLink, function (e) { e.preventDefault(); if (locked) { return; } locked = true; var $link = $(this); var voteType = $link.is(selectors.upvoteLink) ? 'upvote' : 'downvote'; var $wrapper = $link.parents(selectors.wrapper); var nonce = $.trim($link.attr('data-snax-nonce')); var itemId = parseInt($link.attr('data-snax-item-id'), 10); var authorId = parseInt($link.attr('data-snax-author-id'), 10); ctx.vote({ 'itemId': itemId, 'authorId': authorId, 'type': voteType }, nonce, $wrapper); }); // Iterate over all voting boxes and update them based on cookie states. $(selectors.wrapper).each(function () { var $this = $(this); var id = parseInt($this.attr('data-snax-item-id'), 10); if (id <= 0) { return; } var typeCookie = 'snax_vote_type_' + id; var scoreCookie = 'snax_vote_score_' + id; var type = ctx.readCookie(typeCookie); var score = ctx.readCookie(scoreCookie); if (!type && !score) { return; } if (score) { ctx.updateVoteScore($this.find(selectors.scoreWrapper), score); } if (type) { var $upVoteLink = $this.find(selectors.upvoteLink); var $downVoteLink = $this.find(selectors.downvoteLink); if ('upvote' === type) { $upVoteLink.addClass(classes.voted); $downVoteLink.removeClass(classes.voted); } else { $downVoteLink.addClass(classes.voted); $upVoteLink.removeClass(classes.voted); } } }); }; ctx.vote = function (data, nonce, $box) { var config = $.parseJSON(window.snax_front_config); if ( $box.find('.snax-login-required').length > 0 ){ return; } if (!config) { ctx.log('Item voting failed. Global config is not defined!'); return; } /* * Apply new voting box state before ajax response. */ var $userVoted = $box.find('.snax-user-voted'); var userUpvoted = $userVoted.length > 0 && $userVoted.is('.snax-voting-upvote'); var userDownvoted = $userVoted.length > 0 && $userVoted.is('.snax-voting-downvote'); var score = parseInt( $box.find('.snax-voting-score').data('snax-voting-score'), 10); var diff = 'upvote' === data.type ? 1 : -1; // Remove all bubbles. $box.find('.snax-voting-bubble').remove(); // User reverted his vote. if (userUpvoted && 'upvote' === data.type || userDownvoted && 'downvote' === data.type) { diff *= -1; $box.find('.snax-user-voted').removeClass('snax-user-voted'); if ( 'upvote' === data.type ) { $box.find('.snax-voting-upvote').append('-1'); } else { $box.find('.snax-voting-downvote').append('+1'); } // User voted opposite. } else if (userUpvoted && 'downvote' === data.type || userDownvoted && 'upvote' === data.type) { diff *= 2; $box.find('.snax-user-voted').removeClass('snax-user-voted'); $box.find('.snax-voting-' + data.type).addClass('snax-user-voted'); if ( 'upvote' === data.type ) { $box.find('.snax-voting-upvote').append('+2'); } else { $box.find('.snax-voting-downvote').append('-2'); } // User added new vote. } else { if ( 'upvote' === data.type ) { $box.find('.snax-voting-upvote').addClass('snax-user-voted').append('+1'); } else { $box.find('.snax-voting-downvote').addClass('snax-user-voted').append('-1'); } } // Update score. ctx.updateVoteScore($box.find(selectors.scoreWrapper), score + diff); // Send ajax. var xhr = $.ajax({ 'type': 'POST', 'url': config.ajax_url, 'dataType': 'json', 'data': { 'action': 'snax_vote_item', 'security': nonce, 'snax_item_id': data.itemId, 'snax_author_id': data.authorId, 'snax_vote_type': data.type, 'snax_user_voted': ctx.readCookie( 'snax_vote_type_' + data.itemId ) } }); // Update state immediately after sending ajax. Don't wait for response. ctx.updateVoteState(data.itemId, data.type, $box); xhr.done(function (res) { locked = false; }); }; ctx.updateVoteState = function(itemId, type, $box) { var typeCookie = 'snax_vote_type_' + itemId; var scoreCookie = 'snax_vote_score_' + itemId; var currentValue = ctx.readCookie(typeCookie); // Cookie can't be read immediately so we need to update CSS classes manually. $box.find(selectors.voted).removeClass(classes.voted); // User voted and now he wants to remove the vote. if (currentValue === type) { ctx.deleteCookie(typeCookie); } else { ctx.createCookie(typeCookie, type, 1); // Cookie can't be read immediately so we need to update CSS classes manually. $box.find('.snax-voting-' + type).addClass(classes.voted); } // Update score. var score = parseInt($box.find(selectors.scoreWrapper).data('snax-voting-score'), 10); ctx.createCookie(scoreCookie, score, 1); }; ctx.updateVoteScore = function($wrapper, score) { var $container = $wrapper.parents('.snax-voting'); score = parseInt(score, 10); var scoreShort = score; var units = ['', 'k', 'M']; var i; for (i = 0; scoreShort >= 1000; i++) { scoreShort /= 1000; } var scoreHtml = +scoreShort.toFixed(1) + units[i]; // Singular? if (1 === Math.abs(score)) { scoreHtml = ctx.config.i18n.points_singular_short_tpl.replace('%s', scoreHtml); } else { scoreHtml = ctx.config.i18n.points_plural_short_tpl.replace('%s', scoreHtml); } // Remove all score related classes. $container.removeClass('snax-voting-0 snax-voting-negative snax-voting-positive'); // Add score related classes. if (0 < score) { $container.addClass( 'snax-voting-positive' ); } else if (0 > score) { $container.addClass( 'snax-voting-negative' ); } else { $container.addClass( 'snax-voting-0' ); } $wrapper.data('snax-voting-score', score); $wrapper.html(scoreHtml); }; // fire $(document).ready(function () { ctx.votes(); }); })(jQuery, snax); /********************* * * Module: Login form * ********************/ (function ($, ctx) { 'use strict'; var selectors = { 'loginTab': '.snax-login-tab', 'loginFormWrapper': '.snax-login-form', 'loginForm': '.snax-login-form #loginform-in-popup', 'forgotTab': '.snax-forgot-pass-tab', 'forgotFormWrapper': '.snax-forgot-pass-form', 'forgotForm': '.snax-forgot-pass-form #lostpasswordform', 'gdprTab': '.snax-gdpr-tab', 'backToLoginTab': '.snax-back-to-login-tab', 'loginErrorMessage': '.snax-login-form .snax-login-error-message', 'forgotErrorMessage': '.snax-forgot-pass-form .snax-forgot-pass-error-message', 'forgotSuccessMessage': '.snax-forgot-pass-form .snax-forgot-pass-success-message', 'user': { 'loginInput': '#user_login', 'emailInput': '#user_email', 'passwordInput': '#user_pass' }, 'forgotPasswordLink': '#snax-popup-content .snax-link-forgot-pass', 'passwordWrapper': '#snax-popup-content .login-password', 'connectWithLabel': '#snax-popup-content .wp-social-login-connect-with', 'resetTab': '.snax-reset-tab' }; ctx.loginFormSelectors = selectors; var useReCaptcha; var reCaptchaToken; var urlAction = ctx.getUrlParameter(ctx.config.login_popup_url_var); ctx.loginForm = function () { useReCaptcha = ctx.config.use_login_recaptcha; // Add input placeholders. $.each(selectors.user, function (id, selector) { var $input = $(selector); var $label = $input.prev('label'); if ($label.length > 0) { $input.attr('placeholder', $label.text()); } }); // Move forgot link after password field. $(selectors.passwordWrapper + ' input').after( $(selectors.forgotPasswordLink) ); // Wrap label with

tag. $(selectors.connectWithLabel).wrapInner( '

' ); $('.wp-social-login-provider').on('click', function(e) { var $that = $(this); if ($('.snax-wpsl-gdpr-consent input').length > 0) { if (!$('.snax-wpsl-gdpr-consent input').is(':checked')) { e.stopPropagation(); e.stopImmediatePropagation(); e.preventDefault(); handleLoginGDPR($that); } } }); handleLoginAction(); handleForgotPassAction(); handleTabsSwitch(); if (urlAction==='reset_password'){ $(selectors.loginTab).removeClass('snax-tab-active').addClass('snax-tab-inactive'); $(selectors.resetTab).removeClass('snax-tab-inactive').addClass('snax-tab-active'); } if (urlAction==='forgot_password'){ $(selectors.loginTab).removeClass('snax-tab-active').addClass('snax-tab-inactive'); $(selectors.forgotTab).removeClass('snax-tab-inactive').addClass('snax-tab-active'); } $('body').on('snaxPopupOpened', function(e, action) { if (useReCaptcha && 'login' === action) { loadReCaptcha(); } }); }; var handleLoginGDPR = function($clickedProvider) { $(selectors.loginTab).removeClass('snax-tab-active').addClass('snax-tab-inactive'); $(selectors.gdprTab).removeClass('snax-tab-inactive').addClass('snax-tab-active'); $('.snax-login-gdpr-accept').on('click', function() { $('.snax-wpsl-gdpr-consent input').prop('checked', true); $(selectors.gdprTab).removeClass('snax-tab-active').addClass('snax-tab-inactive'); $(selectors.loginTab).removeClass('snax-tab-inactive').addClass('snax-tab-active'); var redirectTo = $clickedProvider.attr('href'); window.location.href = redirectTo; }); }; var handleLoginAction = function() { $(selectors.loginForm).on('submit', function(e) { e.preventDefault(); var $form = $(this); var $errorMessage = $(selectors.loginErrorMessage); var requestData = { 'action': 'snax_login' }; $.each($form.serializeArray(), function(i, field) { requestData[field.name] = field.value; }); // Read config directly, DO NOT use any reference. We change the value while auto logging. if (ctx.config.use_login_recaptcha) { if (!reCaptchaToken) { $errorMessage.html( '

' + ctx.config.i18n.recaptcha_invalid + '

'); return; } } // Clear error message. $errorMessage.html('

' + ctx.config.i18n.user_is_logging + '

'); var xhr = $.ajax({ 'type': 'POST', 'url': ctx.config.ajax_url, 'dataType': 'json', 'data': requestData }); xhr.done(function (res) { if ('success' === res.status) { var redirectTo = res.args.redirect_url; if (!redirectTo) { redirectTo = window.location.href; } if (redirectTo.indexOf('?') > 0){ redirectTo += '&' + ctx.config.login_success_var + '=true'; }else{ redirectTo += '?' + ctx.config.login_success_var + '=true'; } window.location.href = redirectTo; } else { if (res.message) { $errorMessage.html( '

' + res.message + '

'); } if (useReCaptcha) { grecaptcha.reset(); } } }); // Reload page if failed. xhr.fail(function() { var reloadUrl = window.location.href; if (reloadUrl.indexOf('?') > 0){ reloadUrl += '&' + ctx.config.login_success_var + '=false'; }else{ reloadUrl += '?' + ctx.config.login_success_var + '=false'; } window.location.href = reloadUrl; }); }); }; var handleForgotPassAction = function() { $(selectors.forgotForm).on('submit', function(e) { e.preventDefault(); var $form = $(this); var $errorMessage = $(selectors.forgotErrorMessage); var $successMessage = $(selectors.forgotSuccessMessage); var requestData = { 'action': 'snax_forgot_pass' }; $.each($form.serializeArray(), function(i, field) { requestData[field.name] = field.value; }); // Clear messages. $errorMessage.text(''); $successMessage.text(''); var xhr = $.ajax({ 'type': 'POST', 'url': ctx.config.ajax_url, 'dataType': 'json', 'data': requestData }); xhr.done(function (res) { if ('success' === res.status) { if (res.message) { $successMessage.html( '

' + res.message + '

'); } } else { if (res.message) { $errorMessage.html( '

' + res.message + '

'); } } }); }); }; var handleTabsSwitch = function() { $(selectors.forgotPasswordLink).on('click', function(e) { e.preventDefault(); $(selectors.loginTab).removeClass('snax-tab-active').addClass('snax-tab-inactive'); $(selectors.forgotTab).removeClass('snax-tab-inactive').addClass('snax-tab-active'); }); $(selectors.backToLoginTab).on('click', function(e) { e.preventDefault(); $(selectors.resetTab).removeClass('snax-tab-active').addClass('snax-tab-inactive'); $(selectors.forgotTab).removeClass('snax-tab-active').addClass('snax-tab-inactive'); $(selectors.loginTab).removeClass('snax-tab-inactive').addClass('snax-tab-active'); }); }; var loadReCaptcha = function() { var apiUrl = ctx.config.recaptcha_api_url; var ver = ctx.config.recaptcha_version; var siteKey = ctx.config.recaptcha_site_key; if (!siteKey || !apiUrl) { return; } var renderLoginReCaptcha = function() { try { if ('30' === ver) { grecaptcha.execute( siteKey, { action: 'login' } ).then( function( token ) { $('#snax-login-recaptcha').html(''); reCaptchaEnteredCorrectly(token); } ); } else { grecaptcha.render('snax-login-recaptcha', { 'sitekey' : siteKey, 'callback': reCaptchaEnteredCorrectly }); } } catch (error) {} }; // Google reCaptcha API loaded. if (typeof grecaptcha !== 'undefined') { renderLoginReCaptcha(); } else { // API not loaded. Register callback and load script. window.snaxReCaptchaOnloadCallback = function() { renderLoginReCaptcha(); }; if ('30' === ver) { $('head').append(' Image tag attributes: rel:animated_src - If this url is specified, it's loaded into the player instead of src. This allows a preview frame to be shown until animated gif data is streamed into the canvas rel:auto_play - Defaults to 1 if not specified. If set to zero, a call to the play() method is needed Constructor options args gif Required. The DOM element of an img tag. loop_mode Optional. Setting this to false will force disable looping of the gif. auto_play Optional. Same as the rel:auto_play attribute above, this arg overrides the img tag info. max_width Optional. Scale images over max_width down to max_width. Helpful with mobile. on_end Optional. Add a callback for when the gif reaches the end of a single loop (one iteration). The first argument passed will be the gif HTMLElement. loop_delay Optional. The amount of time to pause (in ms) after each single loop (iteration). draw_while_loading Optional. Determines whether the gif will be drawn to the canvas whilst it is loaded. show_progress_bar Optional. Only applies when draw_while_loading is set to true. Instance methods // loading load( callback ) Loads the gif specified by the src or rel:animated_src sttributie of the img tag into a canvas element and then calls callback if one is passed load_url( src, callback ) Loads the gif file specified in the src argument into a canvas element and then calls callback if one is passed // play controls play - Start playing the gif pause - Stop playing the gif move_to(i) - Move to frame i of the gif move_relative(i) - Move i frames ahead (or behind if i < 0) // getters get_canvas The canvas element that the gif is playing in. Handy for assigning event handlers to. get_playing Whether or not the gif is currently playing get_loading Whether or not the gif has finished loading/parsing get_auto_play Whether or not the gif is set to play automatically get_length The number of frames in the gif get_current_frame The index of the currently displayed frame of the gif For additional customization (viewport inside iframe) these params may be passed: c_w, c_h - width and height of canvas vp_t, vp_l, vp_ w, vp_h - top, left, width and height of the viewport A bonus: few articles to understand what is going on http://enthusiasms.org/post/16976438906 http://www.matthewflickinger.com/lab/whatsinagif/bits_and_bytes.asp http://humpy77.deviantart.com/journal/Frame-Delay-Times-for-Animated-GIFs-214150546 */ (function (root, factory) { if (typeof define === 'function' && define.amd) { define([], factory); } else if (typeof exports === 'object') { module.exports = factory(); } else { root.SuperGif = factory(); } }(this, function () { // Generic functions var bitsToNum = function (ba) { return ba.reduce(function (s, n) { return s * 2 + n; }, 0); }; var byteToBitArr = function (bite) { var a = []; for (var i = 7; i >= 0; i--) { a.push( !! (bite & (1 << i))); } return a; }; // Stream /** * @constructor */ // Make compiler happy. var Stream = function (data) { this.data = data; this.len = this.data.length; this.pos = 0; this.readByte = function () { if (this.pos >= this.data.length) { throw new Error('Attempted to read past end of stream.'); } if (data instanceof Uint8Array) return data[this.pos++]; else return data.charCodeAt(this.pos++) & 0xFF; }; this.readBytes = function (n) { var bytes = []; for (var i = 0; i < n; i++) { bytes.push(this.readByte()); } return bytes; }; this.read = function (n) { var s = ''; for (var i = 0; i < n; i++) { s += String.fromCharCode(this.readByte()); } return s; }; this.readUnsigned = function () { // Little-endian. var a = this.readBytes(2); return (a[1] << 8) + a[0]; }; }; var lzwDecode = function (minCodeSize, data) { // TODO: Now that the GIF parser is a bit different, maybe this should get an array of bytes instead of a String? var pos = 0; // Maybe this streaming thing should be merged with the Stream? var readCode = function (size) { var code = 0; for (var i = 0; i < size; i++) { if (data.charCodeAt(pos >> 3) & (1 << (pos & 7))) { code |= 1 << i; } pos++; } return code; }; var output = []; var clearCode = 1 << minCodeSize; var eoiCode = clearCode + 1; var codeSize = minCodeSize + 1; var dict = []; var clear = function () { dict = []; codeSize = minCodeSize + 1; for (var i = 0; i < clearCode; i++) { dict[i] = [i]; } dict[clearCode] = []; dict[eoiCode] = null; }; var code; var last; while (true) { last = code; code = readCode(codeSize); if (code === clearCode) { clear(); continue; } if (code === eoiCode) break; if (code < dict.length) { if (last !== clearCode) { dict.push(dict[last].concat(dict[code][0])); } } else { if (code !== dict.length) throw new Error('Invalid LZW code.'); dict.push(dict[last].concat(dict[last][0])); } output.push.apply(output, dict[code]); if (dict.length === (1 << codeSize) && codeSize < 12) { // If we're at the last code and codeSize is 12, the next code will be a clearCode, and it'll be 12 bits long. codeSize++; } } // I don't know if this is technically an error, but some GIFs do it. //if (Math.ceil(pos / 8) !== data.length) throw new Error('Extraneous LZW bytes.'); return output; }; // The actual parsing; returns an object with properties. var parseGIF = function (st, handler) { handler || (handler = {}); // LZW (GIF-specific) var parseCT = function (entries) { // Each entry is 3 bytes, for RGB. var ct = []; for (var i = 0; i < entries; i++) { ct.push(st.readBytes(3)); } return ct; }; var readSubBlocks = function () { var size, data; data = ''; do { size = st.readByte(); data += st.read(size); } while (size !== 0); return data; }; var parseHeader = function () { var hdr = {}; hdr.sig = st.read(3); hdr.ver = st.read(3); if (hdr.sig !== 'GIF') throw new Error('Not a GIF file.'); // XXX: This should probably be handled more nicely. hdr.width = st.readUnsigned(); hdr.height = st.readUnsigned(); var bits = byteToBitArr(st.readByte()); hdr.gctFlag = bits.shift(); hdr.colorRes = bitsToNum(bits.splice(0, 3)); hdr.sorted = bits.shift(); hdr.gctSize = bitsToNum(bits.splice(0, 3)); hdr.bgColor = st.readByte(); hdr.pixelAspectRatio = st.readByte(); // if not 0, aspectRatio = (pixelAspectRatio + 15) / 64 if (hdr.gctFlag) { hdr.gct = parseCT(1 << (hdr.gctSize + 1)); } handler.hdr && handler.hdr(hdr); }; var parseExt = function (block) { var parseGCExt = function (block) { var blockSize = st.readByte(); // Always 4 var bits = byteToBitArr(st.readByte()); block.reserved = bits.splice(0, 3); // Reserved; should be 000. block.disposalMethod = bitsToNum(bits.splice(0, 3)); block.userInput = bits.shift(); block.transparencyGiven = bits.shift(); block.delayTime = st.readUnsigned(); block.transparencyIndex = st.readByte(); block.terminator = st.readByte(); handler.gce && handler.gce(block); }; var parseComExt = function (block) { block.comment = readSubBlocks(); handler.com && handler.com(block); }; var parsePTExt = function (block) { // No one *ever* uses this. If you use it, deal with parsing it yourself. var blockSize = st.readByte(); // Always 12 block.ptHeader = st.readBytes(12); block.ptData = readSubBlocks(); handler.pte && handler.pte(block); }; var parseAppExt = function (block) { var parseNetscapeExt = function (block) { var blockSize = st.readByte(); // Always 3 block.unknown = st.readByte(); // ??? Always 1? What is this? block.iterations = st.readUnsigned(); block.terminator = st.readByte(); handler.app && handler.app.NETSCAPE && handler.app.NETSCAPE(block); }; var parseUnknownAppExt = function (block) { block.appData = readSubBlocks(); // FIXME: This won't work if a handler wants to match on any identifier. handler.app && handler.app[block.identifier] && handler.app[block.identifier](block); }; var blockSize = st.readByte(); // Always 11 block.identifier = st.read(8); block.authCode = st.read(3); switch (block.identifier) { case 'NETSCAPE': parseNetscapeExt(block); break; default: parseUnknownAppExt(block); break; } }; var parseUnknownExt = function (block) { block.data = readSubBlocks(); handler.unknown && handler.unknown(block); }; block.label = st.readByte(); switch (block.label) { case 0xF9: block.extType = 'gce'; parseGCExt(block); break; case 0xFE: block.extType = 'com'; parseComExt(block); break; case 0x01: block.extType = 'pte'; parsePTExt(block); break; case 0xFF: block.extType = 'app'; parseAppExt(block); break; default: block.extType = 'unknown'; parseUnknownExt(block); break; } }; var parseImg = function (img) { var deinterlace = function (pixels, width) { // Of course this defeats the purpose of interlacing. And it's *probably* // the least efficient way it's ever been implemented. But nevertheless... var newPixels = new Array(pixels.length); var rows = pixels.length / width; var cpRow = function (toRow, fromRow) { var fromPixels = pixels.slice(fromRow * width, (fromRow + 1) * width); newPixels.splice.apply(newPixels, [toRow * width, width].concat(fromPixels)); }; // See appendix E. var offsets = [0, 4, 2, 1]; var steps = [8, 8, 4, 2]; var fromRow = 0; for (var pass = 0; pass < 4; pass++) { for (var toRow = offsets[pass]; toRow < rows; toRow += steps[pass]) { cpRow(toRow, fromRow) fromRow++; } } return newPixels; }; img.leftPos = st.readUnsigned(); img.topPos = st.readUnsigned(); img.width = st.readUnsigned(); img.height = st.readUnsigned(); var bits = byteToBitArr(st.readByte()); img.lctFlag = bits.shift(); img.interlaced = bits.shift(); img.sorted = bits.shift(); img.reserved = bits.splice(0, 2); img.lctSize = bitsToNum(bits.splice(0, 3)); if (img.lctFlag) { img.lct = parseCT(1 << (img.lctSize + 1)); } img.lzwMinCodeSize = st.readByte(); var lzwData = readSubBlocks(); img.pixels = lzwDecode(img.lzwMinCodeSize, lzwData); if (img.interlaced) { // Move img.pixels = deinterlace(img.pixels, img.width); } handler.img && handler.img(img); }; var parseBlock = function () { var block = {}; block.sentinel = st.readByte(); switch (String.fromCharCode(block.sentinel)) { // For ease of matching case '!': block.type = 'ext'; parseExt(block); break; case ',': block.type = 'img'; parseImg(block); break; case ';': block.type = 'eof'; handler.eof && handler.eof(block); break; default: throw new Error('Unknown block: 0x' + block.sentinel.toString(16)); // TODO: Pad this with a 0. } if (block.type !== 'eof') setTimeout(parseBlock, 0); }; var parse = function () { parseHeader(); setTimeout(parseBlock, 0); }; parse(); }; var SuperGif = function ( opts ) { var options = { //viewport position vp_l: 0, vp_t: 0, vp_w: null, vp_h: null, //canvas sizes c_w: null, c_h: null }; for (var i in opts ) { options[i] = opts[i] } if (options.vp_w && options.vp_h) options.is_vp = true; var stream; var hdr; var loadError = null; var loading = false; var transparency = null; var delay = null; var disposalMethod = null; var disposalRestoreFromIdx = 0; var lastDisposalMethod = null; var frame = null; var lastImg = null; var playing = true; var forward = true; var ctx_scaled = false; var frames = []; var frameOffsets = []; // elements have .x and .y properties var gif = options.gif; if (typeof options.auto_play == 'undefined') options.auto_play = (!gif.getAttribute('rel:auto_play') || gif.getAttribute('rel:auto_play') == '1'); var onEndListener = (options.hasOwnProperty('on_end') ? options.on_end : null); var loopDelay = (options.hasOwnProperty('loop_delay') ? options.loop_delay : 0); var overrideLoopMode = (options.hasOwnProperty('loop_mode') ? options.loop_mode : 'auto'); var drawWhileLoading = (options.hasOwnProperty('draw_while_loading') ? options.draw_while_loading : true); var showProgressBar = drawWhileLoading ? (options.hasOwnProperty('show_progress_bar') ? options.show_progress_bar : true) : false; var clear = function () { transparency = null; delay = null; lastDisposalMethod = disposalMethod; disposalMethod = null; frame = null; }; // XXX: There's probably a better way to handle catching exceptions when // callbacks are involved. var doParse = function () { try { parseGIF(stream, handler); } catch (err) { doLoadError('parse'); } }; var doText = function (text) { toolbar.innerHTML = text; // innerText? Escaping? Whatever. toolbar.style.visibility = 'visible'; }; var setSizes = function(w, h) { canvas.width = w * get_canvas_scale(); canvas.height = h * get_canvas_scale(); toolbar.style.minWidth = ( w * get_canvas_scale() ) + 'px'; tmpCanvas.width = w; tmpCanvas.height = h; tmpCanvas.style.width = w + 'px'; tmpCanvas.style.height = h + 'px'; tmpCanvas.getContext('2d').setTransform(1, 0, 0, 1, 0, 0); }; var setFrameOffset = function(frame, offset) { if (!frameOffsets[frame]) { frameOffsets[frame] = offset; return; } if (typeof offset.x !== 'undefined') { frameOffsets[frame].x = offset.x; } if (typeof offset.y !== 'undefined') { frameOffsets[frame].y = offset.y; } }; var doShowProgress = function (pos, length, draw) { if (draw && showProgressBar) { var height = 25; var left, mid, top, width; if (options.is_vp) { if (!ctx_scaled) { top = (options.vp_t + options.vp_h - height); height = height; left = options.vp_l; mid = left + (pos / length) * options.vp_w; width = canvas.width; } else { top = (options.vp_t + options.vp_h - height) / get_canvas_scale(); height = height / get_canvas_scale(); left = (options.vp_l / get_canvas_scale() ); mid = left + (pos / length) * (options.vp_w / get_canvas_scale()); width = canvas.width / get_canvas_scale(); } //some debugging, draw rect around viewport if (false) { if (!ctx_scaled) { var l = options.vp_l, t = options.vp_t; var w = options.vp_w, h = options.vp_h; } else { var l = options.vp_l/get_canvas_scale(), t = options.vp_t/get_canvas_scale(); var w = options.vp_w/get_canvas_scale(), h = options.vp_h/get_canvas_scale(); } ctx.rect(l,t,w,h); ctx.stroke(); } } else { top = (canvas.height - height) / (ctx_scaled ? get_canvas_scale() : 1); mid = ((pos / length) * canvas.width) / (ctx_scaled ? get_canvas_scale() : 1); width = canvas.width / (ctx_scaled ? get_canvas_scale() : 1 ); height /= ctx_scaled ? get_canvas_scale() : 1; } // XXX Figure out alpha fillRect. //ctx.fillStyle = 'salmon'; ctx.fillStyle = 'rgba(255,255,255,0.4)'; ctx.fillRect(mid, top, width - mid, height); //ctx.fillStyle = 'teal'; ctx.fillStyle = 'rgba(255,0,22,.8)'; ctx.fillRect(0, top, mid, height); } }; var doLoadError = function (originOfError) { var drawError = function () { ctx.fillStyle = 'black'; ctx.fillRect(0, 0, options.c_w ? options.c_w : hdr.width, options.c_h ? options.c_h : hdr.height); ctx.strokeStyle = '`red`'; ctx.lineWidth = 3; ctx.moveTo(0, 0); ctx.lineTo(options.c_w ? options.c_w : hdr.width, options.c_h ? options.c_h : hdr.height); ctx.moveTo(0, options.c_h ? options.c_h : hdr.height); ctx.lineTo(options.c_w ? options.c_w : hdr.width, 0); ctx.stroke(); }; loadError = originOfError; hdr = { width: gif.width, height: gif.height }; // Fake header. frames = []; drawError(); }; var doHdr = function (_hdr) { hdr = _hdr; setSizes(hdr.width, hdr.height) }; var doGCE = function (gce) { pushFrame(); clear(); transparency = gce.transparencyGiven ? gce.transparencyIndex : null; delay = gce.delayTime; disposalMethod = gce.disposalMethod; // We don't have much to do with the rest of GCE. }; var pushFrame = function () { if (!frame) return; frames.push({ data: frame.getImageData(0, 0, hdr.width, hdr.height), delay: delay }); frameOffsets.push({ x: 0, y: 0 }); }; var doImg = function (img) { if (!frame) frame = tmpCanvas.getContext('2d'); var currIdx = frames.length; //ct = color table, gct = global color table var ct = img.lctFlag ? img.lct : hdr.gct; // TODO: What if neither exists? /* Disposal method indicates the way in which the graphic is to be treated after being displayed. Values : 0 - No disposal specified. The decoder is not required to take any action. 1 - Do not dispose. The graphic is to be left in place. 2 - Restore to background color. The area used by the graphic must be restored to the background color. 3 - Restore to previous. The decoder is required to restore the area overwritten by the graphic with what was there prior to rendering the graphic. Importantly, "previous" means the frame state after the last disposal of method 0, 1, or 2. */ if (currIdx > 0) { if (lastDisposalMethod === 3) { // Restore to previous frame.putImageData(frames[disposalRestoreFromIdx].data, 0, 0); } else { disposalRestoreFromIdx = currIdx - 1; } if (lastDisposalMethod === 2) { // Restore to background color // Browser implementations historically restore to transparent; we do the same. // http://www.wizards-toolkit.org/discourse-server/viewtopic.php?f=1&t=21172#p86079 frame.clearRect(lastImg.leftPos, lastImg.topPos, lastImg.width, lastImg.height); } } // else, Undefined/Do not dispose. // frame contains final pixel data from the last frame; do nothing //Get existing pixels for img region after applying disposal method var imgData = frame.getImageData(img.leftPos, img.topPos, img.width, img.height); //apply color table colors var cdd = imgData.data; img.pixels.forEach(function (pixel, i) { // imgData.data === [R,G,B,A,R,G,B,A,...] if (pixel !== transparency) { cdd[i * 4 + 0] = ct[pixel][0]; cdd[i * 4 + 1] = ct[pixel][1]; cdd[i * 4 + 2] = ct[pixel][2]; cdd[i * 4 + 3] = 255; // Opaque. } }); imgData.data.set(cdd); frame.putImageData(imgData, img.leftPos, img.topPos); if (!ctx_scaled) { ctx.scale(get_canvas_scale(),get_canvas_scale()); ctx_scaled = true; } // We could use the on-page canvas directly, except that we draw a progress // bar for each image chunk (not just the final image). if (drawWhileLoading) ctx.drawImage(tmpCanvas, 0, 0); lastImg = img; }; var player = (function () { var i = -1; var iterationCount = 0; var showingInfo = false; var pinned = false; /** * Gets the index of the frame "up next". * @returns {number} */ var getNextFrameNo = function () { var delta = (forward ? 1 : -1); return (i + delta + frames.length) % frames.length; }; var stepFrame = function (amount) { // XXX: Name is confusing. i = i + amount; putFrame(); }; var completeLoop = function () { if (onEndListener !== null) onEndListener(gif); iterationCount++; }; var step = (function () { var stepping = false; var doStep = function () { stepping = playing; if (!stepping) return; stepFrame(1); var delay = frames[i].delay * 10; if (!delay) delay = 100; // FIXME: Should this even default at all? What should it be? var nextFrameNo = getNextFrameNo(); if (nextFrameNo === 0) { delay += loopDelay; setTimeout(completeLoop, delay - 1); } if ((overrideLoopMode !== false || nextFrameNo !== 0 || iterationCount < 0)) setTimeout(doStep, delay); }; return function () { if (!stepping) setTimeout(doStep, 0); }; }()); var putFrame = function () { var offset; i = parseInt(i, 10); if (i > frames.length - 1){ i = 0; } if (i < 0){ i = 0; } offset = frameOffsets[i]; tmpCanvas.getContext("2d").putImageData(frames[i].data, offset.x, offset.y); ctx.globalCompositeOperation = "copy"; ctx.drawImage(tmpCanvas, 0, 0); }; var play = function () { playing = true; step(); }; var pause = function () { playing = false; }; return { init: function () { if (loadError) return; if ( ! (options.c_w && options.c_h) ) { ctx.scale(get_canvas_scale(),get_canvas_scale()); } if (options.auto_play) { step(); } else { i = 0; putFrame(); } }, step: step, play: play, pause: pause, playing: playing, move_relative: stepFrame, current_frame: function() { return i; }, length: function() { return frames.length }, move_to: function ( frame_idx ) { i = frame_idx; putFrame(); } } }()); var doDecodeProgress = function (draw) { doShowProgress(stream.pos, stream.data.length, draw); }; var doNothing = function () {}; /** * @param{boolean=} draw Whether to draw progress bar or not; this is not idempotent because of translucency. * Note that this means that the text will be unsynchronized with the progress bar on non-frames; * but those are typically so small (GCE etc.) that it doesn't really matter. TODO: Do this properly. */ var withProgress = function (fn, draw) { return function (block) { fn(block); doDecodeProgress(draw); }; }; var handler = { hdr: withProgress(doHdr), gce: withProgress(doGCE), com: withProgress(doNothing), // I guess that's all for now. app: { // TODO: Is there much point in actually supporting iterations? NETSCAPE: withProgress(doNothing) }, img: withProgress(doImg, true), eof: function (block) { //toolbar.style.display = ''; pushFrame(); doDecodeProgress(false); if ( ! (options.c_w && options.c_h) ) { canvas.width = hdr.width * get_canvas_scale(); canvas.height = hdr.height * get_canvas_scale(); } player.init(); loading = false; if (load_callback) { load_callback(gif); } } }; var init = function () { var parent = gif.parentNode; var div = document.createElement('div'); canvas = document.createElement('canvas'); ctx = canvas.getContext('2d'); toolbar = document.createElement('div'); tmpCanvas = document.createElement('canvas'); div.width = canvas.width = gif.width; div.height = canvas.height = gif.height; toolbar.style.minWidth = gif.width + 'px'; div.className = 'jsgif'; toolbar.className = 'jsgif_toolbar'; div.appendChild(canvas); div.appendChild(toolbar); parent.insertBefore(div, gif); parent.removeChild(gif); if (options.c_w && options.c_h) setSizes(options.c_w, options.c_h); initialized=true; }; var get_canvas_scale = function() { var scale; if (options.max_width && hdr && hdr.width > options.max_width) { scale = options.max_width / hdr.width; } else { scale = 1; } return scale; } var canvas, ctx, toolbar, tmpCanvas; var initialized = false; var load_callback = false; var load_setup = function(callback) { if (loading) return false; if (callback) load_callback = callback; else load_callback = false; loading = true; frames = []; clear(); disposalRestoreFromIdx = 0; lastDisposalMethod = null; frame = null; lastImg = null; return true; } return { // play controls play: player.play, pause: player.pause, move_relative: player.move_relative, move_to: player.move_to, // getters for instance vars get_playing : function() { return player.playing }, get_canvas : function() { return canvas }, get_canvas_scale : function() { return get_canvas_scale() }, get_loading : function() { return loading }, get_auto_play : function() { return options.auto_play }, get_length : function() { return player.length() }, get_current_frame: function() { return player.current_frame() }, load_url: function(src,callback){ if (!load_setup(callback)) return; var h = new XMLHttpRequest(); h.overrideMimeType('text/plain; charset=x-user-defined'); h.onloadstart = function() { // Wait until connection is opened to replace the gif element with a canvas to avoid a blank img if (!initialized) init(); }; h.onload = function(e) { stream = new Stream(h.responseText); setTimeout(doParse, 0); }; h.onprogress = function (e) { if (e.lengthComputable) doShowProgress(e.loaded, e.total, true); }; h.onerror = function() { doLoadError('xhr'); }; h.open('GET', src, true); h.send(); }, load: function (callback) { this.load_url(gif.getAttribute('rel:animated_src') || gif.src,callback); }, load_raw: function(arr, callback) { if (!load_setup(callback)) return; if (!initialized) init(); stream = new Stream(arr); setTimeout(doParse, 0); }, set_frame_offset: setFrameOffset }; }; return SuperGif; })); ; /****************** * * Init GIF Player * *****************/ (function ($) { 'use strict'; var isEnabled = g1.config.use_gif_player; g1.gifPlayer = function ($scope) { if ( ! isEnabled ) { return; } if (! $scope ) { $scope = $('body'); } // SuperGif library depends on the overrideMimeType method of the XMLHttpRequest object // if browser doesn't support this method, we can't use that library if ( typeof XMLHttpRequest.prototype.overrideMimeType === 'undefined' ) { return; } g1.gifPlayerIncludeSelectors =[ '.entry-content img.aligncenter[src$=".gif"]', '.entry-content .aligncenter img[src$=".gif"]', 'img.g1-enable-gif-player', '.entry-featured-media-main img[src$=".gif"]', '.entry-tpl-stream .entry-featured-media img[src$=".gif"]', '.entry-tpl-grid-l .entry-featured-media img[src$=".gif"]' ]; g1.gifPlayerExcludeSelectors = [ '.ajax-loader', // for Contact Form 7 '.g1-disable-gif-player', '.wp-block-image.g1-disable-gif-player img[src$=".gif"]' ]; $( g1.gifPlayerIncludeSelectors.join(','), $scope ).not( g1.gifPlayerExcludeSelectors.join(',') ).each(function () { var $img = $(this); var imgClasses = $img.attr('class'); var imgSrc = $img.attr('src'); // Check only absolute paths. Relative paths, by nature, are from the same domain. // Seems like the GIFs from outside of the site's domain work too. // if (-1 !== imgSrc.indexOf('http')) { // // Only locally stored gifs, unless user decided otherwise. // if (imgSrc.indexOf(location.hostname) === -1 && !$img.is('.g1-enable-gif-player')) { // return; // } // } var gifObj = new SuperGif({ gif: this, auto_play: 0 }); var $gitIndicator = $(''); gifObj.load(function() { var frames = gifObj.get_length(); var $canvasWrapper = $(gifObj.get_canvas()).parent(); // Only for animated gifs. if (frames > 1) { gifObj.isPlaying = false; // Store references to original methods. var playRef = gifObj.play; var pauseRef = gifObj.pause; var playGif = function() { playRef(); gifObj.isPlaying = true; $gitIndicator.addClass('g1-indicator-gif-playing'); }; var pauseGif = function() { pauseRef(); gifObj.isPlaying = false; $gitIndicator.removeClass('g1-indicator-gif-playing'); }; // Override and extend the API. gifObj.play = playGif; gifObj.pause = pauseGif; // Play/stop the GIF. $canvasWrapper.on('click', function(e) { // Prevent redirecting to single post. e.preventDefault(); if (gifObj.isPlaying) { pauseGif(); } else { playGif(); } }); $gitIndicator.toggleClass('g1-loading g1-loaded'); $(document).trigger('bimberGifPlayerLoaded', [$canvasWrapper]); } else { // It's just a gif type image, not animation to play. $gitIndicator.remove(); } }); // canvas parent can be fetched after gifObj.load() call var $canvasWrapper = $(gifObj.get_canvas()).parent(); $canvasWrapper. addClass(imgClasses + ' g1-enable-share-links'). attr('data-img-src', imgSrc). append($gitIndicator). data('gifPlayer', gifObj); }); }; // Listeners. $('body').on('g1NewContentLoaded', function(e, $newContent) { g1.gifPlayer($newContent); }); })(jQuery); /************************ * * Media Players Factory * ***********************/ (function ($) { 'use strict'; var selectors = { 'iframe': 'iframe', 'mp4': '.mejs-video', 'gif': '.jsgif', 'html5Video': '.snax-native-video', 'embedly': '.embedly-card iframe', 'maceYT': '.mace-youtube' }; g1.mediaPlayers = {}; g1.getMediaPlayer = function(element) { var player = $(element).data('g1MediaPlayer'); if (player) { g1.log('Returning a player (' + player.getType() + ') assigned to the element.'); return player; } // IFRAME. var $iframe = $(selectors.iframe, element); if ($iframe.length > 0) { var iframesrc = false; if ($iframe.attr('data-src')) { iframesrc = $iframe.attr('data-src'); } else { iframesrc= $iframe.attr('src'); } if (iframesrc) { // YouTube? if (iframesrc.indexOf('youtu') > 0) { player = g1.mediaPlayers.youtube($iframe); $(element).data('g1MediaPlayer', player); return player; } // Vimeo? if (iframesrc.indexOf('vimeo') > 0) { player = g1.mediaPlayers.vimeo($iframe); $(element).data('g1MediaPlayer', player); return player; } // Dailymotion? if (iframesrc.indexOf('dailymotion') > 0) { player = g1.mediaPlayers.dailymotion($iframe); $(element).data('g1MediaPlayer', player); return player; } // Gfycat? if (iframesrc.indexOf('gfycat') > 0) { player = g1.mediaPlayers.gfycat($iframe); $(element).data('g1MediaPlayer', player); return player; } } return false; } // MP4. var $mp4 = $(selectors.mp4, element); if ($mp4.length > 0) { var playerId = $mp4.attr('id'); if (playerId && mejs && typeof mejs.players !== 'undefined') { if (typeof mejs.players[playerId] !== 'undefined') { var mejsPlayer = mejs.players[playerId]; player = g1.mediaPlayers.mp4(mejsPlayer); $(element).data('g1MediaPlayer', player); return player; } } return false; } // GIF. var $gif = $(selectors.gif, element); if ($gif.length > 0) { var gifPlayer = $gif.data('gifPlayer'); if (gifPlayer) { player = g1.mediaPlayers.gif(gifPlayer); $(element).data('g1MediaPlayer', player); return player; } return false; } // MediaAce Lazy Loaded video. var $maceYT = $(selectors.maceYT, element); // HTML5 native videos. var $html5 = $(selectors.html5Video, element); if ( $html5.length > 0 ) { player = g1.mediaPlayers.html5video($html5[0]); $(element).data('g1MediaPlayer', player); return player; } // Embedly. if (typeof embedly !== 'undefined') { var $embedly = $(selectors.embedly, element); if ($embedly.length > 0 ) { // The following iterates over all the instances of the player. embedly('player', function(embedlyPlayer){ if ($embedly[0] === $(embedlyPlayer.frame.elem)[0]) { player = g1.mediaPlayers.embedly(embedlyPlayer); $(element).data('g1MediaPlayer', player); return player; } else { player.pause(); } }); return false; } else { embedly('player', function(player){ player.pause(); }); } } // MediaAce YouTube lazy loader. if ($maceYT.length > 0) { // Start to load YouTube player. $maceYT.find('.mace-play-button').trigger('click'); // YouTube player (iframe) loaded. $maceYT.on('maceIframeLoaded', function(e, $iframe) { // Get YT player to initialize YT properly. player = g1.getMediaPlayer($maceYT); // Assign the player to the element. $(element).data('g1MediaPlayer', player); }); // We don't want to return an instance of the MaceYT player here, as the MaceYT is just a wrapper for YT player. // So we return false here and wait for YT iframe. When it's loaded, we assigned the YT player to the element. return false; } }; })(jQuery); /******************* * * YouTube Player * ******************/ (function ($) { 'use strict'; g1.mediaPlayers.youtube = function ($iframe) { let obj = {}; let isPlaying = false; function init() { g1.log('YouTube player object initialized'); $iframe.on('load', function() { // Mute on load. $iframe[0].contentWindow.postMessage(JSON.stringify({ 'event': 'command', 'func': 'mute', 'args': ''}), '*'); }); let iframesrc = ''; let separator = '?'; if ($iframe.attr('data-src')) { iframesrc = $iframe.attr('data-src'); } else { iframesrc = $iframe.attr('src'); } if (iframesrc.indexOf('?') > 0){ separator = '&'; } // Trigger the "load" event, with new params. $iframe.attr('src', iframesrc + separator + 'autoplay=1&enablejsapi=1&loop=1'); return obj; } obj.getType = function() { return 'YouTube'; }; obj.play = function () { $iframe[0].contentWindow.postMessage(JSON.stringify({ 'event': 'command', 'func': 'playVideo', 'args': ''}), '*'); isPlaying = true; }; obj.pause = function () { $iframe[0].contentWindow.postMessage(JSON.stringify({ 'event': 'command', 'func': 'pauseVideo', 'args': ''}), '*'); isPlaying = false; }; obj.isPlaying = function() { return isPlaying; }; return init(); }; })(jQuery); /******************* * * Vimoe Player * ******************/ (function ($) { 'use strict'; g1.mediaPlayers.vimeo = function ($iframe) { let obj = {}; let isPlaying = false; function init() { g1.log('Vimeo player object initialized'); $iframe.on('load', function() { $iframe[0].contentWindow.postMessage(JSON.stringify({ method: 'setVolume', value: 0 }), '*'); }); let iframesrc = ''; let separator = '?'; if ($iframe.attr('data-src')) { iframesrc = $iframe.attr('data-src'); } else { iframesrc = $iframe.attr('src'); } if (iframesrc.indexOf('?') > 0){ separator = '&'; } $iframe.attr('src', iframesrc + separator + 'autoplay=1&autopause=0'); return obj; } obj.getType = function() { return 'Vimeo'; }; obj.play = function () { $iframe[0].contentWindow.postMessage(JSON.stringify({ method: 'play' }), '*'); isPlaying = true; }; obj.pause = function () { $iframe[0].contentWindow.postMessage(JSON.stringify({ method: 'pause' }), '*'); isPlaying = false; }; obj.isPlaying = function() { return isPlaying; }; return init(); }; })(jQuery); /******************* * * DailyMotion Player * ******************/ (function ($) { 'use strict'; g1.mediaPlayers.dailymotion = function ($iframe) { let obj = {}; let isPlaying = false; function init() { g1.log('DailyMotion player object initialized'); // Mute on load. let iframesrc = ''; let separator = '?'; if ($iframe.attr('data-src')) { iframesrc = $iframe.attr('data-src'); } else { iframesrc = $iframe.attr('src'); } if (iframesrc.indexOf('?') > 0){ separator = '&'; } $iframe.attr('src', iframesrc + separator + 'autoplay=1&api=postMessage&mute=1'); return obj; } obj.getType = function() { return 'DailyMotion'; }; obj.play = function () { $iframe[0].contentWindow.postMessage('play', '*'); isPlaying = true; }; obj.pause = function () { $iframe[0].contentWindow.postMessage('pause', '*'); isPlaying = false; }; obj.isPlaying = function() { return isPlaying; }; return init(); }; })(jQuery); /******************* * * Gfycat Player * ******************/ (function ($) { 'use strict'; g1.mediaPlayers.gfycat = function ($iframe) { let obj = {}; let isPlaying = false; function init() { g1.log('Gfycat player object initialized'); return obj; } obj.getType = function() { return 'Gfycat'; }; obj.play = function () { $iframe[0].contentWindow.postMessage('play', '*'); isPlaying = true; }; obj.pause = function () { $iframe[0].contentWindow.postMessage('pause', '*'); isPlaying = false; }; obj.isPlaying = function() { return isPlaying; }; return init(); }; })(jQuery); /******************* * * MP4 Player * ******************/ (function ($) { 'use strict'; g1.mediaPlayers.mp4 = function (mejsPlayer) { let obj = {}; let isPlaying = false; function init() { g1.log('MP4 player initialized'); // Start muted. mejsPlayer.setMuted(true); // Play in loop. mejsPlayer.media.addEventListener('ended', function() { mejsPlayer.play(); }, false); return obj; } obj.getType = function() { return 'MP4'; }; obj.play = function() { mejsPlayer.play(); isPlaying = true; }; obj.pause = function() { mejsPlayer.pause(); isPlaying = false; }; obj.isPlaying = function() { return isPlaying; }; return init(); }; })(jQuery); /******************* * * GIF Player * ******************/ (function ($) { 'use strict'; g1.mediaPlayers.gif = function (gifPlayer) { let obj = {}; function init() { g1.log('GIF player initialized'); return obj; } obj.getType = function() { return 'GIF'; }; obj.play = function() { gifPlayer.play(); }; obj.pause = function() { gifPlayer.pause(); }; obj.isPlaying = function() { return gifPlayer.isPlaying; }; return init(); }; })(jQuery); /******************* * * HTML Video Player * ******************/ (function ($) { 'use strict'; g1.mediaPlayers.html5video = function (video) { let obj = {}; let isPlaying = false; function init() { g1.log('HTML5 Video player initialized'); return obj; } obj.getType = function() { return 'HTML5 Video'; }; obj.play = function() { video.play(); isPlaying = true; }; obj.pause = function() { video.pause(); isPlaying = false; }; obj.isPlaying = function() { return isPlaying; }; return init(); }; })(jQuery); /******************* * * Embedly Player * ******************/ (function ($) { 'use strict'; g1.mediaPlayers.embedly = function (embedlyPlayer) { let obj = {}; let isPlaying = false; function init() { g1.log('Embedly player initialized'); embedlyPlayer.mute(); return obj; } obj.getType = function() { return 'Embedly'; }; obj.play = function() { embedlyPlayer.play(); isPlaying = true; }; obj.pause = function() { embedlyPlayer.pause(); isPlaying = false; }; obj.isPlaying = function() { return isPlaying; }; return init(); }; })(jQuery); /********************** /********************** * * Auto Play Controller * ********************** **********************/ (function ($) { 'use strict'; var selectors = { 'postMedia': '.archive-body-stream .entry-tpl-stream .entry-featured-media:not(.entry-media-nsfw-embed)' }; // Due to varied autoplay browsers' policies, it's almost impossible to guarantee autoplying on mobiles, so we turn it off. g1.isAutoPlayEnabled = g1.config.auto_play_videos && ! g1.isTouchDevice(); var players = {}; // Initialized players. g1.autoPlayVideo = function () { if ( ! g1.isAutoPlayEnabled ) { return; } var pauseAllVideos = function() { g1.log('Pausing all videos'); for(var i in players) { players[i].pause(); } }; var play = function(element) { var postId = $(element).parents('article').attr('id'); g1.log('Trying to play media...'); var player = g1.getMediaPlayer(element); if (!player) { g1.log('Media player not defined for the element'); return; } // Before playing this video we want to make sure that others video are paused too. pauseAllVideos(); player.play(); g1.log(player.getType() + ' played'); // Store reference. if (!players[postId]) { players[postId] = player; } }; var pause = function (element) { g1.log('Trying to pause media...'); var player = g1.getMediaPlayer(element); if (!player) { g1.log('Media player not defined for the element'); return; } player.pause(); g1.log(player.getType() + ' paused'); }; var bindEvents = function() { // Delay waypoint. User scroll activate events. var scrollEvents = 0; var allowPlaying = false; // Wait for user scroll. Not scroll event while page loading. $(document).scroll(function() { scrollEvents++; if (scrollEvents > 5) { allowPlaying = true; } }); // ENTER, while up to down scrolling. $(selectors.postMedia).waypoint(function(direction) { if ('down' === direction) { if (allowPlaying) { g1.log([ '>>> ENTER post (direction: DOWN)', this.element ] ); play(this.element); } } }, { // When the bottom of the element hits the bottom of the viewport. offset: 'bottom-in-view' }); // ENTER, while down to up scrolling. $(selectors.postMedia).waypoint(function(direction) { if ('up' === direction) { if (allowPlaying) { g1.log([ '>>> ENTER post (direction: UP)', this.element ] ); play(this.element); } } }, { // When the top of the element hits the top of the viewport. offset: '0' }); // EXIT, while up to down scrolling. $(selectors.postMedia).waypoint(function(direction) { if ('down' === direction) { g1.log([ '>>> EXIT post (direction: DOWN)', this.element ] ); pause(this.element); } }, { offset: function() { // Fires when top of the element is (HALF OF ELEMENT HEIGHT)px from the top of the window. return -Math.round(this.element.clientHeight / 2); } }); // EXIT, while down to up scrolling. $(selectors.postMedia).waypoint(function(direction) { if ('up' === direction) { g1.log([ '>>> EXIT post (direction: UP)', this.element ] ); pause(this.element); } }, { offset: function() { var viewportHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0); // Fires when top of the element is (HALF OF ELEMENT HEIGHT)px from the bottom of the window. return viewportHeight - Math.round(this.element.clientHeight / 2); } }); // Play on demand. $(selectors.postMedia).on('bimber:play', function() { g1.log([ '>>> PLAY ', $(this).get(0) ] ); play($(this).get(0)); }); // Pause on demand. $(selectors.postMedia).on('bimber:pause', function() { g1.log([ '>>> PAUSE ', $(this).get(0) ] ); pause($(this).get(0)); }); }; bindEvents(); }; })(jQuery); /************************** * * document ready functions (keep this at the end for better compatibillity with optimizing plugins) * *************************/ (function ($) { 'use strict'; $(document).ready(function () { // Init GIF player. g1.gifPlayer(); // Init videos auto load on scroll. g1.autoPlayVideo(); }); })(jQuery);; /*! jQuery UI - v1.13.3 - 2024-04-26 * https://jqueryui.com * Includes: widget.js, position.js, data.js, disable-selection.js, effect.js, effects/effect-blind.js, effects/effect-bounce.js, effects/effect-clip.js, effects/effect-drop.js, effects/effect-explode.js, effects/effect-fade.js, effects/effect-fold.js, effects/effect-highlight.js, effects/effect-puff.js, effects/effect-pulsate.js, effects/effect-scale.js, effects/effect-shake.js, effects/effect-size.js, effects/effect-slide.js, effects/effect-transfer.js, focusable.js, form-reset-mixin.js, jquery-patch.js, keycode.js, labels.js, scroll-parent.js, tabbable.js, unique-id.js, widgets/accordion.js, widgets/autocomplete.js, widgets/button.js, widgets/checkboxradio.js, widgets/controlgroup.js, widgets/datepicker.js, widgets/dialog.js, widgets/draggable.js, widgets/droppable.js, widgets/menu.js, widgets/mouse.js, widgets/progressbar.js, widgets/resizable.js, widgets/selectable.js, widgets/selectmenu.js, widgets/slider.js, widgets/sortable.js, widgets/spinner.js, widgets/tabs.js, widgets/tooltip.js * Copyright jQuery Foundation and other contributors; Licensed MIT */ !function(t){"use strict";"function"==typeof define&&define.amd?define(["jquery"],t):t(jQuery)}(function(x){"use strict";var t,e,i,n,W,C,o,s,r,l,a,h,u;function E(t,e,i){return[parseFloat(t[0])*(a.test(t[0])?e/100:1),parseFloat(t[1])*(a.test(t[1])?i/100:1)]}function L(t,e){return parseInt(x.css(t,e),10)||0}function N(t){return null!=t&&t===t.window}x.ui=x.ui||{},x.ui.version="1.13.3", /*! * jQuery UI :data 1.13.3 * https://jqueryui.com * * Copyright OpenJS Foundation and other contributors * Released under the MIT license. * https://jquery.org/license */ x.extend(x.expr.pseudos,{data:x.expr.createPseudo?x.expr.createPseudo(function(e){return function(t){return!!x.data(t,e)}}):function(t,e,i){return!!x.data(t,i[3])}}), /*! * jQuery UI Disable Selection 1.13.3 * https://jqueryui.com * * Copyright OpenJS Foundation and other contributors * Released under the MIT license. * https://jquery.org/license */ x.fn.extend({disableSelection:(t="onselectstart"in document.createElement("div")?"selectstart":"mousedown",function(){return this.on(t+".ui-disableSelection",function(t){t.preventDefault()})}),enableSelection:function(){return this.off(".ui-disableSelection")}}), /*! * jQuery UI Focusable 1.13.3 * https://jqueryui.com * * Copyright OpenJS Foundation and other contributors * Released under the MIT license. * https://jquery.org/license */ x.ui.focusable=function(t,e){var i,n,o,s=t.nodeName.toLowerCase();return"area"===s?(o=(i=t.parentNode).name,!(!t.href||!o||"map"!==i.nodeName.toLowerCase())&&0<(i=x("img[usemap='#"+o+"']")).length&&i.is(":visible")):(/^(input|select|textarea|button|object)$/.test(s)?(n=!t.disabled)&&(o=x(t).closest("fieldset")[0])&&(n=!o.disabled):n="a"===s&&t.href||e,n&&x(t).is(":visible")&&function(t){var e=t.css("visibility");for(;"inherit"===e;)t=t.parent(),e=t.css("visibility");return"visible"===e}(x(t)))},x.extend(x.expr.pseudos,{focusable:function(t){return x.ui.focusable(t,null!=x.attr(t,"tabindex"))}}),x.fn._form=function(){return"string"==typeof this[0].form?this.closest("form"):x(this[0].form)}, /*! * jQuery UI Form Reset Mixin 1.13.3 * https://jqueryui.com * * Copyright OpenJS Foundation and other contributors * Released under the MIT license. * https://jquery.org/license */ x.ui.formResetMixin={_formResetHandler:function(){var e=x(this);setTimeout(function(){var t=e.data("ui-form-reset-instances");x.each(t,function(){this.refresh()})})},_bindFormResetHandler:function(){var t;this.form=this.element._form(),this.form.length&&((t=this.form.data("ui-form-reset-instances")||[]).length||this.form.on("reset.ui-form-reset",this._formResetHandler),t.push(this),this.form.data("ui-form-reset-instances",t))},_unbindFormResetHandler:function(){var t;this.form.length&&((t=this.form.data("ui-form-reset-instances")).splice(x.inArray(this,t),1),t.length?this.form.data("ui-form-reset-instances",t):this.form.removeData("ui-form-reset-instances").off("reset.ui-form-reset"))}},x.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase()), /*! * jQuery UI Support for jQuery core 1.8.x and newer 1.13.3 * https://jqueryui.com * * Copyright OpenJS Foundation and other contributors * Released under the MIT license. * https://jquery.org/license * */ x.expr.pseudos||(x.expr.pseudos=x.expr[":"]),x.uniqueSort||(x.uniqueSort=x.unique),x.escapeSelector||(e=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\x80-\uFFFF\w-]/g,i=function(t,e){return e?"\0"===t?"�":t.slice(0,-1)+"\\"+t.charCodeAt(t.length-1).toString(16)+" ":"\\"+t},x.escapeSelector=function(t){return(t+"").replace(e,i)}),x.fn.even&&x.fn.odd||x.fn.extend({even:function(){return this.filter(function(t){return t%2==0})},odd:function(){return this.filter(function(t){return t%2==1})}}), /*! * jQuery UI Keycode 1.13.3 * https://jqueryui.com * * Copyright OpenJS Foundation and other contributors * Released under the MIT license. * https://jquery.org/license */ x.ui.keyCode={BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38}, /*! * jQuery UI Labels 1.13.3 * https://jqueryui.com * * Copyright OpenJS Foundation and other contributors * Released under the MIT license. * https://jquery.org/license */ x.fn.labels=function(){var t,e,i;return this.length?this[0].labels&&this[0].labels.length?this.pushStack(this[0].labels):(e=this.eq(0).parents("label"),(t=this.attr("id"))&&(i=(i=this.eq(0).parents().last()).add((i.length?i:this).siblings()),t="label[for='"+x.escapeSelector(t)+"']",e=e.add(i.find(t).addBack(t))),this.pushStack(e)):this.pushStack([])},x.ui.plugin={add:function(t,e,i){var n,o=x.ui[t].prototype;for(n in i)o.plugins[n]=o.plugins[n]||[],o.plugins[n].push([e,i[n]])},call:function(t,e,i,n){var o,s=t.plugins[e];if(s&&(n||t.element[0].parentNode&&11!==t.element[0].parentNode.nodeType))for(o=0;o
")).children()[0],x("body").append(e),t=i.offsetWidth,e.css("overflow","scroll"),t===(i=i.offsetWidth)&&(i=e[0].clientWidth),e.remove(),n=t-i)},getScrollInfo:function(t){var e=t.isWindow||t.isDocument?"":t.element.css("overflow-x"),i=t.isWindow||t.isDocument?"":t.element.css("overflow-y"),e="scroll"===e||"auto"===e&&t.widthW(C(n),C(o))?s.important="horizontal":s.important="vertical",f.using.call(this,t,s)}),r.offset(x.extend(h,{using:t}))})):h.apply(this,arguments)},x.ui.position={fit:{left:function(t,e){var i,n=e.within,o=n.isWindow?n.scrollLeft:n.offset.left,n=n.width,s=t.left-e.collisionPosition.marginLeft,r=o-s,l=s+e.collisionWidth-n-o;n",options:{classes:{},disabled:!1,create:null},_createWidget:function(t,e){e=x(e||this.defaultElement||this)[0],this.element=x(e),this.uuid=c++,this.eventNamespace="."+this.widgetName+this.uuid,this.bindings=x(),this.hoverable=x(),this.focusable=x(),this.classesElementLookup={},e!==this&&(x.data(e,this.widgetFullName,this),this._on(!0,this.element,{remove:function(t){t.target===e&&this.destroy()}}),this.document=x(e.style?e.ownerDocument:e.document||e),this.window=x(this.document[0].defaultView||this.document[0].parentWindow)),this.options=x.widget.extend({},this.options,this._getCreateOptions(),t),this._create(),this.options.disabled&&this._setOptionDisabled(this.options.disabled),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:function(){return{}},_getCreateEventData:x.noop,_create:x.noop,_init:x.noop,destroy:function(){var i=this;this._destroy(),x.each(this.classesElementLookup,function(t,e){i._removeClass(e,t)}),this.element.off(this.eventNamespace).removeData(this.widgetFullName),this.widget().off(this.eventNamespace).removeAttr("aria-disabled"),this.bindings.off(this.eventNamespace)},_destroy:x.noop,widget:function(){return this.element},option:function(t,e){var i,n,o,s=t;if(0===arguments.length)return x.widget.extend({},this.options);if("string"==typeof t)if(s={},t=(i=t.split(".")).shift(),i.length){for(n=s[t]=x.widget.extend({},this.options[t]),o=0;o",delay:300,options:{icons:{submenu:"ui-icon-caret-1-e"},items:"> *",menus:"ul",position:{my:"left top",at:"right top"},role:"menu",blur:null,focus:null,select:null},_create:function(){this.activeMenu=this.element,this.mouseHandled=!1,this.lastMousePosition={x:null,y:null},this.element.uniqueId().attr({role:this.options.role,tabIndex:0}),this._addClass("ui-menu","ui-widget ui-widget-content"),this._on({"mousedown .ui-menu-item":function(e){e.preventDefault(),this._activateItem(e)},"click .ui-menu-item":function(e){var t=a(e.target),i=a(a.ui.safeActiveElement(this.document[0]));!this.mouseHandled&&t.not(".ui-state-disabled").length&&(this.select(e),e.isPropagationStopped()||(this.mouseHandled=!0),t.has(".ui-menu").length?this.expand(e):!this.element.is(":focus")&&i.closest(".ui-menu").length&&(this.element.trigger("focus",[!0]),this.active)&&1===this.active.parents(".ui-menu").length&&clearTimeout(this.timer))},"mouseenter .ui-menu-item":"_activateItem","mousemove .ui-menu-item":"_activateItem",mouseleave:"collapseAll","mouseleave .ui-menu":"collapseAll",focus:function(e,t){var i=this.active||this._menuItems().first();t||this.focus(e,i)},blur:function(e){this._delay(function(){a.contains(this.element[0],a.ui.safeActiveElement(this.document[0]))||this.collapseAll(e)})},keydown:"_keydown"}),this.refresh(),this._on(this.document,{click:function(e){this._closeOnDocumentClick(e)&&this.collapseAll(e,!0),this.mouseHandled=!1}})},_activateItem:function(e){var t,i;this.previousFilter||e.clientX===this.lastMousePosition.x&&e.clientY===this.lastMousePosition.y||(this.lastMousePosition={x:e.clientX,y:e.clientY},t=a(e.target).closest(".ui-menu-item"),i=a(e.currentTarget),t[0]!==i[0])||i.is(".ui-state-active")||(this._removeClass(i.siblings().children(".ui-state-active"),null,"ui-state-active"),this.focus(e,i))},_destroy:function(){var e=this.element.find(".ui-menu-item").removeAttr("role aria-disabled").children(".ui-menu-item-wrapper").removeUniqueId().removeAttr("tabIndex role aria-haspopup");this.element.removeAttr("aria-activedescendant").find(".ui-menu").addBack().removeAttr("role aria-labelledby aria-expanded aria-hidden aria-disabled tabIndex").removeUniqueId().show(),e.children().each(function(){var e=a(this);e.data("ui-menu-submenu-caret")&&e.remove()})},_keydown:function(e){var t,i,s,n=!0;switch(e.keyCode){case a.ui.keyCode.PAGE_UP:this.previousPage(e);break;case a.ui.keyCode.PAGE_DOWN:this.nextPage(e);break;case a.ui.keyCode.HOME:this._move("first","first",e);break;case a.ui.keyCode.END:this._move("last","last",e);break;case a.ui.keyCode.UP:this.previous(e);break;case a.ui.keyCode.DOWN:this.next(e);break;case a.ui.keyCode.LEFT:this.collapse(e);break;case a.ui.keyCode.RIGHT:this.active&&!this.active.is(".ui-state-disabled")&&this.expand(e);break;case a.ui.keyCode.ENTER:case a.ui.keyCode.SPACE:this._activate(e);break;case a.ui.keyCode.ESCAPE:this.collapse(e);break;default:t=this.previousFilter||"",s=n=!1,i=96<=e.keyCode&&e.keyCode<=105?(e.keyCode-96).toString():String.fromCharCode(e.keyCode),clearTimeout(this.filterTimer),i===t?s=!0:i=t+i,t=this._filterMenuItems(i),(t=s&&-1!==t.index(this.active.next())?this.active.nextAll(".ui-menu-item"):t).length||(i=String.fromCharCode(e.keyCode),t=this._filterMenuItems(i)),t.length?(this.focus(e,t),this.previousFilter=i,this.filterTimer=this._delay(function(){delete this.previousFilter},1e3)):delete this.previousFilter}n&&e.preventDefault()},_activate:function(e){this.active&&!this.active.is(".ui-state-disabled")&&(this.active.children("[aria-haspopup='true']").length?this.expand(e):this.select(e))},refresh:function(){var e,t,s=this,n=this.options.icons.submenu,i=this.element.find(this.options.menus);this._toggleClass("ui-menu-icons",null,!!this.element.find(".ui-icon").length),e=i.filter(":not(.ui-menu)").hide().attr({role:this.options.role,"aria-hidden":"true","aria-expanded":"false"}).each(function(){var e=a(this),t=e.prev(),i=a("").data("ui-menu-submenu-caret",!0);s._addClass(i,"ui-menu-icon","ui-icon "+n),t.attr("aria-haspopup","true").prepend(i),e.attr("aria-labelledby",t.attr("id"))}),this._addClass(e,"ui-menu","ui-widget ui-widget-content ui-front"),(e=i.add(this.element).find(this.options.items)).not(".ui-menu-item").each(function(){var e=a(this);s._isDivider(e)&&s._addClass(e,"ui-menu-divider","ui-widget-content")}),t=(i=e.not(".ui-menu-item, .ui-menu-divider")).children().not(".ui-menu").uniqueId().attr({tabIndex:-1,role:this._itemRole()}),this._addClass(i,"ui-menu-item")._addClass(t,"ui-menu-item-wrapper"),e.filter(".ui-state-disabled").attr("aria-disabled","true"),this.active&&!a.contains(this.element[0],this.active[0])&&this.blur()},_itemRole:function(){return{menu:"menuitem",listbox:"option"}[this.options.role]},_setOption:function(e,t){var i;"icons"===e&&(i=this.element.find(".ui-menu-icon"),this._removeClass(i,null,this.options.icons.submenu)._addClass(i,null,t.submenu)),this._super(e,t)},_setOptionDisabled:function(e){this._super(e),this.element.attr("aria-disabled",String(e)),this._toggleClass(null,"ui-state-disabled",!!e)},focus:function(e,t){var i;this.blur(e,e&&"focus"===e.type),this._scrollIntoView(t),this.active=t.first(),i=this.active.children(".ui-menu-item-wrapper"),this._addClass(i,null,"ui-state-active"),this.options.role&&this.element.attr("aria-activedescendant",i.attr("id")),i=this.active.parent().closest(".ui-menu-item").children(".ui-menu-item-wrapper"),this._addClass(i,null,"ui-state-active"),e&&"keydown"===e.type?this._close():this.timer=this._delay(function(){this._close()},this.delay),(i=t.children(".ui-menu")).length&&e&&/^mouse/.test(e.type)&&this._startOpening(i),this.activeMenu=t.parent(),this._trigger("focus",e,{item:t})},_scrollIntoView:function(e){var t,i,s;this._hasScroll()&&(t=parseFloat(a.css(this.activeMenu[0],"borderTopWidth"))||0,i=parseFloat(a.css(this.activeMenu[0],"paddingTop"))||0,t=e.offset().top-this.activeMenu.offset().top-t-i,i=this.activeMenu.scrollTop(),s=this.activeMenu.height(),e=e.outerHeight(),t<0?this.activeMenu.scrollTop(i+t):s{"use strict";var e={d:(t,d)=>{for(var o in d)e.o(d,o)&&!e.o(t,o)&&Object.defineProperty(t,o,{enumerable:!0,get:d[o]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},t={};function d(e){"undefined"!=typeof document&&("complete"!==document.readyState&&"interactive"!==document.readyState?document.addEventListener("DOMContentLoaded",e):e())}e.d(t,{default:()=>d}),(window.wp=window.wp||{}).domReady=t.default})(); //# sourceMappingURL=index.min.js.map;