/* Detect-zoom
* -----------
* Cross Browser Zoom and Pixel Ratio Detector
* Version 1.0.4 | Apr 1 2013
* dual-licensed under the WTFPL and MIT license
* Maintained by https://github/tombigel
* Original developer https://github.com/yonran
*/
//AMD and CommonJS initialization copied from https://github.com/zohararad/audio5js
(function (root, ns, factory) {
"use strict";
if (typeof (module) !== 'undefined' && module.exports) { // CommonJS
module.exports = factory(ns, root);
} else if (typeof (define) === 'function' && define.amd) { // AMD
define("factory", function () {
return factory(ns, root);
});
} else {
root[ns] = factory(ns, root);
}
}(window, 'detectZoom', function () {
/**
* Use devicePixelRatio if supported by the browser
* @return {Number}
* @private
*/
var devicePixelRatio = function () {
return window.devicePixelRatio || 1;
};
/**
* Fallback function to set default values
* @return {Object}
* @private
*/
var fallback = function () {
return {
zoom: 1,
devicePxPerCssPx: 1
};
};
/**
* IE 8 and 9: no trick needed!
* TODO: Test on IE10 and Windows 8 RT
* @return {Object}
* @private
**/
var ie8 = function () {
var zoom = Math.round((screen.deviceXDPI / screen.logicalXDPI) * 100) / 100;
return {
zoom: zoom,
devicePxPerCssPx: zoom * devicePixelRatio()
};
};
/**
* For IE10 we need to change our technique again...
* thanks https://github.com/stefanvanburen
* @return {Object}
* @private
*/
var ie10 = function () {
var zoom = Math.round((document.documentElement.offsetHeight / window.innerHeight) * 100) / 100;
return {
zoom: zoom,
devicePxPerCssPx: zoom * devicePixelRatio()
};
};
/**
* Mobile WebKit
* the trick: window.innerWIdth is in CSS pixels, while
* screen.width and screen.height are in system pixels.
* And there are no scrollbars to mess up the measurement.
* @return {Object}
* @private
*/
var webkitMobile = function () {
var deviceWidth = (Math.abs(window.orientation) == 90) ? screen.height : screen.width;
var zoom = deviceWidth / window.innerWidth;
return {
zoom: zoom,
devicePxPerCssPx: zoom * devicePixelRatio()
};
};
/**
* Desktop Webkit
* the trick: an element's clientHeight is in CSS pixels, while you can
* set its line-height in system pixels using font-size and
* -webkit-text-size-adjust:none.
* device-pixel-ratio: http://www.webkit.org/blog/55/high-dpi-web-sites/
*
* Previous trick (used before http://trac.webkit.org/changeset/100847):
* documentElement.scrollWidth is in CSS pixels, while
* document.width was in system pixels. Note that this is the
* layout width of the document, which is slightly different from viewport
* because document width does not include scrollbars and might be wider
* due to big elements.
* @return {Object}
* @private
*/
var webkit = function () {
var important = function (str) {
return str.replace(/;/g, " !important;");
};
var div = document.createElement('div');
div.innerHTML = "1 2 3 4 5 6 7 8 9 0";
div.setAttribute('style', important('font: 100px/1em sans-serif; -webkit-text-size-adjust: none; text-size-adjust: none; height: auto; width: 1em; padding: 0; overflow: visible;'));
// The container exists so that the div will be laid out in its own flow
// while not impacting the layout, viewport size, or display of the
// webpage as a whole.
// Add !important and relevant CSS rule resets
// so that other rules cannot affect the results.
var container = document.createElement('div');
container.setAttribute('style', important('width:0; height:0; overflow:hidden; visibility:hidden; position: absolute;'));
container.appendChild(div);
document.body.appendChild(container);
var zoom = 1000 / div.clientHeight;
zoom = Math.round(zoom * 100) / 100;
document.body.removeChild(container);
return{
zoom: zoom,
devicePxPerCssPx: zoom * devicePixelRatio()
};
};
/**
* no real trick; device-pixel-ratio is the ratio of device dpi / css dpi.
* (Note that this is a different interpretation than Webkit's device
* pixel ratio, which is the ratio device dpi / system dpi).
*
* Also, for Mozilla, there is no difference between the zoom factor and the device ratio.
*
* @return {Object}
* @private
*/
var firefox4 = function () {
var zoom = mediaQueryBinarySearch('min--moz-device-pixel-ratio', '', 0, 10, 20, 0.0001);
zoom = Math.round(zoom * 100) / 100;
return {
zoom: zoom,
devicePxPerCssPx: zoom
};
};
/**
* Firefox 18.x
* Mozilla added support for devicePixelRatio to Firefox 18,
* but it is affected by the zoom level, so, like in older
* Firefox we can't tell if we are in zoom mode or in a device
* with a different pixel ratio
* @return {Object}
* @private
*/
var firefox18 = function () {
return {
zoom: firefox4().zoom,
devicePxPerCssPx: devicePixelRatio()
};
};
/**
* works starting Opera 11.11
* the trick: outerWidth is the viewport width including scrollbars in
* system px, while innerWidth is the viewport width including scrollbars
* in CSS px
* @return {Object}
* @private
*/
var opera11 = function () {
var zoom = window.top.outerWidth / window.top.innerWidth;
zoom = Math.round(zoom * 100) / 100;
return {
zoom: zoom,
devicePxPerCssPx: zoom * devicePixelRatio()
};
};
/**
* Use a binary search through media queries to find zoom level in Firefox
* @param property
* @param unit
* @param a
* @param b
* @param maxIter
* @param epsilon
* @return {Number}
*/
var mediaQueryBinarySearch = function (property, unit, a, b, maxIter, epsilon) {
var matchMedia;
var head, style, div;
if (window.matchMedia) {
matchMedia = window.matchMedia;
} else {
head = document.getElementsByTagName('head')[0];
style = document.createElement('style');
head.appendChild(style);
div = document.createElement('div');
div.className = 'mediaQueryBinarySearch';
div.style.display = 'none';
document.body.appendChild(div);
matchMedia = function (query) {
style.sheet.insertRule('@media ' + query + '{.mediaQueryBinarySearch ' + '{text-decoration: underline} }', 0);
var matched = getComputedStyle(div, null).textDecoration == 'underline';
style.sheet.deleteRule(0);
return {matches: matched};
};
}
var ratio = binarySearch(a, b, maxIter);
if (div) {
head.removeChild(style);
document.body.removeChild(div);
}
return ratio;
function binarySearch(a, b, maxIter) {
var mid = (a + b) / 2;
if (maxIter <= 0 || b - a < epsilon) {
return mid;
}
var query = "(" + property + ":" + mid + unit + ")";
if (matchMedia(query).matches) {
return binarySearch(mid, b, maxIter - 1);
} else {
return binarySearch(a, mid, maxIter - 1);
}
}
};
/**
* Generate detection function
* @private
*/
var detectFunction = (function () {
var func = fallback;
//IE8+
if (!isNaN(screen.logicalXDPI) && !isNaN(screen.systemXDPI)) {
func = ie8;
}
// IE10+ / Touch
else if (window.navigator.msMaxTouchPoints) {
func = ie10;
}
//Mobile Webkit
else if ('orientation' in window && typeof document.body.style.webkitMarquee === 'string') {
func = webkitMobile;
}
//WebKit
else if (typeof document.body.style.webkitMarquee === 'string') {
func = webkit;
}
//Opera
else if (navigator.userAgent.indexOf('Opera') >= 0) {
func = opera11;
}
//Last one is Firefox
//FF 18.x
else if (window.devicePixelRatio) {
func = firefox18;
}
//FF 4.0 - 17.x
else if (firefox4().zoom > 0.001) {
func = firefox4;
}
return func;
}());
return ({
/**
* Ratios.zoom shorthand
* @return {Number} Zoom level
*/
zoom: function () {
return detectFunction().zoom;
},
/**
* Ratios.devicePxPerCssPx shorthand
* @return {Number} devicePxPerCssPx level
*/
device: function () {
return detectFunction().devicePxPerCssPx;
}
});
}));
var wpcom_img_zoomer = {
clientHintSupport: {
gravatar: false,
files: false,
photon: false,
mshots: false,
staticAssets: false,
latex: false,
imgpress: false,
},
useHints: false,
zoomed: false,
timer: null,
interval: 1000, // zoom polling interval in millisecond
// Should we apply width/height attributes to control the image size?
imgNeedsSizeAtts: function( img ) {
// Do not overwrite existing width/height attributes.
if ( img.getAttribute('width') !== null || img.getAttribute('height') !== null )
return false;
// Do not apply the attributes if the image is already constrained by a parent element.
if ( img.width < img.naturalWidth || img.height < img.naturalHeight )
return false;
return true;
},
hintsFor: function( service ) {
if ( this.useHints === false ) {
return false;
}
if ( this.hints() === false ) {
return false;
}
if ( typeof this.clientHintSupport[service] === "undefined" ) {
return false;
}
if ( this.clientHintSupport[service] === true ) {
return true;
}
return false;
},
hints: function() {
try {
var chrome = window.navigator.userAgent.match(/\sChrome\/([0-9]+)\.[.0-9]+\s/)
if (chrome !== null) {
var version = parseInt(chrome[1], 10)
if (isNaN(version) === false && version >= 46) {
return true
}
}
} catch (e) {
return false
}
return false
},
init: function() {
var t = this;
try{
t.zoomImages();
t.timer = setInterval( function() { t.zoomImages(); }, t.interval );
}
catch(e){
}
},
stop: function() {
if ( this.timer )
clearInterval( this.timer );
},
getScale: function() {
var scale = detectZoom.device();
// Round up to 1.5 or the next integer below the cap.
if ( scale <= 1.0 ) scale = 1.0;
else if ( scale <= 1.5 ) scale = 1.5;
else if ( scale <= 2.0 ) scale = 2.0;
else if ( scale <= 3.0 ) scale = 3.0;
else if ( scale <= 4.0 ) scale = 4.0;
else scale = 5.0;
return scale;
},
shouldZoom: function( scale ) {
var t = this;
// Do not operate on hidden frames.
if ( "innerWidth" in window && !window.innerWidth )
return false;
// Don't do anything until scale > 1
if ( scale == 1.0 && t.zoomed == false )
return false;
return true;
},
zoomImages: function() {
var t = this;
var scale = t.getScale();
if ( ! t.shouldZoom( scale ) ){
return;
}
t.zoomed = true;
// Loop through all the elements on the page.
var imgs = document.getElementsByTagName("img");
for ( var i = 0; i < imgs.length; i++ ) {
// Wait for original images to load
if ( "complete" in imgs[i] && ! imgs[i].complete )
continue;
// Skip images that have srcset attributes.
if ( imgs[i].hasAttribute('srcset') ) {
continue;
}
// Skip images that don't need processing.
var imgScale = imgs[i].getAttribute("scale");
if ( imgScale == scale || imgScale == "0" )
continue;
// Skip images that have already failed at this scale
var scaleFail = imgs[i].getAttribute("scale-fail");
if ( scaleFail && scaleFail <= scale )
continue;
// Skip images that have no dimensions yet.
if ( ! ( imgs[i].width && imgs[i].height ) )
continue;
// Skip images from Lazy Load plugins
if ( ! imgScale && imgs[i].getAttribute("data-lazy-src") && (imgs[i].getAttribute("data-lazy-src") !== imgs[i].getAttribute("src")))
continue;
if ( t.scaleImage( imgs[i], scale ) ) {
// Mark the img as having been processed at this scale.
imgs[i].setAttribute("scale", scale);
}
else {
// Set the flag to skip this image.
imgs[i].setAttribute("scale", "0");
}
}
},
scaleImage: function( img, scale ) {
var t = this;
var newSrc = img.src;
var isFiles = false;
var isLatex = false;
var isPhoton = false;
// Skip slideshow images
if ( img.parentNode.className.match(/slideshow-slide/) )
return false;
// Skip CoBlocks Lightbox images
if ( img.parentNode.className.match(/coblocks-lightbox__image/) )
return false;
// Scale gravatars that have ?s= or ?size=
if ( img.src.match( /^https?:\/\/([^\/]*\.)?gravatar\.com\/.+[?&](s|size)=/ ) ) {
if ( this.hintsFor( "gravatar" ) === true ) {
return false;
}
newSrc = img.src.replace( /([?&](s|size)=)(\d+)/, function( $0, $1, $2, $3 ) {
// Stash the original size
var originalAtt = "originals",
originalSize = img.getAttribute(originalAtt);
if ( originalSize === null ) {
originalSize = $3;
img.setAttribute(originalAtt, originalSize);
if ( t.imgNeedsSizeAtts( img ) ) {
// Fix width and height attributes to rendered dimensions.
img.width = img.width;
img.height = img.height;
}
}
// Get the width/height of the image in CSS pixels
var size = img.clientWidth;
// Convert CSS pixels to device pixels
var targetSize = Math.ceil(img.clientWidth * scale);
// Don't go smaller than the original size
targetSize = Math.max( targetSize, originalSize );
// Don't go larger than the service supports
targetSize = Math.min( targetSize, 512 );
return $1 + targetSize;
});
}
// Scale mshots that have width
else if ( img.src.match(/^https?:\/\/([^\/]+\.)*(wordpress|wp)\.com\/mshots\/.+[?&]w=\d+/) ) {
if ( this.hintsFor( "mshots" ) === true ) {
return false;
}
newSrc = img.src.replace( /([?&]w=)(\d+)/, function($0, $1, $2) {
// Stash the original size
var originalAtt = 'originalw', originalSize = img.getAttribute(originalAtt);
if ( originalSize === null ) {
originalSize = $2;
img.setAttribute(originalAtt, originalSize);
if ( t.imgNeedsSizeAtts( img ) ) {
// Fix width and height attributes to rendered dimensions.
img.width = img.width;
img.height = img.height;
}
}
// Get the width of the image in CSS pixels
var size = img.clientWidth;
// Convert CSS pixels to device pixels
var targetSize = Math.ceil(size * scale);
// Don't go smaller than the original size
targetSize = Math.max( targetSize, originalSize );
// Don't go bigger unless the current one is actually lacking
if ( scale > img.getAttribute("scale") && targetSize <= img.naturalWidth )
targetSize = $2;
if ( $2 != targetSize )
return $1 + targetSize;
return $0;
});
// Update height attribute to match width
newSrc = newSrc.replace( /([?&]h=)(\d+)/, function($0, $1, $2) {
if ( newSrc == img.src ) {
return $0;
}
// Stash the original size
var originalAtt = 'originalh', originalSize = img.getAttribute(originalAtt);
if ( originalSize === null ) {
originalSize = $2;
img.setAttribute(originalAtt, originalSize);
}
// Get the height of the image in CSS pixels
var size = img.clientHeight;
// Convert CSS pixels to device pixels
var targetSize = Math.ceil(size * scale);
// Don't go smaller than the original size
targetSize = Math.max( targetSize, originalSize );
// Don't go bigger unless the current one is actually lacking
if ( scale > img.getAttribute("scale") && targetSize <= img.naturalHeight )
targetSize = $2;
if ( $2 != targetSize )
return $1 + targetSize;
return $0;
});
}
// Scale simple imgpress queries (s0.wp.com) that only specify w/h/fit
else if ( img.src.match(/^https?:\/\/([^\/.]+\.)*(wp|wordpress)\.com\/imgpress\?(.+)/) ) {
if ( this.hintsFor( "imgpress" ) === true ) {
return false;
}
var imgpressSafeFunctions = ["zoom", "url", "h", "w", "fit", "filter", "brightness", "contrast", "colorize", "smooth", "unsharpmask"];
// Search the query string for unsupported functions.
var qs = RegExp.$3.split('&');
for ( var q in qs ) {
q = qs[q].split('=')[0];
if ( imgpressSafeFunctions.indexOf(q) == -1 ) {
return false;
}
}
// Fix width and height attributes to rendered dimensions.
img.width = img.width;
img.height = img.height;
// Compute new src
if ( scale == 1 )
newSrc = img.src.replace(/\?(zoom=[^&]+&)?/, '?');
else
newSrc = img.src.replace(/\?(zoom=[^&]+&)?/, '?zoom=' + scale + '&');
}
// Scale files.wordpress.com, LaTeX, or Photon images (i#.wp.com)
else if (
( isFiles = img.src.match(/^https?:\/\/([^\/]+)\.files\.wordpress\.com\/.+[?&][wh]=/) ) ||
( isLatex = img.src.match(/^https?:\/\/([^\/.]+\.)*(wp|wordpress)\.com\/latex\.php\?(latex|zoom)=(.+)/) ) ||
( isPhoton = img.src.match(/^https?:\/\/i[\d]{1}\.wp\.com\/(.+)/) )
) {
if ( false !== isFiles && this.hintsFor( "files" ) === true ) {
return false
}
if ( false !== isLatex && this.hintsFor( "latex" ) === true ) {
return false
}
if ( false !== isPhoton && this.hintsFor( "photon" ) === true ) {
return false
}
// Fix width and height attributes to rendered dimensions.
img.width = img.width;
img.height = img.height;
// Compute new src
if ( scale == 1 ) {
newSrc = img.src.replace(/\?(zoom=[^&]+&)?/, '?');
} else {
newSrc = img.src;
var url_var = newSrc.match( /([?&]w=)(\d+)/ );
if ( url_var !== null && url_var[2] ) {
newSrc = newSrc.replace( url_var[0], url_var[1] + img.width );
}
url_var = newSrc.match( /([?&]h=)(\d+)/ );
if ( url_var !== null && url_var[2] ) {
newSrc = newSrc.replace( url_var[0], url_var[1] + img.height );
}
var zoom_arg = '&zoom=2';
if ( !newSrc.match( /\?/ ) ) {
zoom_arg = '?zoom=2';
}
img.setAttribute( 'srcset', newSrc + zoom_arg + ' ' + scale + 'x' );
}
}
// Scale static assets that have a name matching *-1x.png or *@1x.png
else if ( img.src.match(/^https?:\/\/[^\/]+\/.*[-@]([12])x\.(gif|jpeg|jpg|png)(\?|$)/) ) {
if ( this.hintsFor( "staticAssets" ) === true ) {
return false;
}
// Fix width and height attributes to rendered dimensions.
img.width = img.width;
img.height = img.height;
var currentSize = RegExp.$1, newSize = currentSize;
if ( scale <= 1 )
newSize = 1;
else
newSize = 2;
if ( currentSize != newSize )
newSrc = img.src.replace(/([-@])[12]x\.(gif|jpeg|jpg|png)(\?|$)/, '$1'+newSize+'x.$2$3');
}
else {
return false;
}
// Don't set img.src unless it has changed. This avoids unnecessary reloads.
if ( newSrc != img.src ) {
// Store the original img.src
var prevSrc, origSrc = img.getAttribute("src-orig");
if ( !origSrc ) {
origSrc = img.src;
img.setAttribute("src-orig", origSrc);
}
// In case of error, revert img.src
prevSrc = img.src;
img.onerror = function(){
img.src = prevSrc;
if ( img.getAttribute("scale-fail") < scale )
img.setAttribute("scale-fail", scale);
img.onerror = null;
};
// Finally load the new image
img.src = newSrc;
}
return true;
}
};
wpcom_img_zoomer.init();
;
/**
* author Christopher Blum
* - based on the idea of Remy Sharp, http://remysharp.com/2009/01/26/element-in-view-event-plugin/
* - forked from http://github.com/zuk/jquery.inview/
*/
(function ($) {
var inviewObjects = {}, viewportSize, viewportOffset,
d = document, w = window, documentElement = d.documentElement, expando = $.expando;
$.event.special.inview = {
add: function(data) {
inviewObjects[data.guid + "-" + this[expando]] = { data: data, $element: $(this) };
},
remove: function(data) {
try { delete inviewObjects[data.guid + "-" + this[expando]]; } catch(e) {}
}
};
function getViewportSize() {
var mode, domObject, size = { height: w.innerHeight, width: w.innerWidth };
// if this is correct then return it. iPad has compat Mode, so will
// go into check clientHeight/clientWidth (which has the wrong value).
if (!size.height) {
mode = d.compatMode;
if (mode || !$.support.boxModel) { // IE, Gecko
domObject = mode === 'CSS1Compat' ?
documentElement : // Standards
d.body; // Quirks
size = {
height: domObject.clientHeight,
width: domObject.clientWidth
};
}
}
return size;
}
function getViewportOffset() {
return {
top: w.pageYOffset || documentElement.scrollTop || d.body.scrollTop,
left: w.pageXOffset || documentElement.scrollLeft || d.body.scrollLeft
};
}
function checkInView() {
var $elements = $(), elementsLength, i = 0;
$.each(inviewObjects, function(i, inviewObject) {
var selector = inviewObject.data.selector,
$element = inviewObject.$element;
$elements = $elements.add(selector ? $element.find(selector) : $element);
});
elementsLength = $elements.length;
if (elementsLength) {
viewportSize = viewportSize || getViewportSize();
viewportOffset = viewportOffset || getViewportOffset();
for (; i= 0 && element.offsetHeight >= 0 && element.style.display != "none" &&
elementOffset.top + elementSize.height > viewportOffset.top &&
elementOffset.top < viewportOffset.top + viewportSize.height &&
elementOffset.left + elementSize.width > viewportOffset.left &&
elementOffset.left < viewportOffset.left + viewportSize.width) {
visiblePartX = (viewportOffset.left > elementOffset.left ?
'right' : (viewportOffset.left + viewportSize.width) < (elementOffset.left + elementSize.width) ?
'left' : 'both');
visiblePartY = (viewportOffset.top > elementOffset.top ?
'bottom' : (viewportOffset.top + viewportSize.height) < (elementOffset.top + elementSize.height) ?
'top' : 'both');
visiblePartsMerged = visiblePartX + "-" + visiblePartY;
if (!inView || inView !== visiblePartsMerged) {
$element.data('inview', visiblePartsMerged).trigger('inview', [true, visiblePartX, visiblePartY]);
}
} else if (inView) {
$element.data('inview', false).trigger('inview', [false]);
}
}
}
}
$(w).bind("scroll resize", function() {
viewportSize = viewportOffset = null;
});
// IE < 9 scrolls to focused elements without firing the "scroll" event
if (!documentElement.addEventListener && documentElement.attachEvent) {
documentElement.attachEvent("onfocusin", function() {
viewportOffset = null;
});
}
// Use setInterval in order to also make sure this captures elements within
// "overflow:scroll" elements or elements that appeared in the dom tree due to
// dom manipulation and reflow
// old: $(window).scroll(checkInView);
//
// By the way, iOS (iPad, iPhone, ...) seems to not execute, or at least delays
// intervals while the user scrolls. Therefore the inview event might fire a bit late there
setInterval(checkInView, 250);
})(jQuery);;
/* global Jetpack, JSON */
/**
* Resizeable Iframes.
*
* Start listening to resize postMessage events for selected iframes:
* $( selector ).Jetpack( 'resizeable' );
* - OR -
* Jetpack.resizeable( 'on', context );
*
* Resize selected iframes:
* $( selector ).Jetpack( 'resizeable', 'resize', { width: 100, height: 200 } );
* - OR -
* Jetpack.resizeable( 'resize', { width: 100, height: 200 }, context );
*
* Stop listening to resize postMessage events for selected iframes:
* $( selector ).Jetpack( 'resizeable', 'off' );
* - OR -
* Jetpack.resizeable( 'off', context );
*
* Stop listening to all resize postMessage events:
* Jetpack.resizeable( 'off' );
*/
( function ( $ ) {
var listening = false, // Are we listening for resize postMessage events
sourceOrigins = [], // What origins are allowed to send resize postMessage events
$sources = false, // What iframe elements are we tracking resize postMessage events from
URLtoOrigin, // Utility to convert URLs into origins
setupListener, // Binds global resize postMessage event handler
destroyListener, // Unbinds global resize postMessage event handler
methods; // Jetpack.resizeable methods
// Setup the Jetpack global
if ( 'undefined' === typeof window.Jetpack ) {
window.Jetpack = {
/**
* Handles the two different calling methods:
* $( selector ).Jetpack( 'namespace', 'method', context ) // here, context is optional and is used to filter the collection
* - vs. -
* Jetpack.namespace( 'method', context ) // here context defines the collection
*
* @internal
*
* Call as: Jetpack.getTarget.call( this, context )
*
* @param string context: jQuery selector
* @return jQuery|undefined object on which to perform operations or undefined when context cannot be determined
*/
getTarget: function ( context ) {
if ( this instanceof jQuery ) {
return context ? this.filter( context ) : this;
}
return context ? $( context ) : context;
},
};
}
// Setup the Jetpack jQuery method
if ( 'undefined' === typeof $.fn.Jetpack ) {
/**
* Dispatches calls to the correct namespace
*
* @param string namespace
* @param ...
* @return mixed|jQuery (chainable)
*/
$.fn.Jetpack = function ( namespace ) {
if ( 'function' === typeof Jetpack[ namespace ] ) {
// Send the call to the correct Jetpack.namespace
return Jetpack[ namespace ].apply( this, Array.prototype.slice.call( arguments, 1 ) );
} else {
$.error( 'Namespace "' + namespace + '" does not exist on jQuery.Jetpack' );
}
};
}
// Define Jetpack.resizeable() namespace to just always bail if no postMessage
if ( 'function' !== typeof window.postMessage ) {
$.extend( window.Jetpack, {
/**
* Defines the Jetpack.resizeable() namespace.
* See below for non-trivial definition for browsers with postMessage.
*/
resizeable: function () {
$.error( 'Browser does not support window.postMessage' );
},
} );
return;
}
/**
* Utility to convert URLs into origins
*
* http://example.com:port/path?query#fragment -> http://example.com:port
*
* @param string URL
* @return string origin
*/
URLtoOrigin = function ( URL ) {
if ( ! URL.match( /^https?:\/\// ) ) {
URL = document.location.href;
}
return URL.split( '/' ).slice( 0, 3 ).join( '/' );
};
/**
* Binds global resize postMessage event handler
*/
setupListener = function () {
listening = true;
$( window ).on( 'message.JetpackResizeableIframe', function ( e ) {
var event = e.originalEvent,
data;
// Ensure origin is allowed
if ( -1 === $.inArray( event.origin, sourceOrigins ) ) {
return;
}
// Some browsers send structured data, some send JSON strings
if ( 'object' === typeof event.data ) {
data = event.data.data;
} else {
try {
data = JSON.parse( event.data );
} catch ( err ) {
data = false;
}
}
if ( ! data.data ) {
return;
}
// Un-nest
data = data.data;
// Is it a resize event?
if ( 'undefined' === typeof data.action || 'resize' !== data.action ) {
return;
}
// Find the correct iframe and resize it
$sources
.filter( function () {
if ( 'undefined' !== typeof data.name ) {
return this.name === data.name;
} else {
return event.source === this.contentWindow;
}
} )
.first()
.Jetpack( 'resizeable', 'resize', data );
} );
};
/**
* Unbinds global resize postMessage event handler
*/
destroyListener = function () {
listening = false;
$( window ).off( 'message.JetpackResizeableIframe' );
sourceOrigins = [];
$( '.jetpack-resizeable' ).removeClass( 'jetpack-resizeable' );
$sources = false;
};
// Methods for Jetpack.resizeable() namespace
methods = {
/**
* Start listening for resize postMessage events on the given iframes
*
* Call statically as: Jetpack.resizeable( 'on', context )
* Call as: $( selector ).Jetpack( 'resizeable', 'on', context ) // context optional: used to filter the collectino
*
* @param string context jQuery selector.
* @return jQuery (chainable)
*/
on: function ( context ) {
var target = Jetpack.getTarget.call( this, context );
if ( ! listening ) {
setupListener();
}
target
.each( function () {
sourceOrigins.push( URLtoOrigin( $( this ).attr( 'src' ) ) );
} )
.addClass( 'jetpack-resizeable' );
$sources = $( '.jetpack-resizeable' );
return target;
},
/**
* Stop listening for resize postMessage events on the given iframes
*
* Call statically as: Jetpack.resizeable( 'off', context )
* Call as: $( selector ).Jetpack( 'resizeable', 'off', context ) // context optional: used to filter the collectino
*
* @param string context jQuery selector
* @return jQuery (chainable)
*/
off: function ( context ) {
var target = Jetpack.getTarget.call( this, context );
if ( 'undefined' === typeof target ) {
destroyListener();
return target;
}
target
.each( function () {
var origin = URLtoOrigin( $( this ).attr( 'src' ) ),
pos = $.inArray( origin, sourceOrigins );
if ( -1 !== pos ) {
sourceOrigins.splice( pos, 1 );
}
} )
.removeClass( 'jetpack-resizeable' );
$sources = $( '.jetpack-resizeable' );
return target;
},
/**
* Resize the given iframes
*
* Call statically as: Jetpack.resizeable( 'resize', dimensions, context )
* Call as: $( selector ).Jetpack( 'resizeable', 'resize', dimensions, context ) // context optional: used to filter the collectino
*
* @param object dimensions in pixels: { width: (int), height: (int) }
* @param string context jQuery selector
* @return jQuery (chainable)
*/
resize: function ( dimensions, context ) {
var target = Jetpack.getTarget.call( this, context );
$.each( [ 'width', 'height' ], function ( i, variable ) {
var value = 0,
container;
if ( 'undefined' !== typeof dimensions[ variable ] ) {
value = parseInt( dimensions[ variable ], 10 );
}
if ( 0 !== value ) {
target[ variable ]( value );
container = target.parent();
if ( container.hasClass( 'slim-likes-widget' ) ) {
container[ variable ]( value );
}
}
} );
return target;
},
};
// Define Jetpack.resizeable() namespace
$.extend( window.Jetpack, {
/**
* Defines the Jetpack.resizeable() namespace.
* See above for trivial definition for browsers with no postMessage.
*
* @param string method
* @param ...
* @return mixed|jQuery (chainable)
*/
resizeable: function ( method ) {
if ( methods[ method ] ) {
// Send the call to the correct Jetpack.resizeable() method
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ) );
} else if ( ! method ) {
// By default, send to Jetpack.resizeable( 'on' ), which isn't useful in that form but is when called as
// jQuery( selector ).Jetpack( 'resizeable' )
return methods.on.apply( this );
} else {
$.error( 'Method ' + method + ' does not exist on Jetpack.resizeable' );
}
},
} );
} )( jQuery );
;
/* global pm, wpcom_reblog */
var jetpackLikesWidgetQueue = [];
var jetpackLikesWidgetBatch = [];
var jetpackLikesMasterReady = false;
function JetpackLikespostMessage( message, target ) {
if ( 'string' === typeof message ){
try {
message = JSON.parse( message );
} catch(e) {
return;
}
}
pm( {
target: target,
type: 'likesMessage',
data: message,
origin: '*'
} );
}
function JetpackLikesBatchHandler() {
var requests = [];
jQuery( 'div.jetpack-likes-widget-unloaded' ).each( function() {
if ( jetpackLikesWidgetBatch.indexOf( this.id ) > -1 ) {
return;
}
jetpackLikesWidgetBatch.push( this.id );
var regex = /like-(post|comment)-wrapper-(\d+)-(\d+)-(\w+)/,
match = regex.exec( this.id ),
info;
if ( ! match || match.length !== 5 ) {
return;
}
info = {
blog_id: match[2],
width: this.width
};
if ( 'post' === match[1] ) {
info.post_id = match[3];
} else if ( 'comment' === match[1] ) {
info.comment_id = match[3];
}
info.obj_id = match[4];
requests.push( info );
});
if ( requests.length > 0 ) {
JetpackLikespostMessage( { event: 'initialBatch', requests: requests }, window.frames['likes-master'] );
}
}
function JetpackLikesMessageListener( event, message ) {
var allowedOrigin, $container, $list, offset, rowLength, height, scrollbarWidth;
if ( 'undefined' === typeof event.event ) {
return;
}
// We only allow messages from one origin
allowedOrigin = window.location.protocol + '//widgets.wp.com';
if ( allowedOrigin !== message.origin ) {
return;
}
if ( 'masterReady' === event.event ) {
jQuery( document ).ready( function() {
jetpackLikesMasterReady = true;
var stylesData = {
event: 'injectStyles'
},
$sdTextColor = jQuery( '.sd-text-color' ),
$sdLinkColor = jQuery( '.sd-link-color' );
if ( jQuery( 'iframe.admin-bar-likes-widget' ).length > 0 ) {
JetpackLikespostMessage( { event: 'adminBarEnabled' }, window.frames[ 'likes-master' ] );
stylesData.adminBarStyles = {
background: jQuery( '#wpadminbar .quicklinks li#wp-admin-bar-wpl-like > a' ).css( 'background' ),
isRtl: ( 'rtl' === jQuery( '#wpadminbar' ).css( 'direction' ) )
};
}
// enable reblogs if we're on a single post page
if ( jQuery( 'body' ).hasClass( 'single' ) ) {
JetpackLikespostMessage( { event: 'reblogsEnabled' }, window.frames[ 'likes-master' ] );
}
if ( ! window.addEventListener ) {
jQuery( '#wp-admin-bar-admin-bar-likes-widget' ).hide();
}
stylesData.textStyles = {
color: $sdTextColor.css( 'color' ),
fontFamily: $sdTextColor.css( 'font-family' ),
fontSize: $sdTextColor.css( 'font-size' ),
direction: $sdTextColor.css( 'direction' ),
fontWeight: $sdTextColor.css( 'font-weight' ),
fontStyle: $sdTextColor.css( 'font-style' ),
textDecoration: $sdTextColor.css('text-decoration')
};
stylesData.linkStyles = {
color: $sdLinkColor.css('color'),
fontFamily: $sdLinkColor.css('font-family'),
fontSize: $sdLinkColor.css('font-size'),
textDecoration: $sdLinkColor.css('text-decoration'),
fontWeight: $sdLinkColor.css( 'font-weight' ),
fontStyle: $sdLinkColor.css( 'font-style' )
};
JetpackLikespostMessage( stylesData, window.frames[ 'likes-master' ] );
JetpackLikesBatchHandler();
jQuery( document ).on( 'inview', 'div.jetpack-likes-widget-unloaded', function() {
jetpackLikesWidgetQueue.push( this.id );
});
});
}
if ( 'showLikeWidget' === event.event ) {
jQuery( '#' + event.id + ' .post-likes-widget-placeholder' ).fadeOut( 'fast', function() {
jQuery( '#' + event.id + ' .post-likes-widget' ).fadeIn( 'fast', function() {
JetpackLikespostMessage( { event: 'likeWidgetDisplayed', blog_id: event.blog_id, post_id: event.post_id, obj_id: event.obj_id }, window.frames['likes-master'] );
});
});
}
if ( 'clickReblogFlair' === event.event ) {
wpcom_reblog.toggle_reblog_box_flair( event.obj_id );
}
if ( 'showOtherGravatars' === event.event ) {
$container = jQuery( '#likes-other-gravatars' );
$list = $container.find( 'ul' );
$container.hide();
$list.html( '' );
$container.find( '.likes-text span' ).text( event.total );
jQuery.each( event.likers, function( i, liker ) {
var element = jQuery( '
' );
element.addClass( liker.css_class );
element.find( 'a' ).
attr({
href: liker.profile_URL,
rel: 'nofollow',
target: '_parent'
}).
addClass( 'wpl-liker' );
element.find( 'img' ).
attr({
src: liker.avatar_URL,
alt: liker.name
}).
css({
width: '30px',
height: '30px',
paddingRight: '3px'
});
$list.append( element );
} );
offset = jQuery( '[name=\'' + event.parent + '\']' ).offset();
$container.css( 'left', offset.left + event.position.left - 10 + 'px' );
$container.css( 'top', offset.top + event.position.top - 33 + 'px' );
rowLength = Math.floor( event.width / 37 );
height = ( Math.ceil( event.likers.length / rowLength ) * 37 ) + 13;
if ( height > 204 ) {
height = 204;
}
$container.css( 'height', height + 'px' );
$container.css( 'width', rowLength * 37 - 7 + 'px' );
$list.css( 'width', rowLength * 37 + 'px' );
$container.fadeIn( 'slow' );
scrollbarWidth = $list[0].offsetWidth - $list[0].clientWidth;
if ( scrollbarWidth > 0 ) {
$container.width( $container.width() + scrollbarWidth );
$list.width( $list.width() + scrollbarWidth );
}
}
}
pm.bind( 'likesMessage', JetpackLikesMessageListener );
jQuery( document ).click( function( e ) {
var $container = jQuery( '#likes-other-gravatars' );
if ( $container.has( e.target ).length === 0 ) {
$container.fadeOut( 'slow' );
}
});
function JetpackLikesWidgetQueueHandler() {
var $wrapper, wrapperID, found;
if ( ! jetpackLikesMasterReady ) {
setTimeout( JetpackLikesWidgetQueueHandler, 500 );
return;
}
if ( jetpackLikesWidgetQueue.length > 0 ) {
// We may have a widget that needs creating now
found = false;
while( jetpackLikesWidgetQueue.length > 0 ) {
// Grab the first member of the queue that isn't already loading.
wrapperID = jetpackLikesWidgetQueue.splice( 0, 1 )[0];
if ( jQuery( '#' + wrapperID ).hasClass( 'jetpack-likes-widget-unloaded' ) ) {
found = true;
break;
}
}
if ( ! found ) {
setTimeout( JetpackLikesWidgetQueueHandler, 500 );
return;
}
} else if ( jQuery( 'div.jetpack-likes-widget-unloaded' ).length > 0 ) {
// Grab any unloaded widgets for a batch request
JetpackLikesBatchHandler();
// Get the next unloaded widget
wrapperID = jQuery( 'div.jetpack-likes-widget-unloaded' ).first()[0].id;
if ( ! wrapperID ) {
// Everything is currently loaded
setTimeout( JetpackLikesWidgetQueueHandler, 500 );
return;
}
}
if ( 'undefined' === typeof wrapperID ) {
setTimeout( JetpackLikesWidgetQueueHandler, 500 );
return;
}
$wrapper = jQuery( '#' + wrapperID );
$wrapper.find( 'iframe' ).remove();
if ( $wrapper.hasClass( 'slim-likes-widget' ) ) {
$wrapper.find( '.post-likes-widget-placeholder' ).after( '' );
} else {
$wrapper.find( '.post-likes-widget-placeholder' ).after( '' );
}
$wrapper.removeClass( 'jetpack-likes-widget-unloaded' ).addClass( 'jetpack-likes-widget-loading' );
$wrapper.find( 'iframe' ).load( function( e ) {
var $iframe = jQuery( e.target );
$wrapper.removeClass( 'jetpack-likes-widget-loading' ).addClass( 'jetpack-likes-widget-loaded' );
JetpackLikespostMessage( { event: 'loadLikeWidget', name: $iframe.attr( 'name' ), width: $iframe.width(), domain: window.location.hostname }, window.frames[ 'likes-master' ] );
if ( $wrapper.hasClass( 'slim-likes-widget' ) ) {
$wrapper.find( 'iframe' ).Jetpack( 'resizeable' );
}
});
setTimeout( JetpackLikesWidgetQueueHandler, 250 );
}
JetpackLikesWidgetQueueHandler();
;
/*
* Swipe 2.0
*
* Brad Birdsall
* Copyright 2013, MIT License
*
*/
function Swipe(container, options) {
"use strict";
// utilities
var noop = function() {}; // simple no operation function
var offloadFn = function(fn) { setTimeout(fn || noop, 0) }; // offload a functions execution
// check browser capabilities
var browser = {
addEventListener: !!window.addEventListener,
touch: ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch,
transitions: (function(temp) {
var props = ['transitionProperty', 'WebkitTransition', 'MozTransition', 'OTransition', 'msTransition'];
for ( var i in props ) if (temp.style[ props[i] ] !== undefined) return true;
return false;
})(document.createElement('swipe'))
};
// quit if no root element
if (!container) return;
var element = container.children[0];
var slides, slidePos, width, length;
options = options || {};
var index = parseInt(options.startSlide, 10) || 0;
var speed = options.speed || 300;
options.continuous = options.continuous !== undefined ? options.continuous : true;
function setup() {
// cache slides
slides = element.children;
length = slides.length;
// set continuous to false if only one slide
if (slides.length < 2) options.continuous = false;
//special case if two slides
if (browser.transitions && options.continuous && slides.length < 3) {
element.appendChild(slides[0].cloneNode(true));
element.appendChild(element.children[1].cloneNode(true));
slides = element.children;
}
// create an array to store current positions of each slide
slidePos = new Array(slides.length);
// determine width of each slide
width = container.getBoundingClientRect().width || container.offsetWidth;
element.style.width = (slides.length * width) + 'px';
// stack elements
var pos = slides.length;
while(pos--) {
var slide = slides[pos];
slide.style.width = width + 'px';
slide.setAttribute('data-index', pos);
if (browser.transitions) {
slide.style.left = (pos * -width) + 'px';
move(pos, index > pos ? -width : (index < pos ? width : 0), 0);
}
}
// reposition elements before and after index
if (options.continuous && browser.transitions) {
move(circle(index-1), -width, 0);
move(circle(index+1), width, 0);
}
if (!browser.transitions) element.style.left = (index * -width) + 'px';
container.style.visibility = 'visible';
}
function prev() {
if (options.continuous) slide(index-1);
else if (index) slide(index-1);
}
function next() {
if (options.continuous) slide(index+1);
else if (index < slides.length - 1) slide(index+1);
}
function circle(index) {
// a simple positive modulo using slides.length
return (slides.length + (index % slides.length)) % slides.length;
}
function slide(to, slideSpeed) {
// do nothing if already on requested slide
if (index == to) return;
if (browser.transitions) {
var direction = Math.abs(index-to) / (index-to); // 1: backward, -1: forward
// get the actual position of the slide
if (options.continuous) {
var natural_direction = direction;
direction = -slidePos[circle(to)] / width;
// if going forward but to < index, use to = slides.length + to
// if going backward but to > index, use to = -slides.length + to
if (direction !== natural_direction) to = -direction * slides.length + to;
}
var diff = Math.abs(index-to) - 1;
// move all the slides between index and to in the right direction
while (diff--) move( circle((to > index ? to : index) - diff - 1), width * direction, 0);
to = circle(to);
move(index, width * direction, slideSpeed || speed);
move(to, 0, slideSpeed || speed);
if (options.continuous) move(circle(to - direction), -(width * direction), 0); // we need to get the next in place
} else {
to = circle(to);
animate(index * -width, to * -width, slideSpeed || speed);
//no fallback for a circular continuous if the browser does not accept transitions
}
index = to;
offloadFn(options.callback && options.callback(index, slides[index]));
}
function move(index, dist, speed) {
translate(index, dist, speed);
slidePos[index] = dist;
}
function translate(index, dist, speed) {
var slide = slides[index];
var style = slide && slide.style;
if (!style) return;
style.webkitTransitionDuration =
style.MozTransitionDuration =
style.msTransitionDuration =
style.OTransitionDuration =
style.transitionDuration = speed + 'ms';
style.webkitTransform = 'translate(' + dist + 'px,0)' + 'translateZ(0)';
style.msTransform =
style.MozTransform =
style.OTransform = 'translateX(' + dist + 'px)';
}
function animate(from, to, speed) {
// if not an animation, just reposition
if (!speed) {
element.style.left = to + 'px';
return;
}
var start = +new Date;
var timer = setInterval(function() {
var timeElap = +new Date - start;
if (timeElap > speed) {
element.style.left = to + 'px';
if (delay) begin();
options.transitionEnd && options.transitionEnd.call(event, index, slides[index]);
clearInterval(timer);
return;
}
element.style.left = (( (to - from) * (Math.floor((timeElap / speed) * 100) / 100) ) + from) + 'px';
}, 4);
}
// setup auto slideshow
var delay = options.auto || 0;
var interval;
function begin() {
interval = setTimeout(next, delay);
}
function stop() {
delay = 0;
clearTimeout(interval);
}
// setup initial vars
var start = {};
var delta = {};
var isScrolling;
// setup event capturing
var events = {
handleEvent: function(event) {
switch (event.type) {
case 'touchstart': this.start(event); break;
case 'touchmove': this.move(event); break;
case 'touchend': offloadFn(this.end(event)); break;
case 'webkitTransitionEnd':
case 'msTransitionEnd':
case 'oTransitionEnd':
case 'otransitionend':
case 'transitionend': offloadFn(this.transitionEnd(event)); break;
case 'resize': offloadFn(setup.call()); break;
}
if (options.stopPropagation) event.stopPropagation();
},
start: function(event) {
var touches = event.touches[0];
// measure start values
start = {
// get initial touch coords
x: touches.pageX,
y: touches.pageY,
// store time to determine touch duration
time: +new Date
};
// used for testing first move event
isScrolling = undefined;
// reset delta and end measurements
delta = {};
// attach touchmove and touchend listeners
element.addEventListener('touchmove', this, false);
element.addEventListener('touchend', this, false);
},
move: function(event) {
// ensure swiping with one touch and not pinching
if ( event.touches.length > 1 || event.scale && event.scale !== 1) return
if (options.disableScroll) event.preventDefault();
var touches = event.touches[0];
// measure change in x and y
delta = {
x: touches.pageX - start.x,
y: touches.pageY - start.y
}
// determine if scrolling test has run - one time test
if ( typeof isScrolling == 'undefined') {
isScrolling = !!( isScrolling || Math.abs(delta.x) < Math.abs(delta.y) );
}
// if user is not trying to scroll vertically
if (!isScrolling) {
// prevent native scrolling
event.preventDefault();
// stop slideshow
stop();
// increase resistance if first or last slide
if (options.continuous) { // we don't add resistance at the end
translate(circle(index-1), delta.x + slidePos[circle(index-1)], 0);
translate(index, delta.x + slidePos[index], 0);
translate(circle(index+1), delta.x + slidePos[circle(index+1)], 0);
} else {
delta.x =
delta.x /
( (!index && delta.x > 0 // if first slide and sliding left
|| index == slides.length - 1 // or if last slide and sliding right
&& delta.x < 0 // and if sliding at all
) ?
( Math.abs(delta.x) / width + 1 ) // determine resistance level
: 1 ); // no resistance if false
// translate 1:1
translate(index-1, delta.x + slidePos[index-1], 0);
translate(index, delta.x + slidePos[index], 0);
translate(index+1, delta.x + slidePos[index+1], 0);
}
}
},
end: function(event) {
// measure duration
var duration = +new Date - start.time;
// determine if slide attempt triggers next/prev slide
var isValidSlide =
Number(duration) < 250 // if slide duration is less than 250ms
&& Math.abs(delta.x) > 20 // and if slide amt is greater than 20px
|| Math.abs(delta.x) > width/2; // or if slide amt is greater than half the width
// determine if slide attempt is past start and end
var isPastBounds =
!index && delta.x > 0 // if first slide and slide amt is greater than 0
|| index == slides.length - 1 && delta.x < 0; // or if last slide and slide amt is less than 0
if (options.continuous) isPastBounds = false;
// determine direction of swipe (true:right, false:left)
var direction = delta.x < 0;
// if not scrolling vertically
if (!isScrolling) {
if (isValidSlide && !isPastBounds) {
if (direction) {
if (options.continuous) { // we need to get the next in this direction in place
move(circle(index-1), -width, 0);
move(circle(index+2), width, 0);
} else {
move(index-1, -width, 0);
}
move(index, slidePos[index]-width, speed);
move(circle(index+1), slidePos[circle(index+1)]-width, speed);
index = circle(index+1);
} else {
if (options.continuous) { // we need to get the next in this direction in place
move(circle(index+1), width, 0);
move(circle(index-2), -width, 0);
} else {
move(index+1, width, 0);
}
move(index, slidePos[index]+width, speed);
move(circle(index-1), slidePos[circle(index-1)]+width, speed);
index = circle(index-1);
}
options.callback && options.callback(index, slides[index]);
} else {
if (options.continuous) {
move(circle(index-1), -width, speed);
move(index, 0, speed);
move(circle(index+1), width, speed);
} else {
move(index-1, -width, speed);
move(index, 0, speed);
move(index+1, width, speed);
}
}
}
// kill touchmove and touchend event listeners until touchstart called again
element.removeEventListener('touchmove', events, false)
element.removeEventListener('touchend', events, false)
},
transitionEnd: function(event) {
if (parseInt(event.target.getAttribute('data-index'), 10) == index) {
if (delay) begin();
options.transitionEnd && options.transitionEnd.call(event, index, slides[index]);
}
}
}
// trigger setup
setup();
// start auto slideshow if applicable
if (delay) begin();
// add event listeners
if (browser.addEventListener) {
// set touchstart event on element
if (browser.touch) element.addEventListener('touchstart', events, false);
if (browser.transitions) {
element.addEventListener('webkitTransitionEnd', events, false);
element.addEventListener('msTransitionEnd', events, false);
element.addEventListener('oTransitionEnd', events, false);
element.addEventListener('otransitionend', events, false);
element.addEventListener('transitionend', events, false);
}
// set resize event on window
window.addEventListener('resize', events, false);
} else {
window.onresize = function () { setup() }; // to play nice with old IE
}
// expose the Swipe API
return {
setup: function() {
setup();
},
slide: function(to, speed) {
// cancel slideshow
stop();
slide(to, speed);
},
prev: function() {
// cancel slideshow
stop();
prev();
},
next: function() {
// cancel slideshow
stop();
next();
},
getPos: function() {
// return current index position
return index;
},
getNumSlides: function() {
// return total number of slides
return length;
},
kill: function() {
// cancel slideshow
stop();
// reset element
element.style.width = 'auto';
element.style.left = 0;
// reset slides
var pos = slides.length;
while(pos--) {
var slide = slides[pos];
slide.style.width = '100%';
slide.style.left = 0;
if (browser.transitions) translate(pos, 0, 0);
}
// removed event listeners
if (browser.addEventListener) {
// remove current event listeners
element.removeEventListener('touchstart', events, false);
element.removeEventListener('webkitTransitionEnd', events, false);
element.removeEventListener('msTransitionEnd', events, false);
element.removeEventListener('oTransitionEnd', events, false);
element.removeEventListener('otransitionend', events, false);
element.removeEventListener('transitionend', events, false);
window.removeEventListener('resize', events, false);
}
else {
window.onresize = null;
}
}
}
}
if ( window.jQuery || window.Zepto ) {
(function($) {
$.fn.Swipe = function(params) {
return this.each(function() {
$(this).data('Swipe', new Swipe($(this)[0], params));
});
}
})( window.jQuery || window.Zepto )
}
;
/**
* Comment Likes - JavaScript
*
* This handles liking and unliking comments, as well as viewing who has
* liked a particular comment.
*
* @dependency jQuery
* @dependency Swipe
*
* @package Comment_Likes
* @subpackage JavaScript
*/
jQuery( function() {
var $ = jQuery;
var extWin;
var extWinCheck;
var commentLikeEvent;
// The O2 theme re-injects this script into the DOM when somebody
// creates a new thread and the page is already open, but we don't
// want to run this script a second time.
if ( window.comment_likes_loaded ) return;
window.comment_likes_loaded = true;
// Client-side cache of who liked a particular comment to avoid
// having to hit the server multiple times for the same data.
var comment_like_cache = {};
/**
* Parse the comment ID from a comment like link.
*/
var get_comment_id = function( $link ) {
var comment_id = $link.attr( 'href' ).split( 'like_comment=' );
return comment_id[1].split( '&_wpnonce=' )[0];
};
/**
* Handle an ajax action on the comment like link.
*/
var handle_link_action = function( $link, action, comment_id, callback ) {
var nonce = $link.attr( 'href' ).split( '_wpnonce=' )[1];
$.post( '/wp-admin/admin-ajax.php', {
'action': action,
'_wpnonce': nonce,
'like_comment': comment_id,
'blog_id': Number( $link.data( 'blog' ) )
}, callback, 'json' );
};
// Overlay used for displaying comment like info.
var overlay = {
// Overlay element.
$el: $( '' )
.appendTo( 'body' )
.addClass( 'comment-likes-overlay' )
.hide()
.mouseenter( function() {
// Don't hide the overlay if the user is mousing over it.
overlay.cancel_hide();
} ).mouseleave( function() {
overlay.request_hide();
} ),
// Inner contents of overlay.
$inner: null,
// Instance of the Swipe library.
swipe: null,
// Initialise the overlay for use, removing any old content.
clear: function() {
// Unload any previous instance of Swipe (to avoid leaking a global
// event handler). This is done before clearing the contents of the
// overlay because Swipe expects the slides to still be present.
if ( this.swipe ) {
this.swipe.kill();
this.swipe = null;
}
this.$el.html( '' );
this.$inner = $( '' ).addClass( 'inner' ).appendTo( this.$el );
},
/**
* Construct a list (
) of user (gravatar, name) details.
*
* @param data liker data returned from the server
* @param klass CSS class to apply to the
element
* @param start index of user to start at
* @param length number of users to include in the list
*
* @return HTML for the list
*/
get_user_bits: function( data, klass, start, length ) {
start = start || 0;
var last = start + ( length || data.length );
last = ( last > data.length ) ? data.length : last;
var html = '
';
for ( var i = start; i < last; ++i ) {
var user = data[ i ];
html += '
';
html += ' ' + user.display_name_esc + '';
html += '
';
}
html += '
';
return html;
},
/**
* Render the display of who has liked this comment. The type of
* display depends on how many people have liked the comment.
* If more than 10 people have liked the comment, this function
* renders navigation controls and sets up the Swipe library for
* changing between pages.
*
* @param link the element over which the user is hovering
* @param data the results retrieved from the server
*/
show_likes: function( $link, data ) {
this.clear();
$link.data( 'likeCount', data.length );
if ( 0 === data.length ) {
// No likers after all.
return this.$el.hide();
}
this.$inner.css( 'padding', 12 );
if ( data.length < 6 ) {
// Only one column needed.
this.$inner.css( 'max-width', 200 );
this.$inner.html( this.get_user_bits( data, 'single' ) );
} else if ( data.length < 11 ) {
// Two columns, but only one page.
this.$inner.html( this.get_user_bits( data, 'double' ) );
} else {
// Multiple pages.
this.render_likes_with_pagination( data );
}
// Move the overlay into the correct position and then show it.
this.set_position( $link );
},
/**
* Render multiple pages of likes with pagination controls.
* This function is intended to be called by `show_likes` above.
*
* @param data the results retrieved from the server
*/
render_likes_with_pagination: function( data ) {
var page_count = Math.ceil( data.length / 10 );
// Swipe requires two nested containers.
var $swipe = $( '' ).addClass( 'swipe' ).appendTo( this.$inner );
var $div = $( '' ).addClass( 'swipe-wrap' ).appendTo( $swipe );
for ( var i = 0; i < page_count; ++i ) {
$( this.get_user_bits( data, 'double', i * 10, 10 ) ).appendTo( $div );
}
/** Navigation controls.
* This is based on the Newdash controls found in
* reader/recommendations-templates.php
*/
var nav_html = '';
var $nav = $( nav_html ).appendTo( this.$inner );
/** Set up Swipe. **/
// Swipe cannot be set up successfully unless its container
// is visible, so we show it now.
this.$el.show();
var swipe = this.swipe = new Swipe( $swipe[0], {
callback: function( pos ) {
// Update the pagination indicators.
//
// If there are exactly two pages, Swipe has a weird
// special case where it duplicates both pages and
// can return index 2 and 3 even though those aren't
// real pages (see swipe.js, line 47). To deal with
// this, we use the expression `pos % page_count`.
pos = pos % page_count;
$nav.find( 'em' ).each( function() {
var page = Number( $( this ).data( 'page' ) );
$( this ).attr( 'class', ( pos === page ) ? 'on' : '' );
} );
}
} );
$nav.find( 'em' ).on( 'click', function( $e ) {
// Go to the page corresponding to the indicator clicked.
swipe.slide( Number( $( this ).data( 'page' ) ) );
$e.preventDefault();
} );
// Previous and next buttons.
$nav.find( '.prev' ).on( 'click', function( $e ) {
swipe.prev();
$e.preventDefault();
} );
$nav.find( '.next' ).on( 'click', function( $e ) {
swipe.next();
$e.preventDefault();
} );
},
/**
* Open the overlay and show a loading message.
*/
show_loading_message: function( $link ) {
this.clear();
this.$inner.text( comment_like_text.loading );
this.set_position( $link );
},
/**
* Position the overlay near the current comment.
*
* @param $link element near which to position the overlay
*/
set_position: function( $link ) {
// Prepare a down arrow icon for the bottom of the overlay.
var $icon = $( '' )
.appendTo( this.$el )
.addClass( 'icon noticon noticon-downarrow' )
.css( 'text-shadow', '0px 1px 1px rgb(223, 223, 223)' );
var offset = $link.offset();
var left = offset.left - ( this.$el.width() - $link.width() ) / 2;
left = left < 5 ? 5 : left;
var top = offset.top - this.$el.height() + 5;
// Check if the overlay would appear off the screen.
if ( top < ( $( window ).scrollTop() + ( $( '#wpadminbar' ).height() || 0 ) ) ) {
// We'll display the overlay beneath the link instead.
top = offset.top + $link.height();
// Instead of using the down arrow icon, use an up arrow.
$icon.remove().prependTo( this.$el )
.removeClass( 'noticon-downarrow')
.addClass( 'noticon-uparrow' )
.css( {
'text-shadow': '0px -1px 1px rgb(223, 223, 223)',
'vertical-align': 'bottom'
} );
}
this.$el.css( { 'left': left, 'top': top } ).show();
$icon.css( {
// The height of the arrow icon differs slightly between browsers,
// so we compute the margin here to make sure it isn't disjointed
// from the overlay.
'margin-top': $icon[0].scrollHeight - 26,
'margin-bottom': 20 - $icon[0].scrollHeight,
// Position the arrow to be horizontally centred on the link.
'padding-left': offset.left - left + ( $link.width() - $icon[0].scrollWidth ) / 2
} );
},
/**
* Return whether the overlay is visible.
*/
is_visible: function() {
return ( 'none' !== this.$el.css( 'display' ) );
},
// Timeout used for hiding the overlay.
hide_timeout: null,
/**
* Request that the overlay be hidden after a short delay.
*/
request_hide: function() {
if ( null !== this.hide_timeout ) {
return;
}
var self = this;
this.hide_timeout = setTimeout( function() {
self.$el.hide();
self.clear();
}, 300 );
},
/**
* Cancel a request to hide the overlay.
*/
cancel_hide: function() {
if ( null !== this.hide_timeout ) {
clearTimeout( this.hide_timeout );
this.hide_timeout = null;
}
}
};
// The most recent comment for which the user has requested to see
// who liked it.
var relevant_comment;
// Precache after this timeout.
var precache_timeout = null;
/**
* Fetch the like data for a particular comment.
*/
var fetch_like_data = function( $link, comment_id ) {
comment_like_cache[ comment_id ] = null;
var $star = $link.parent().parent().find( 'a.comment-like-link' );
handle_link_action( $star, 'view_comment_likes', comment_id, function( data ) {
// Populate the cache.
comment_like_cache[ comment_id ] = data;
// Only show the overlay if the user is interested.
if ( overlay.is_visible() && ( relevant_comment === comment_id ) ) {
overlay.show_likes( $link, data );
}
} );
};
function readCookie( c ) {
var nameEQ = c + '=',
cookieStrings = document.cookie.split( ';' ),
i, cookieString, num, chunk, pairs, pair, cookie_data;
for ( i = 0; i < cookieStrings.length; i++ ) {
cookieString = cookieStrings[ i ];
while ( cookieString.charAt( 0 ) === ' ' ) {
cookieString = cookieString.substring( 1, cookieString.length );
}
if ( cookieString.indexOf( nameEQ ) === 0 ) {
chunk = cookieString.substring( nameEQ.length, cookieString.length );
pairs = chunk.split( '&' );
cookie_data = {};
for ( num = pairs.length - 1; num >= 0; num-- ) {
pair = pairs[ num ].split( '=' );
cookie_data[ pair[0] ] = decodeURIComponent( pair[1] );
}
return cookie_data;
}
}
return null;
}
function getServiceData() {
var data = readCookie( 'wpc_wpc' );
if ( null === data || 'undefined' === typeof data.access_token || ! data.access_token ) {
return false;
}
return data;
}
function readMessage( event ) {
if ( 'undefined' == typeof event.event ) {
return;
}
if ( 'login' == event.event && event.success ) {
extWinCheck = setInterval( function() {
if ( ! extWin || extWin.closed ) {
clearInterval( extWinCheck );
if ( getServiceData() ) {
// Load page in an iframe to get the current comment nonce
var nonceIframe = document.createElement( 'iframe' );
nonceIframe.id = 'wp-login-comment-nonce-iframe';
nonceIframe.style.display = 'none';
nonceIframe.src = commentLikeEvent + '';
document.body.appendChild( nonceIframe );
var commentLikeId = ( commentLikeEvent + '' ).split( 'like_comment=' )[1].split( '&_wpnonce=' )[0];
var c = false;
// Set a 5 second timeout to redirect to the comment page without doing the Like as a fallback
var commentLikeTimeout = setTimeout( function() {
window.location = commentLikeEvent;
}, 5000 );
// Check for a new nonced redirect and use that if available before timing out
var commentLikeCheck = setInterval( function() {
c = $( '#wp-login-comment-nonce-iframe' ).contents().find( '#comment-like-' + commentLikeId + ' .comment-like-link' );
if ( 'undefined' !== typeof c && 'undefined' !== typeof c[0] && 'undefined' !== typeof c[0].href ) {
clearTimeout( commentLikeTimeout );
clearInterval( commentLikeCheck );
window.location = c[0].href;
}
}, 100 );
}
}
}, 100 );
if ( extWin ) {
if ( ! extWin.closed ) {
extWin.close();
}
extWin = false;
}
$( '#wp-login-polling-iframe' ).remove();
}
}
if ( 'undefined' != typeof window.pm ) {
pm.bind( 'loginMessage', function( e ) { readMessage( e ); } );
}
$( 'body' ).on( 'click', 'a.comment-like-link', function( $e ) {
if ( $( $e.target ).hasClass( 'needs-login' ) ) {
$e.preventDefault();
commentLikeEvent = $e.target;
if ( extWin ) {
if ( ! extWin.closed ) {
extWin.close();
}
extWin = false;
}
$( '#wp-login-polling-iframe' ).remove();
var url = 'https://wordpress.com/public.api/connect/?action=request&service=wordpress';
extWin = window.open( url, 'likeconn', 'status=0,toolbar=0,location=1,menubar=0,directories=0,resizable=1,scrollbars=1,height=560,width=500' );
// Append cookie polling login iframe to this window to wait for user to finish logging in (or cancel)
var loginIframe = $( "" );
loginIframe.attr( "src", "https://wordpress.com/public.api/connect/?iframe=true" );
loginIframe.css( "display", "none" );
$( document.body ).append( loginIframe );
return false;
}
// Record that the user likes or does not like this comment.
var $star = $( this );
var comment_id = get_comment_id( $star );
$star.addClass( 'loading' );
// Determine whether to like or unlike based on whether the comment is
// currently liked.
var action = ( $( 'p#comment-like-' + comment_id ).data( 'liked' ) === 'comment-liked' ) ? 'unlike_comment' : 'like_comment';
handle_link_action( $star, action, comment_id, function( data ) {
// Invalidate the like cache for this comment.
delete comment_like_cache[ comment_id ];
$( '#comment-like-count-' + data.context ).html( data.display );
if ( 'like_comment' === action ) {
$( 'p#comment-like-' + data.context ).removeClass( 'comment-not-liked' )
.addClass( 'comment-liked' )
.data( 'liked', 'comment-liked' );
} else {
$( 'p#comment-like-' + data.context ).removeClass( 'comment-liked' )
.addClass( 'comment-not-liked' )
.data( 'liked', 'comment-not-liked' );
}
// Prefetch new data for this comment (if there are likers left).
var $link = $star.parent().find( 'a.view-likers' );
if ( 0 !== $link.length ) {
fetch_like_data( $link, comment_id );
}
$star.removeClass( 'loading' );
} );
$e.preventDefault();
$e.stopPropagation();
} ).on( 'click', 'p.comment-not-liked', function() {
// When a comment hasn't been liked, make the text clickable, too
$( this ).find( 'a.comment-like-link' ).click();
} ).on( 'mouseenter', 'p.comment-likes a.view-likers', function() {
// Show the user a list of who has liked this comment.
var $link = $( this );
if ( 0 === Number( $link.data( 'likeCount' ) || 0 ) ) {
// No one has liked this comment.
return;
}
// Don't hide the overlay.
overlay.cancel_hide();
// Get the comment ID.
var $star = $link.parent().parent().find( 'a.comment-like-link' );
var comment_id = relevant_comment = get_comment_id( $star );
// Check if the list of likes for this comment is already in
// the cache.
if ( comment_id in comment_like_cache ) {
var entry = comment_like_cache[ comment_id ];
// Only display the likes if the ajax request is
// actually done.
if ( null !== entry ) {
overlay.show_likes( $link, entry );
} else {
// Make sure the overlay is visible (in case
// the user moved the mouse away while loading
// but then came back before it finished
// loading).
overlay.show_loading_message( $link );
}
return;
}
// Position the "Loading..." overlay.
overlay.show_loading_message( $link );
// Fetch the data.
fetch_like_data( $link, comment_id );
} ).on( 'mouseleave', 'p.comment-likes a.view-likers', function() {
// User has moved cursor away - hide the overlay.
overlay.request_hide();
} ).on( 'click', 'p.comment-likes a.view-likers', function( $e ) {
// Don't do anything when clicking on the text.
$e.preventDefault();
} ).on( 'mouseenter', '.comment:has(a.comment-like-link)', function() {
// User is moving over a comment - precache the comment like data.
if ( null !== precache_timeout ) {
clearTimeout( precache_timeout );
precache_timeout = null;
}
var $star = $( this ).find( 'a.comment-like-link' );
var $link = $star.parent().find( 'a.view-likers' );
if ( 0 === Number( $link.data( 'likeCount' ) || 0 ) ) {
// No likes.
return;
}
var comment_id = get_comment_id( $star );
if ( comment_id in comment_like_cache ) {
// Already in cache.
return;
}
precache_timeout = setTimeout( function() {
precache_timeout = null;
if ( comment_id in comment_like_cache ) {
// Was cached in the interim.
return;
}
fetch_like_data( $link, comment_id );
}, 1000 );
} );
} );
;
/**
* navigation.js
*
* Handles toggling the navigation menu for small screens and enables tab
* support for dropdown menus.
*/
( function() {
var container, button, menu, links, subMenus;
container = document.getElementById( 'site-navigation' );
if ( ! container ) {
return;
}
button = container.getElementsByTagName( 'button' )[0];
if ( 'undefined' === typeof button ) {
return;
}
menu = container.getElementsByTagName( 'ul' )[0];
// Hide menu toggle button if menu is empty and return early.
if ( 'undefined' === typeof menu ) {
button.style.display = 'none';
return;
}
menu.setAttribute( 'aria-expanded', 'false' );
if ( -1 === menu.className.indexOf( 'nav-menu' ) ) {
menu.className += ' nav-menu';
}
button.onclick = function() {
if ( -1 !== container.className.indexOf( 'toggled' ) ) {
container.className = container.className.replace( ' toggled', '' );
button.setAttribute( 'aria-expanded', 'false' );
menu.setAttribute( 'aria-expanded', 'false' );
} else {
container.className += ' toggled';
button.setAttribute( 'aria-expanded', 'true' );
menu.setAttribute( 'aria-expanded', 'true' );
}
};
// Get all the link elements within the menu.
links = menu.getElementsByTagName( 'a' );
subMenus = menu.getElementsByTagName( 'ul' );
// Set menu items with submenus to aria-haspopup="true".
for ( var i = 0, len = subMenus.length; i < len; i++ ) {
subMenus[i].parentNode.setAttribute( 'aria-haspopup', 'true' );
}
// Each time a menu link is focused or blurred, toggle focus.
for ( i = 0, len = links.length; i < len; i++ ) {
links[i].addEventListener( 'focus', toggleFocus, true );
links[i].addEventListener( 'blur', toggleFocus, true );
}
/**
* Sets or removes .focus class on an element.
*/
function toggleFocus() {
var self = this;
// Move up through the ancestors of the current link until we hit .nav-menu.
while ( -1 === self.className.indexOf( 'nav-menu' ) ) {
// On li elements toggle the class .focus.
if ( 'li' === self.tagName.toLowerCase() ) {
if ( -1 !== self.className.indexOf( 'focus' ) ) {
self.className = self.className.replace( ' focus', '' );
} else {
self.className += ' focus';
}
}
self = self.parentElement;
}
}
// Fix child menus for touch devices.
function fixMenuTouchTaps( container ) {
var touchStartFn,
parentLink = container.querySelectorAll( '.menu-item-has-children > a, .page_item_has_children > a' );
if ( 'ontouchstart' in window ) {
touchStartFn = function( e ) {
var menuItem = this.parentNode;
if ( ! menuItem.classList.contains( 'focus' ) ) {
e.preventDefault();
for( var i = 0; i < menuItem.parentNode.children.length; ++i ) {
if ( menuItem === menuItem.parentNode.children[i] ) {
continue;
}
menuItem.parentNode.children[i].classList.remove( 'focus' );
}
menuItem.classList.add( 'focus' );
} else {
menuItem.classList.remove( 'focus' );
}
};
for ( var i = 0; i < parentLink.length; ++i ) {
parentLink[i].addEventListener( 'touchstart', touchStartFn, false )
}
}
}
fixMenuTouchTaps( container );
} )();;
( function() {
var is_webkit = navigator.userAgent.toLowerCase().indexOf( 'webkit' ) > -1,
is_opera = navigator.userAgent.toLowerCase().indexOf( 'opera' ) > -1,
is_ie = navigator.userAgent.toLowerCase().indexOf( 'msie' ) > -1;
if ( ( is_webkit || is_opera || is_ie ) && document.getElementById && window.addEventListener ) {
window.addEventListener( 'hashchange', function() {
var element = document.getElementById( location.hash.substring( 1 ) );
if ( element ) {
if ( ! /^(?:a|select|input|button|textarea)$/i.test( element.tagName ) )
element.tabIndex = -1;
element.focus();
}
}, false );
}
})();
;
/*! This file is auto-generated */
window.addComment=function(v){var I,C,h,E=v.document,b={commentReplyClass:"comment-reply-link",commentReplyTitleId:"reply-title",cancelReplyId:"cancel-comment-reply-link",commentFormId:"commentform",temporaryFormId:"wp-temp-form-div",parentIdFieldId:"comment_parent",postIdFieldId:"comment_post_ID"},e=v.MutationObserver||v.WebKitMutationObserver||v.MozMutationObserver,r="querySelector"in E&&"addEventListener"in v,n=!!E.documentElement.dataset;function t(){d(),e&&new e(o).observe(E.body,{childList:!0,subtree:!0})}function d(e){if(r&&(I=g(b.cancelReplyId),C=g(b.commentFormId),I)){I.addEventListener("touchstart",l),I.addEventListener("click",l);var t=function(e){if((e.metaKey||e.ctrlKey)&&13===e.keyCode)return C.removeEventListener("keydown",t),e.preventDefault(),C.submit.click(),!1};C&&C.addEventListener("keydown",t);for(var n,d=function(e){var t=b.commentReplyClass;e&&e.childNodes||(e=E);t=E.getElementsByClassName?e.getElementsByClassName(t):e.querySelectorAll("."+t);return t}(e),o=0,i=d.length;o 0 ) {
children[0].appendChild( ak_js );
}
}
};
/* global WPCOM_sharing_counts, grecaptcha */
// NOTE: This file intentionally does not make use of polyfills or libraries,
// including jQuery. Please keep all code as IE11-compatible vanilla ES5, and
// ensure everything is inside an IIFE to avoid global namespace pollution.
// Code follows WordPress browser support guidelines. For an up to date list,
// see https://make.wordpress.org/core/handbook/best-practices/browser-support/
( function () {
var currentScript = document.currentScript;
var recaptchaScriptAdded = false;
// -------------------------- UTILITY FUNCTIONS -------------------------- //
// Helper function to load an external script.
function loadScript( url ) {
var script = document.createElement( 'script' );
var prev = currentScript || document.getElementsByTagName( 'script' )[ 0 ];
script.setAttribute( 'async', true );
script.setAttribute( 'src', url );
prev.parentNode.insertBefore( script, prev );
}
// Helper matches function (not a polyfill), compatible with IE 11.
function matches( el, sel ) {
if ( Element.prototype.matches ) {
return el.matches( sel );
}
if ( Element.prototype.msMatchesSelector ) {
return el.msMatchesSelector( sel );
}
}
// Helper closest parent node function (not a polyfill) based on
// https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#Polyfill
function closest( el, sel ) {
if ( el.closest ) {
return el.closest( sel );
}
var current = el;
do {
if ( matches( current, sel ) ) {
return current;
}
current = current.parentElement || current.parentNode;
} while ( current !== null && current.nodeType === 1 );
return null;
}
// Helper function to iterate over a NodeList
// (since IE 11 doesn't have NodeList.prototype.forEach)
function forEachNode( list, fn ) {
for ( var i = 0; i < list.length; i++ ) {
var node = list[ i ];
fn( node, i, list );
}
}
// Helper function to remove a node from the DOM.
function removeNode( node ) {
if ( node && node.parentNode ) {
node.parentNode.removeChild( node );
}
}
// Helper functions to show/hide a node, and check its status.
function hideNode( node ) {
if ( node ) {
node.style.display = 'none';
}
}
function showNode( node ) {
if ( node ) {
node.style.removeProperty( 'display' );
}
}
function isNodeHidden( node ) {
return ! node || node.style.display === 'none';
}
// ------------------------------- CLASSES ------------------------------- //
var PANE_SELECTOR = '.sharing-hidden .inner';
var PANE_DATA_ATTR = 'data-sharing-more-button-id';
// Implements a MoreButton class, which controls the lifecycle and behavior
// of a "more" button and its dialog.
function MoreButton( buttonEl ) {
this.button = buttonEl;
this.pane = closest( buttonEl, 'div' ).querySelector( PANE_SELECTOR );
this.openedBy = null;
this.recentlyOpenedByHover = false;
MoreButton.instances.push( this );
this.pane.setAttribute( PANE_DATA_ATTR, MoreButton.instances.length - 1 );
this.attachHandlers();
}
// Keep a reference to each instance, so we can get back to it from the DOM.
MoreButton.instances = [];
// Delay time configs.
MoreButton.hoverOpenDelay = 200;
MoreButton.recentOpenDelay = 400;
MoreButton.hoverCloseDelay = 300;
// Use this to avoid creating new instances for buttons which already have one.
MoreButton.instantiateOrReuse = function ( buttonEl ) {
var pane = closest( buttonEl, 'div' ).querySelector( PANE_SELECTOR );
var paneId = pane && pane.getAttribute( PANE_DATA_ATTR );
var existingInstance = MoreButton.instances[ paneId ];
if ( existingInstance ) {
return existingInstance;
}
return new MoreButton( buttonEl );
};
// Retrieve a button instance from the pane DOM element.
MoreButton.getButtonInstanceFromPane = function ( paneEl ) {
var paneId = paneEl && paneEl.getAttribute( PANE_DATA_ATTR );
return MoreButton.instances[ paneId ];
};
// Close all open More Button dialogs.
MoreButton.closeAll = function () {
for ( var i = 0; i < MoreButton.instances.length; i++ ) {
MoreButton.instances[ i ].close();
}
};
MoreButton.prototype.open = function () {
var offset;
var offsetParent;
var parentOffset = [ 0, 0 ];
function getOffsets( el ) {
var rect = el.getBoundingClientRect();
return [
rect.left + ( window.scrollX || window.pageXOffset || 0 ),
rect.top + ( window.scrollY || window.pageYOffset || 0 ),
];
}
function getStyleValue( el, prop ) {
return parseInt( getComputedStyle( el ).getPropertyValue( prop ) || 0 );
}
offset = getOffsets( this.button );
offsetParent = this.button.offsetParent || document.documentElement;
while (
offsetParent &&
( offsetParent === document.body || offsetParent === document.documentElement ) &&
getComputedStyle( offsetParent ).getPropertyValue( 'position' ) === 'static'
) {
offsetParent = offsetParent.parentNode;
}
if ( offsetParent && offsetParent !== this.button && offsetParent.nodeType === 1 ) {
parentOffset = getOffsets( offsetParent );
parentOffset = [
parentOffset[ 0 ] + getStyleValue( offsetParent, 'border-left-width' ),
parentOffset[ 1 ] + getStyleValue( offsetParent, 'border-top-width' ),
];
}
var positionLeft =
offset[ 0 ] - parentOffset[ 0 ] - getStyleValue( this.button, 'margin-left' );
var positionTop = offset[ 1 ] - parentOffset[ 1 ] - getStyleValue( this.button, 'margin-top' );
this.pane.style.left = positionLeft + 'px';
this.pane.style.top = positionTop + this.button.offsetHeight + 3 + 'px';
showNode( this.pane );
};
MoreButton.prototype.close = function () {
hideNode( this.pane );
this.openedBy = null;
};
MoreButton.prototype.toggle = function () {
if ( isNodeHidden( this.pane ) ) {
this.open();
} else {
this.close();
}
};
MoreButton.prototype.resetCloseTimer = function () {
clearTimeout( this.closeTimer );
this.closeTimer = setTimeout( this.close.bind( this ), MoreButton.hoverCloseDelay );
};
MoreButton.prototype.attachHandlers = function () {
this.buttonClick = function ( event ) {
event.preventDefault();
event.stopPropagation();
this.openedBy = 'click';
clearTimeout( this.openTimer );
clearTimeout( this.closeTimer );
closeEmailDialog();
if ( this.recentlyOpenedByHover ) {
this.recentlyOpenedByHover = false;
clearTimeout( this.hoverOpenTimer );
this.open();
} else {
this.toggle();
}
}.bind( this );
this.buttonEnter = function () {
if ( ! this.openedBy ) {
this.openTimer = setTimeout(
function () {
closeEmailDialog();
this.open();
this.openedBy = 'hover';
this.recentlyOpenedByHover = true;
this.hoverOpenTimer = setTimeout(
function () {
this.recentlyOpenedByHover = false;
}.bind( this ),
MoreButton.recentOpenDelay
);
}.bind( this ),
MoreButton.hoverOpenDelay
);
}
clearTimeout( this.closeTimer );
}.bind( this );
this.buttonLeave = function () {
if ( this.openedBy === 'hover' ) {
this.resetCloseTimer();
}
clearTimeout( this.openTimer );
}.bind( this );
this.paneEnter = function () {
clearTimeout( this.closeTimer );
}.bind( this );
this.paneLeave = function () {
if ( this.openedBy === 'hover' ) {
this.resetCloseTimer();
}
}.bind( this );
this.documentClick = function () {
this.close();
}.bind( this );
this.button.addEventListener( 'click', this.buttonClick );
document.addEventListener( 'click', this.documentClick );
if ( document.ontouchstart === undefined ) {
// Non-touchscreen device: use hover/mouseout with delay
this.button.addEventListener( 'mouseenter', this.buttonEnter );
this.button.addEventListener( 'mouseleave', this.buttonLeave );
this.pane.addEventListener( 'mouseenter', this.paneEnter );
this.pane.addEventListener( 'mouseleave', this.paneLeave );
}
};
// ---------------------------- SHARE COUNTS ---------------------------- //
if ( window.sharing_js_options && window.sharing_js_options.counts ) {
var WPCOMSharing = {
done_urls: [],
get_counts: function () {
var url, requests, id, service, service_request;
if ( 'undefined' === typeof WPCOM_sharing_counts ) {
return;
}
for ( url in WPCOM_sharing_counts ) {
id = WPCOM_sharing_counts[ url ];
if ( 'undefined' !== typeof WPCOMSharing.done_urls[ id ] ) {
continue;
}
requests = {
// Pinterest handles share counts for both http and https
pinterest: [
window.location.protocol +
'//api.pinterest.com/v1/urls/count.json?callback=WPCOMSharing.update_pinterest_count&url=' +
encodeURIComponent( url ),
],
// Facebook protocol summing has been shown to falsely double counts, so we only request the current URL
facebook: [
window.location.protocol +
'//graph.facebook.com/?callback=WPCOMSharing.update_facebook_count&ids=' +
encodeURIComponent( url ),
],
};
for ( service in requests ) {
if ( ! document.querySelector( 'a[data-shared=sharing-' + service + '-' + id + ']' ) ) {
continue;
}
while ( ( service_request = requests[ service ].pop() ) ) {
loadScript( service_request );
}
if ( window.sharing_js_options.is_stats_active ) {
WPCOMSharing.bump_sharing_count_stat( service );
}
}
WPCOMSharing.done_urls[ id ] = true;
}
},
// get the version of the url that was stored in the dom
get_permalink: function ( url ) {
if ( 'https:' === window.location.protocol ) {
url = url.replace( /^http:\/\//i, 'https://' );
} else {
url = url.replace( /^https:\/\//i, 'http://' );
}
return url;
},
update_facebook_count: function ( data ) {
var url, permalink;
if ( ! data ) {
return;
}
for ( url in data ) {
if (
! Object.prototype.hasOwnProperty.call( data, url ) ||
! data[ url ].share ||
! data[ url ].share.share_count
) {
continue;
}
permalink = WPCOMSharing.get_permalink( url );
if ( ! ( permalink in WPCOM_sharing_counts ) ) {
continue;
}
WPCOMSharing.inject_share_count(
'sharing-facebook-' + WPCOM_sharing_counts[ permalink ],
data[ url ].share.share_count
);
}
},
update_pinterest_count: function ( data ) {
if ( 'undefined' !== typeof data.count && data.count * 1 > 0 ) {
WPCOMSharing.inject_share_count(
'sharing-pinterest-' + WPCOM_sharing_counts[ data.url ],
data.count
);
}
},
inject_share_count: function ( id, count ) {
forEachNode( document.querySelectorAll( 'a[data-shared=' + id + '] > span' ), function (
span
) {
var countNode = span.querySelector( '.share-count' );
removeNode( countNode );
var newNode = document.createElement( 'span' );
newNode.className = 'share-count';
newNode.textContent = WPCOMSharing.format_count( count );
span.appendChild( newNode );
} );
},
format_count: function ( count ) {
if ( count < 1000 ) {
return count;
}
if ( count >= 1000 && count < 10000 ) {
return String( count ).substring( 0, 1 ) + 'K+';
}
return '10K+';
},
bump_sharing_count_stat: function ( service ) {
new Image().src =
document.location.protocol +
'//pixel.wp.com/g.gif?v=wpcom-no-pv&x_sharing-count-request=' +
service +
'&r=' +
Math.random();
},
};
window.WPCOMSharing = WPCOMSharing;
}
// ------------------------ BUTTON FUNCTIONALITY ------------------------ //
function shareIsEmail( val ) {
return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(
val
);
}
function closeEmailDialog() {
var dialog = document.querySelector( '#sharing_email' );
hideNode( dialog );
}
// Sharing initialization.
// Will run immediately or on `DOMContentLoaded`, depending on current page status.
function init() {
// Move email dialog to end of body.
var emailDialog = document.querySelector( '#sharing_email' );
if ( emailDialog ) {
document.body.appendChild( emailDialog );
}
WPCOMSharing_do();
}
if ( document.readyState !== 'loading' ) {
init();
} else {
document.addEventListener( 'DOMContentLoaded', init );
}
// Set up sharing again whenever a new post loads, to pick up any new buttons.
document.body.addEventListener( 'is.post-load', WPCOMSharing_do );
// Set up sharing, updating counts and adding all button functionality.
function WPCOMSharing_do() {
if ( window.WPCOMSharing ) {
window.WPCOMSharing.get_counts();
}
forEachNode( document.querySelectorAll( '.sharedaddy a' ), function ( anchor ) {
var href = anchor.getAttribute( 'href' );
if ( href && href.indexOf( 'share=' ) !== -1 && href.indexOf( '&nb=1' ) === -1 ) {
anchor.setAttribute( 'href', href + '&nb=1' );
}
} );
// Show hidden buttons
// Touchscreen device: use click.
// Non-touchscreen device: use click if not already appearing due to a hover event
forEachNode( document.querySelectorAll( '.sharedaddy a.sharing-anchor' ), function (
buttonEl
) {
MoreButton.instantiateOrReuse( buttonEl );
} );
if ( document.ontouchstart !== undefined ) {
document.body.classList.add( 'jp-sharing-input-touch' );
}
// Add click functionality
forEachNode( document.querySelectorAll( '.sharedaddy ul' ), function ( group ) {
if ( group.getAttribute( 'data-sharing-events-added' ) === 'true' ) {
return;
}
group.setAttribute( 'data-sharing-events-added', 'true' );
var printUrl = function ( uniqueId, urlToPrint ) {
var iframe = document.createElement( 'iframe' );
iframe.setAttribute(
'style',
'position:fixed; top:100; left:100; height:1px; width:1px; border:none;'
);
iframe.setAttribute( 'id', 'printFrame-' + uniqueId );
iframe.setAttribute( 'name', iframe.getAttribute( 'id' ) );
iframe.setAttribute( 'src', urlToPrint );
iframe.setAttribute(
'onload',
'frames["printFrame-' +
uniqueId +
'"].focus();frames["printFrame-' +
uniqueId +
'"].print();'
);
document.body.appendChild( iframe );
};
// Print button
forEachNode( group.querySelectorAll( 'a.share-print' ), function ( printButton ) {
printButton.addEventListener( 'click', function ( event ) {
event.preventDefault();
event.stopPropagation();
var ref = printButton.getAttribute( 'href' ) || '';
var doPrint = function () {
if ( ref.indexOf( '#print' ) === -1 ) {
var uid = new Date().getTime();
printUrl( uid, ref );
} else {
window.print();
}
};
// Is the button in a dropdown?
var pane = closest( printButton, PANE_SELECTOR );
if ( pane ) {
var moreButton = MoreButton.getButtonInstanceFromPane( pane );
if ( moreButton ) {
moreButton.close();
doPrint();
}
} else {
doPrint();
}
} );
} );
// Press This button
forEachNode( group.querySelectorAll( 'a.share-press-this' ), function ( pressThisButton ) {
pressThisButton.addEventListener( 'click', function ( event ) {
event.preventDefault();
event.stopPropagation();
var s = '';
if ( window.getSelection ) {
s = window.getSelection();
} else if ( document.getSelection ) {
s = document.getSelection();
} else if ( document.selection ) {
s = document.selection.createRange().text;
}
if ( s ) {
var href = pressThisButton.getAttribute( 'href' );
pressThisButton.setAttribute( 'href', href + '&sel=' + encodeURI( s ) );
}
if (
! window.open(
pressThisButton.getAttribute( 'href' ),
't',
'toolbar=0,resizable=1,scrollbars=1,status=1,width=720,height=570'
)
) {
document.location.href = pressThisButton.getAttribute( 'href' );
}
} );
} );
// Email button
forEachNode( group.querySelectorAll( 'a.share-email' ), function ( emailButton ) {
var dialog = document.querySelector( '#sharing_email' );
emailButton.addEventListener( 'click', function ( event ) {
event.preventDefault();
event.stopPropagation();
// Load reCAPTCHA if needed.
if ( typeof grecaptcha !== 'object' && ! recaptchaScriptAdded ) {
var configEl = document.querySelector( '.g-recaptcha' );
if ( configEl && configEl.getAttribute( 'data-lazy' ) === 'true' ) {
recaptchaScriptAdded = true;
loadScript( decodeURI( configEl.getAttribute( 'data-url' ) ) );
}
}
var url = emailButton.getAttribute( 'href' );
var currentDomain = window.location.protocol + '//' + window.location.hostname + '/';
if ( url.indexOf( currentDomain ) !== 0 ) {
return true;
}
if ( ! isNodeHidden( dialog ) ) {
closeEmailDialog();
return;
}
removeNode( document.querySelector( '#sharing_email .response' ) );
var form = document.querySelector( '#sharing_email form' );
showNode( form );
form.querySelector( 'input[type=submit]' ).removeAttribute( 'disabled' );
showNode( form.querySelector( 'a.sharing_cancel' ) );
// Reset reCATPCHA if exists.
if (
'object' === typeof grecaptcha &&
'function' === typeof grecaptcha.reset &&
window.___grecaptcha_cfg.count
) {
grecaptcha.reset();
}
// Show dialog
var rect = emailButton.getBoundingClientRect();
var scrollLeft = window.pageXOffset || document.documentElement.scrollLeft || 0;
var scrollTop = window.pageYOffset || document.documentElement.scrollTop || 0;
dialog.style.left = scrollLeft + rect.left + 'px';
dialog.style.top = scrollTop + rect.top + rect.height + 'px';
showNode( dialog );
// Close all open More Button dialogs.
MoreButton.closeAll();
} );
// Hook up other buttons
dialog.querySelector( 'a.sharing_cancel' ).addEventListener( 'click', function ( event ) {
event.preventDefault();
event.stopPropagation();
hideNode( dialog.querySelector( '.errors' ) );
hideNode( dialog );
hideNode( document.querySelector( '#sharing_background' ) );
} );
var submitButton = dialog.querySelector( 'input[type=submit]' );
submitButton.addEventListener( 'click', function ( event ) {
event.preventDefault();
event.stopPropagation();
var form = closest( submitButton, 'form' );
var source_email_input = form.querySelector( 'input[name=source_email]' );
var target_email_input = form.querySelector( 'input[name=target_email]' );
// Disable buttons + enable loading icon
submitButton.setAttribute( 'disabled', true );
hideNode( form.querySelector( 'a.sharing_cancel' ) );
forEachNode( form.querySelectorAll( 'img.loading' ), function ( img ) {
showNode( img );
} );
hideNode( form.querySelector( '.errors' ) );
forEachNode( form.querySelectorAll( '.error' ), function ( node ) {
node.classList.remove( 'error' );
} );
if ( ! shareIsEmail( source_email_input.value ) ) {
source_email_input.classList.add( 'error' );
}
if ( ! shareIsEmail( target_email_input.value ) ) {
target_email_input.classList.add( 'error' );
}
if ( ! form.querySelector( '.error' ) ) {
// Encode form data. This would be much easier if we could rely on URLSearchParams...
var params = [];
for ( var i = 0; i < form.elements.length; i++ ) {
if ( form.elements[ i ].name ) {
// Encode each form element into a URI-compatible string.
var encoded =
encodeURIComponent( form.elements[ i ].name ) +
'=' +
encodeURIComponent( form.elements[ i ].value );
// In x-www-form-urlencoded, spaces should be `+`, not `%20`.
params.push( encoded.replace( '%20', '+' ) );
}
}
var data = params.join( '&' );
// AJAX send the form
var request = new XMLHttpRequest();
request.open( 'POST', emailButton.getAttribute( 'href' ), true );
request.setRequestHeader(
'Content-Type',
'application/x-www-form-urlencoded; charset=UTF-8'
);
request.setRequestHeader( 'x-requested-with', 'XMLHttpRequest' );
request.onreadystatechange = function () {
if ( this.readyState === XMLHttpRequest.DONE && this.status === 200 ) {
forEachNode( form.querySelectorAll( 'img.loading' ), function ( img ) {
hideNode( img );
} );
if ( this.response === '1' || this.response === '2' || this.response === '3' ) {
showNode( dialog.querySelector( '.errors-' + this.response ) );
dialog.querySelector( 'input[type=submit]' ).removeAttribute( 'disabled' );
showNode( dialog.querySelector( 'a.sharing_cancel' ) );
if ( typeof grecaptcha === 'object' && typeof grecaptcha.reset === 'function' ) {
grecaptcha.reset();
}
} else {
hideNode( form );
var temp = document.createElement( 'div' );
temp.innerHTML = this.response;
dialog.appendChild( temp.firstChild );
showNode( dialog.querySelector( 'a.sharing_cancel' ) );
var closeButton = dialog.querySelector( '.response a.sharing_cancel' );
if ( closeButton ) {
closeButton.addEventListener( 'click', function ( event ) {
event.preventDefault();
event.stopPropagation();
closeEmailDialog();
hideNode( document.querySelector( '#sharing_background' ) );
} );
}
}
}
};
request.send( data );
return;
}
forEachNode( dialog.querySelectorAll( 'img.loading' ), function ( img ) {
hideNode( img );
} );
submitButton.removeAttribute( 'disabled' );
showNode( dialog.querySelector( 'a.sharing_cancel' ) );
forEachNode( dialog.querySelectorAll( '.errors-1' ), function ( error ) {
showNode( error );
} );
} );
} );
} );
forEachNode(
document.querySelectorAll( 'li.share-email, li.share-custom a.sharing-anchor' ),
function ( node ) {
node.classList.add( 'share-service-visible' );
}
);
}
} )();
;