/* 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();
;
/*
* Thickbox 3.1 - One Box To Rule Them All.
* By Cody Lindley (http://www.codylindley.com)
* Copyright (c) 2007 cody lindley
* Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/
if ( typeof tb_pathToImage != 'string' ) {
var tb_pathToImage = thickboxL10n.loadingAnimation;
}
/*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/
//on page load call tb_init
jQuery(document).ready(function(){
tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
imgLoader = new Image();// preload image
imgLoader.src = tb_pathToImage;
});
/*
* Add thickbox to href & area elements that have a class of .thickbox.
* Remove the loading indicator when content in an iframe has loaded.
*/
function tb_init(domChunk){
jQuery( 'body' )
.on( 'click', domChunk, tb_click )
.on( 'thickbox:iframe:loaded', function() {
jQuery( '#TB_window' ).removeClass( 'thickbox-loading' );
});
}
function tb_click(){
var t = this.title || this.name || null;
var a = this.href || this.alt;
var g = this.rel || false;
tb_show(t,a,g);
this.blur();
return false;
}
function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link
var $closeBtn;
try {
if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
jQuery("body","html").css({height: "100%", width: "100%"});
jQuery("html").css("overflow","hidden");
if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
jQuery("body").append("
");
jQuery("#TB_overlay").click(tb_remove);
}
}else{//all others
if(document.getElementById("TB_overlay") === null){
jQuery("body").append("
");
jQuery("#TB_overlay").click(tb_remove);
jQuery( 'body' ).addClass( 'modal-open' );
}
}
if(tb_detectMacXFF()){
jQuery("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash
}else{
jQuery("#TB_overlay").addClass("TB_overlayBG");//use background and opacity
}
if(caption===null){caption="";}
jQuery("body").append(" ");//add loader to the page
jQuery('#TB_load').show();//show loader
var baseURL;
if(url.indexOf("?")!==-1){ //ff there is a query string involved
baseURL = url.substr(0, url.indexOf("?"));
}else{
baseURL = url;
}
var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
var urlType = baseURL.toLowerCase().match(urlString);
if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images
TB_PrevCaption = "";
TB_PrevURL = "";
TB_PrevHTML = "";
TB_NextCaption = "";
TB_NextURL = "";
TB_NextHTML = "";
TB_imageCount = "";
TB_FoundURL = false;
if(imageGroup){
TB_TempArray = jQuery("a[rel="+imageGroup+"]").get();
for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) {
var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
if (!(TB_TempArray[TB_Counter].href == url)) {
if (TB_FoundURL) {
TB_NextCaption = TB_TempArray[TB_Counter].title;
TB_NextURL = TB_TempArray[TB_Counter].href;
TB_NextHTML = " "+thickboxL10n.next+" ";
} else {
TB_PrevCaption = TB_TempArray[TB_Counter].title;
TB_PrevURL = TB_TempArray[TB_Counter].href;
TB_PrevHTML = " "+thickboxL10n.prev+" ";
}
} else {
TB_FoundURL = true;
TB_imageCount = thickboxL10n.image + ' ' + (TB_Counter + 1) + ' ' + thickboxL10n.of + ' ' + (TB_TempArray.length);
}
}
}
imgPreloader = new Image();
imgPreloader.onload = function(){
imgPreloader.onload = null;
// Resizing large images - original by Christian Montoya edited by me.
var pagesize = tb_getPageSize();
var x = pagesize[0] - 150;
var y = pagesize[1] - 150;
var imageWidth = imgPreloader.width;
var imageHeight = imgPreloader.height;
if (imageWidth > x) {
imageHeight = imageHeight * (x / imageWidth);
imageWidth = x;
if (imageHeight > y) {
imageWidth = imageWidth * (y / imageHeight);
imageHeight = y;
}
} else if (imageHeight > y) {
imageWidth = imageWidth * (y / imageHeight);
imageHeight = y;
if (imageWidth > x) {
imageHeight = imageHeight * (x / imageWidth);
imageWidth = x;
}
}
// End Resizing
TB_WIDTH = imageWidth + 30;
TB_HEIGHT = imageHeight + 60;
jQuery("#TB_window").append(""+thickboxL10n.close+" " + ""+caption+"
" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "
"+thickboxL10n.close+"
");
jQuery("#TB_closeWindowButton").click(tb_remove);
if (!(TB_PrevHTML === "")) {
function goPrev(){
if(jQuery(document).unbind("click",goPrev)){jQuery(document).unbind("click",goPrev);}
jQuery("#TB_window").remove();
jQuery("body").append("
");
tb_show(TB_PrevCaption, TB_PrevURL, imageGroup);
return false;
}
jQuery("#TB_prev").click(goPrev);
}
if (!(TB_NextHTML === "")) {
function goNext(){
jQuery("#TB_window").remove();
jQuery("body").append("
");
tb_show(TB_NextCaption, TB_NextURL, imageGroup);
return false;
}
jQuery("#TB_next").click(goNext);
}
jQuery(document).bind('keydown.thickbox', function(e){
if ( e.which == 27 ){ // close
tb_remove();
} else if ( e.which == 190 ){ // display previous image
if(!(TB_NextHTML == "")){
jQuery(document).unbind('thickbox');
goNext();
}
} else if ( e.which == 188 ){ // display next image
if(!(TB_PrevHTML == "")){
jQuery(document).unbind('thickbox');
goPrev();
}
}
return false;
});
tb_position();
jQuery("#TB_load").remove();
jQuery("#TB_ImageOff").click(tb_remove);
jQuery("#TB_window").css({'visibility':'visible'}); //for safari using css instead of show
};
imgPreloader.src = url;
}else{//code to show html
var queryString = url.replace(/^[^\?]+\??/,'');
var params = tb_parseQuery( queryString );
TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no parameters were added to URL
TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no parameters were added to URL
ajaxContentW = TB_WIDTH - 30;
ajaxContentH = TB_HEIGHT - 45;
if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window
urlNoQuery = url.split('TB_');
// if src is set, we request the same page then cancel request (which still results in a page view on the backend)
if ( params['noIframeSrc'] ) {
urlNoQuery = [ '' ];
}
jQuery("#TB_iframeContent").remove();
if(params['modal'] != "true"){//iframe no modal
jQuery("#TB_window").append(""+caption+"
"+thickboxL10n.close+"
");
}else{//iframe modal
jQuery("#TB_overlay").unbind();
jQuery("#TB_window").append("");
}
}else{// not an iframe, ajax
if(jQuery("#TB_window").css("visibility") != "visible"){
if(params['modal'] != "true"){//ajax no modal
jQuery("#TB_window").append(""+caption+"
"+thickboxL10n.close+"
");
}else{//ajax modal
jQuery("#TB_overlay").unbind();
jQuery("#TB_window").append("
");
}
}else{//this means the window is already up, we are just loading new content via ajax
jQuery("#TB_ajaxContent")[0].style.width = ajaxContentW +"px";
jQuery("#TB_ajaxContent")[0].style.height = ajaxContentH +"px";
jQuery("#TB_ajaxContent")[0].scrollTop = 0;
jQuery("#TB_ajaxWindowTitle").html(caption);
}
}
jQuery("#TB_closeWindowButton").click(tb_remove);
if(url.indexOf('TB_inline') != -1){
jQuery("#TB_ajaxContent").append(jQuery('#' + params['inlineId']).children());
jQuery("#TB_window").bind('tb_unload', function () {
jQuery('#' + params['inlineId']).append( jQuery("#TB_ajaxContent").children() ); // move elements back when you're finished
});
tb_position();
jQuery("#TB_load").remove();
jQuery("#TB_window").css({'visibility':'visible'});
}else if(url.indexOf('TB_iframe') != -1){
tb_position();
jQuery("#TB_load").remove();
jQuery("#TB_window").css({'visibility':'visible'});
}else{
var load_url = url;
load_url += -1 === url.indexOf('?') ? '?' : '&';
jQuery("#TB_ajaxContent").load(load_url += "random=" + (new Date().getTime()),function(){//to do a post change this load method
tb_position();
jQuery("#TB_load").remove();
tb_init("#TB_ajaxContent a.thickbox");
jQuery("#TB_window").css({'visibility':'visible'});
});
}
}
if(!params['modal']){
jQuery(document).bind('keydown.thickbox', function(e){
if ( e.which == 27 ){ // close
tb_remove();
return false;
}
});
}
$closeBtn = jQuery( '#TB_closeWindowButton' );
/*
* If the native Close button icon is visible, move focus on the button
* (e.g. in the Network Admin Themes screen).
* In other admin screens is hidden and replaced by a different icon.
*/
if ( $closeBtn.find( '.tb-close-icon' ).is( ':visible' ) ) {
$closeBtn.focus();
}
} catch(e) {
//nothing here
}
}
//helper functions below
function tb_showIframe(){
jQuery("#TB_load").remove();
jQuery("#TB_window").css({'visibility':'visible'}).trigger( 'thickbox:iframe:loaded' );
}
function tb_remove() {
jQuery("#TB_imageOff").unbind("click");
jQuery("#TB_closeWindowButton").unbind("click");
jQuery( '#TB_window' ).fadeOut( 'fast', function() {
jQuery( '#TB_window, #TB_overlay, #TB_HideSelect' ).trigger( 'tb_unload' ).unbind().remove();
jQuery( 'body' ).trigger( 'thickbox:removed' );
});
jQuery( 'body' ).removeClass( 'modal-open' );
jQuery("#TB_load").remove();
if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
jQuery("body","html").css({height: "auto", width: "auto"});
jQuery("html").css("overflow","");
}
jQuery(document).unbind('.thickbox');
return false;
}
function tb_position() {
var isIE6 = typeof document.body.style.maxHeight === "undefined";
jQuery("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});
if ( ! isIE6 ) { // take away IE6
jQuery("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
}
}
function tb_parseQuery ( query ) {
var Params = {};
if ( ! query ) {return Params;}// return empty object
var Pairs = query.split(/[;&]/);
for ( var i = 0; i < Pairs.length; i++ ) {
var KeyVal = Pairs[i].split('=');
if ( ! KeyVal || KeyVal.length != 2 ) {continue;}
var key = unescape( KeyVal[0] );
var val = unescape( KeyVal[1] );
val = val.replace(/\+/g, ' ');
Params[key] = val;
}
return Params;
}
function tb_getPageSize(){
var de = document.documentElement;
var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
arrayPageSize = [w,h];
return arrayPageSize;
}
function tb_detectMacXFF() {
var userAgent = navigator.userAgent.toLowerCase();
if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
return true;
}
}
;
/*! This file is auto-generated */
!function(e,t){if("function"==typeof define&&define.amd)define("hoverintent",["module"],t);else if("undefined"!=typeof exports)t(module);else{var n={exports:{}};t(n),e.hoverintent=n.exports}}(this,function(e){"use strict";var t=Object.assign||function(e){for(var t=1;t .ab-item").focus(),w(t,"hover"))}function h(e){var t;13===e.which&&(A(e.target,".ab-sub-wrapper")||(t=A(e.target,".menupop"))&&(e.preventDefault(),E(t,"hover")?w(t,"hover"):L(t,"hover")))}function v(e){var t;13===e.which&&(t=e.target.getAttribute("href"),-1 li').not('.adminbar-handle'),
size = Math.floor( ( $(window).height() - 100 ) / 30 ), // approx, based on current styling
topHandle, bottomHandle, interval, speed = 100;
if ( ! ul.length || li.length < size + 1 || ul.find('li:first').hasClass('.adminbar-handle') )
return;
function move( direction ) {
var hide, show, next,
visible = li.filter(':visible'),
first = visible.first(),
last = visible.last();
if ( 'up' == direction ) {
show = last.next().not('.adminbar-handle');
hide = first;
if ( topHandle.hasClass('scrollend') ) {
topHandle.removeClass('scrollend');
}
if ( show.next().hasClass('adminbar-handle') ) {
bottomHandle.addClass('scrollend');
}
if ( ! show.length ) {
window.clearInterval( interval );
return;
}
} else if ( 'down' == direction ) {
show = first.prev().not('.adminbar-handle');
hide = last;
if ( bottomHandle.hasClass('scrollend') ) {
bottomHandle.removeClass('scrollend');
}
if ( show.prev().hasClass('adminbar-handle') ) {
topHandle.addClass('scrollend');
}
if ( ! show.length ) {
window.clearInterval( interval );
return;
}
} else {
return;
}
if ( hide.length && show.length ) {
// Maybe add some sliding animation?
hide.hide()
show.show()
}
}
// hide the extra items
li.slice(size).hide();
topHandle = $('');
bottomHandle = topHandle.clone().addClass('handle-bottom');
ul.prepend( topHandle.addClass('handle-top scrollend') ).append( bottomHandle );
topHandle.on( 'mouseenter', function() {
interval = window.setInterval( function() { move('down'); }, speed );
}).on( 'click', function() {
move('down');
});
bottomHandle.on( 'mouseenter', function() {
interval = window.setInterval( function() { move('up'); }, speed );
}).on( 'click', function() {
move('up');
});
topHandle.add( bottomHandle ).on( 'mouseleave click', function() {
window.clearInterval( interval );
});
});
;
( function( $ ) {
var cookieValue = document.cookie.replace( /(?:(?:^|.*;\s*)eucookielaw\s*\=\s*([^;]*).*$)|^.*$/, '$1' ),
overlay = $( '#eu-cookie-law' ),
container = $( '.widget_eu_cookie_law_widget' ),
initialScrollPosition,
scrollFunction;
if ( overlay.hasClass( 'ads-active' ) ) {
var adsCookieValue = document.cookie.replace( /(?:(?:^|.*;\s*)personalized-ads-consent\s*\=\s*([^;]*).*$)|^.*$/, '$1' );
if ( '' !== cookieValue && '' !== adsCookieValue ) {
overlay.remove();
}
} else if ( '' !== cookieValue ) {
overlay.remove();
}
$( '.widget_eu_cookie_law_widget' ).appendTo( 'body' ).fadeIn();
overlay.find( 'form' ).on( 'submit', accept );
if ( overlay.hasClass( 'hide-on-scroll' ) ) {
initialScrollPosition = $( window ).scrollTop();
scrollFunction = function() {
if ( Math.abs( $( window ).scrollTop() - initialScrollPosition ) > 50 ) {
accept();
}
};
$( window ).on( 'scroll', scrollFunction );
} else if ( overlay.hasClass( 'hide-on-time' ) ) {
setTimeout( accept, overlay.data( 'hide-timeout' ) * 1000 );
}
var accepted = false;
function accept( event ) {
if ( accepted ) {
return;
}
accepted = true;
if ( event && event.preventDefault ) {
event.preventDefault();
}
if ( overlay.hasClass( 'hide-on-scroll' ) ) {
$( window ).off( 'scroll', scrollFunction );
}
var expireTime = new Date();
expireTime.setTime( expireTime.getTime() + ( overlay.data( 'consent-expiration' ) * 24 * 60 * 60 * 1000 ) );
document.cookie = 'eucookielaw=' + expireTime.getTime() + ';path=/;expires=' + expireTime.toGMTString();
if ( overlay.hasClass( 'ads-active' ) && overlay.hasClass( 'hide-on-button' ) ) {
document.cookie = 'personalized-ads-consent=' + expireTime.getTime() + ';path=/;expires=' + expireTime.toGMTString();
}
overlay.fadeOut( 400, function() {
overlay.remove();
container.remove();
} );
}
} )( jQuery );
;
/*! This file is auto-generated */
(function(){function r(){}var n=this,t=n._,e=Array.prototype,o=Object.prototype,u=Function.prototype,i=e.push,c=e.slice,s=o.toString,a=o.hasOwnProperty,f=Array.isArray,l=Object.keys,p=u.bind,h=Object.create,v=function(n){return n instanceof v?n:this instanceof v?void(this._wrapped=n):new v(n)};"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=v),exports._=v):n._=v,v.VERSION="1.8.3";var y=function(u,i,n){if(void 0===i)return u;switch(null==n?3:n){case 1:return function(n){return u.call(i,n)};case 2:return function(n,t){return u.call(i,n,t)};case 3:return function(n,t,r){return u.call(i,n,t,r)};case 4:return function(n,t,r,e){return u.call(i,n,t,r,e)}}return function(){return u.apply(i,arguments)}},d=function(n,t,r){return null==n?v.identity:v.isFunction(n)?y(n,t,r):v.isObject(n)?v.matcher(n):v.property(n)};v.iteratee=function(n,t){return d(n,t,1/0)};function g(c,f){return function(n){var t=arguments.length;if(t<2||null==n)return n;for(var r=1;r":">",'"':""","'":"'","`":"`"},R=v.invert(T);v.escape=B(T),v.unescape=B(R),v.result=function(n,t,r){var e=null==n?void 0:n[t];return void 0===e&&(e=r),v.isFunction(e)?e.call(n):e};var q=0;v.uniqueId=function(n){var t=++q+"";return n?n+t:t},v.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};function K(n){return"\\"+D[n]}var z=/(.)^/,D={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028","\u2029":"u2029"},L=/\\|'|\r|\n|\u2028|\u2029/g;v.template=function(i,n,t){!n&&t&&(n=t),n=v.defaults({},n,v.templateSettings);var r=RegExp([(n.escape||z).source,(n.interpolate||z).source,(n.evaluate||z).source].join("|")+"|$","g"),o=0,a="__p+='";i.replace(r,function(n,t,r,e,u){return a+=i.slice(o,u).replace(L,K),o=u+n.length,t?a+="'+\n((__t=("+t+"))==null?'':_.escape(__t))+\n'":r?a+="'+\n((__t=("+r+"))==null?'':__t)+\n'":e&&(a+="';\n"+e+"\n__p+='"),n}),a+="';\n",n.variable||(a="with(obj||{}){\n"+a+"}\n"),a="var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};\n"+a+"return __p;\n";try{var e=new Function(n.variable||"obj","_",a)}catch(n){throw n.source=a,n}function u(n){return e.call(this,n,v)}var c=n.variable||"obj";return u.source="function("+c+"){\n"+a+"}",u},v.chain=function(n){var t=v(n);return t._chain=!0,t};function P(n,t){return n._chain?v(t).chain():t}v.mixin=function(r){v.each(v.functions(r),function(n){var t=v[n]=r[n];v.prototype[n]=function(){var n=[this._wrapped];return i.apply(n,arguments),P(this,t.apply(v,n))}})},v.mixin(v),v.each(["pop","push","reverse","shift","sort","splice","unshift"],function(t){var r=e[t];v.prototype[t]=function(){var n=this._wrapped;return r.apply(n,arguments),"shift"!==t&&"splice"!==t||0!==n.length||delete n[0],P(this,n)}}),v.each(["concat","join","slice"],function(n){var t=e[n];v.prototype[n]=function(){return P(this,t.apply(this._wrapped,arguments))}}),v.prototype.value=function(){return this._wrapped},v.prototype.valueOf=v.prototype.toJSON=v.prototype.value,v.prototype.toString=function(){return""+this._wrapped},"function"==typeof define&&define.amd&&define("underscore",[],function(){return v})}).call(this);;
/*! This file is auto-generated */
!function(n){var s="object"==typeof self&&self.self===self&&self||"object"==typeof global&&global.global===global&&global;if("function"==typeof define&&define.amd)define(["underscore","jquery","exports"],function(t,e,i){s.Backbone=n(s,i,t,e)});else if("undefined"!=typeof exports){var t,e=require("underscore");try{t=require("jquery")}catch(t){}n(s,exports,e,t)}else s.Backbone=n(s,{},s._,s.jQuery||s.Zepto||s.ender||s.$)}(function(t,h,x,e){var i=t.Backbone,o=Array.prototype.slice;h.VERSION="1.4.0",h.$=e,h.noConflict=function(){return t.Backbone=i,this},h.emulateHTTP=!1,h.emulateJSON=!1;var a,n=h.Events={},u=/\s+/,l=function(t,e,i,n,s){var r,o=0;if(i&&"object"==typeof i){void 0!==n&&"context"in s&&void 0===s.context&&(s.context=n);for(r=x.keys(i);othis.length&&(n=this.length),n<0&&(n+=this.length+1);var s,r,o=[],a=[],h=[],u=[],l={},c=e.add,d=e.merge,f=e.remove,p=!1,g=this.comparator&&null==n&&!1!==e.sort,v=x.isString(this.comparator)?this.comparator:null;for(r=0;r": ">",
'"': '"',
"'": '''
};
function escapeHTML(string) {
return String(string).replace(/&(?!\w+;)|[<>"']/g, function (s) {
return escapeMap[s] || s;
});
}
/**
* Adds the `template`, `line`, and `file` properties to the given error
* object and alters the message to provide more useful debugging information.
*/
function debug(e, template, line, file) {
file = file || "";
var lines = template.split("\n"),
start = Math.max(line - 3, 0),
end = Math.min(lines.length, line + 3),
context = lines.slice(start, end);
var c;
for (var i = 0, len = context.length; i < len; ++i) {
c = i + start + 1;
context[i] = (c === line ? " >> " : " ") + context[i];
}
e.template = template;
e.line = line;
e.file = file;
e.message = [file + ":" + line, context.join("\n"), "", e.message].join("\n");
return e;
}
/**
* Looks up the value of the given `name` in the given context `stack`.
*/
function lookup(name, stack, defaultValue) {
if (name === ".") {
return stack[stack.length - 1];
}
var names = name.split(".");
var lastIndex = names.length - 1;
var target = names[lastIndex];
var value, context, i = stack.length, j, localStack;
while (i) {
localStack = stack.slice(0);
context = stack[--i];
j = 0;
while (j < lastIndex) {
context = context[names[j++]];
if (context == null) {
break;
}
localStack.push(context);
}
if (context && typeof context === "object" && target in context) {
value = context[target];
break;
}
}
// If the value is a function, call it in the current context.
if (typeof value === "function") {
value = value.call(localStack[localStack.length - 1]);
}
if (value == null) {
return defaultValue;
}
return value;
}
function renderSection(name, stack, callback, inverted) {
var buffer = "";
var value = lookup(name, stack);
if (inverted) {
// From the spec: inverted sections may render text once based on the
// inverse value of the key. That is, they will be rendered if the key
// doesn't exist, is false, or is an empty list.
if (value == null || value === false || (isArray(value) && value.length === 0)) {
buffer += callback();
}
} else if (isArray(value)) {
forEach(value, function (value) {
stack.push(value);
buffer += callback();
stack.pop();
});
} else if (typeof value === "object") {
stack.push(value);
buffer += callback();
stack.pop();
} else if (typeof value === "function") {
var scope = stack[stack.length - 1];
var scopedRender = function (template) {
return render(template, scope);
};
buffer += value.call(scope, callback(), scopedRender) || "";
} else if (value) {
buffer += callback();
}
return buffer;
}
/**
* Parses the given `template` and returns the source of a function that,
* with the proper arguments, will render the template. Recognized options
* include the following:
*
* - file The name of the file the template comes from (displayed in
* error messages)
* - tags An array of open and close tags the `template` uses. Defaults
* to the value of Mustache.tags
* - debug Set `true` to log the body of the generated function to the
* console
* - space Set `true` to preserve whitespace from lines that otherwise
* contain only a {{tag}}. Defaults to `false`
*/
function parse(template, options) {
options = options || {};
var tags = options.tags || exports.tags,
openTag = tags[0],
closeTag = tags[tags.length - 1];
var code = [
'var buffer = "";', // output buffer
"\nvar line = 1;", // keep track of source line number
"\ntry {",
'\nbuffer += "'
];
var spaces = [], // indices of whitespace in code on the current line
hasTag = false, // is there a {{tag}} on the current line?
nonSpace = false; // is there a non-space char on the current line?
// Strips all space characters from the code array for the current line
// if there was a {{tag}} on it and otherwise only spaces.
var stripSpace = function () {
if (hasTag && !nonSpace && !options.space) {
while (spaces.length) {
code.splice(spaces.pop(), 1);
}
} else {
spaces = [];
}
hasTag = false;
nonSpace = false;
};
var sectionStack = [], updateLine, nextOpenTag, nextCloseTag;
var setTags = function (source) {
tags = trim(source).split(/\s+/);
nextOpenTag = tags[0];
nextCloseTag = tags[tags.length - 1];
};
var includePartial = function (source) {
code.push(
'";',
updateLine,
'\nvar partial = partials["' + trim(source) + '"];',
'\nif (partial) {',
'\n buffer += render(partial,stack[stack.length - 1],partials);',
'\n}',
'\nbuffer += "'
);
};
var openSection = function (source, inverted) {
var name = trim(source);
if (name === "") {
throw debug(new Error("Section name may not be empty"), template, line, options.file);
}
sectionStack.push({name: name, inverted: inverted});
code.push(
'";',
updateLine,
'\nvar name = "' + name + '";',
'\nvar callback = (function () {',
'\n return function () {',
'\n var buffer = "";',
'\nbuffer += "'
);
};
var openInvertedSection = function (source) {
openSection(source, true);
};
var closeSection = function (source) {
var name = trim(source);
var openName = sectionStack.length != 0 && sectionStack[sectionStack.length - 1].name;
if (!openName || name != openName) {
throw debug(new Error('Section named "' + name + '" was never opened'), template, line, options.file);
}
var section = sectionStack.pop();
code.push(
'";',
'\n return buffer;',
'\n };',
'\n})();'
);
if (section.inverted) {
code.push("\nbuffer += renderSection(name,stack,callback,true);");
} else {
code.push("\nbuffer += renderSection(name,stack,callback);");
}
code.push('\nbuffer += "');
};
var sendPlain = function (source) {
code.push(
'";',
updateLine,
'\nbuffer += lookup("' + trim(source) + '",stack,"");',
'\nbuffer += "'
);
};
var sendEscaped = function (source) {
code.push(
'";',
updateLine,
'\nbuffer += escapeHTML(lookup("' + trim(source) + '",stack,""));',
'\nbuffer += "'
);
};
var line = 1, c, callback;
for (var i = 0, len = template.length; i < len; ++i) {
if (template.slice(i, i + openTag.length) === openTag) {
i += openTag.length;
c = template.substr(i, 1);
updateLine = '\nline = ' + line + ';';
nextOpenTag = openTag;
nextCloseTag = closeTag;
hasTag = true;
switch (c) {
case "!": // comment
i++;
callback = null;
break;
case "=": // change open/close tags, e.g. {{=<% %>=}}
i++;
closeTag = "=" + closeTag;
callback = setTags;
break;
case ">": // include partial
i++;
callback = includePartial;
break;
case "#": // start section
i++;
callback = openSection;
break;
case "^": // start inverted section
i++;
callback = openInvertedSection;
break;
case "/": // end section
i++;
callback = closeSection;
break;
case "{": // plain variable
closeTag = "}" + closeTag;
// fall through
case "&": // plain variable
i++;
nonSpace = true;
callback = sendPlain;
break;
default: // escaped variable
nonSpace = true;
callback = sendEscaped;
}
var end = template.indexOf(closeTag, i);
if (end === -1) {
throw debug(new Error('Tag "' + openTag + '" was not closed properly'), template, line, options.file);
}
var source = template.substring(i, end);
if (callback) {
callback(source);
}
// Maintain line count for \n in source.
var n = 0;
while (~(n = source.indexOf("\n", n))) {
line++;
n++;
}
i = end + closeTag.length - 1;
openTag = nextOpenTag;
closeTag = nextCloseTag;
} else {
c = template.substr(i, 1);
switch (c) {
case '"':
case "\\":
nonSpace = true;
code.push("\\" + c);
break;
case "\r":
// Ignore carriage returns.
break;
case "\n":
spaces.push(code.length);
code.push("\\n");
stripSpace(); // Check for whitespace on the current line.
line++;
break;
default:
if (isWhitespace(c)) {
spaces.push(code.length);
} else {
nonSpace = true;
}
code.push(c);
}
}
}
if (sectionStack.length != 0) {
throw debug(new Error('Section "' + sectionStack[sectionStack.length - 1].name + '" was not closed properly'), template, line, options.file);
}
// Clean up any whitespace from a closing {{tag}} that was at the end
// of the template without a trailing \n.
stripSpace();
code.push(
'";',
"\nreturn buffer;",
"\n} catch (e) { throw {error: e, line: line}; }"
);
// Ignore `buffer += "";` statements.
var body = code.join("").replace(/buffer \+= "";\n/g, "");
if (options.debug) {
if (typeof console != "undefined" && console.log) {
console.log(body);
} else if (typeof print === "function") {
print(body);
}
}
return body;
}
/**
* Used by `compile` to generate a reusable function for the given `template`.
*/
function _compile(template, options) {
var args = "view,partials,stack,lookup,escapeHTML,renderSection,render";
var body = parse(template, options);
var fn = new Function(args, body);
// This anonymous function wraps the generated function so we can do
// argument coercion, setup some variables, and handle any errors
// encountered while executing it.
return function (view, partials) {
partials = partials || {};
var stack = [view]; // context stack
try {
return fn(view, partials, stack, lookup, escapeHTML, renderSection, render);
} catch (e) {
throw debug(e.error, template, e.line, options.file);
}
};
}
// Cache of pre-compiled templates.
var _cache = {};
/**
* Clear the cache of compiled templates.
*/
function clearCache() {
_cache = {};
}
/**
* Compiles the given `template` into a reusable function using the given
* `options`. In addition to the options accepted by Mustache.parse,
* recognized options include the following:
*
* - cache Set `false` to bypass any pre-compiled version of the given
* template. Otherwise, a given `template` string will be cached
* the first time it is parsed
*/
function compile(template, options) {
options = options || {};
// Use a pre-compiled version from the cache if we have one.
if (options.cache !== false) {
if (!_cache[template]) {
_cache[template] = _compile(template, options);
}
return _cache[template];
}
return _compile(template, options);
}
/**
* High-level function that renders the given `template` using the given
* `view` and `partials`. If you need to use any of the template options (see
* `compile` above), you must compile in a separate step, and then call that
* compiled function.
*/
function render(template, view, partials) {
return compile(template)(view, partials);
}
})(Mustache);
;
/* Common front-end code for the Notifications system
* - wpNotesCommon wraps all the proxied REST calls
* - wpNoteModel & wpNoteList are Backbone.js Model, & Collection implementations
*/
var wpNotesCommon;
var wpNotesCommentModView;
var wpNoteList;
var wpNoteModel;
(function($){
var cookies = document.cookie.split( /;\s*/ ), cookie = false;
for ( i = 0; i < cookies.length; i++ ) {
if ( cookies[i].match( /^wp_api=/ ) ) {
cookies = cookies[i].split( '=' );
cookie = cookies[1];
break;
}
}
wpNotesCommon = {
jsonAPIbase: 'https://public-api.wordpress.com/rest/v1',
hasUpgradedProxy: false,
noteTypes: {
comment: 'comment',
follow: 'follow',
like: [
'like',
'like_trap'
],
reblog: 'reblog',
trophy: [
'best_liked_day_feat',
'like_milestone_achievement',
'achieve_automattician_note',
'achieve_user_anniversary',
'best_followed_day_feat',
'followed_milestone_achievement'
],
'alert': [
'expired_domain_alert'
]
},
noteType2Noticon: {
'like': 'like',
'follow': 'follow',
'comment_like': 'like',
'comment': 'comment',
'comment_pingback': 'external',
'reblog': 'reblog',
'like_milestone_achievement': 'trophy',
'achieve_followed_milestone_note': 'trophy',
'achieve_user_anniversary': 'trophy',
'best_liked_day_feat': 'milestone',
'best_followed_day_feat': 'milestone',
'automattician_achievement': 'trophy',
'expired_domain_alert': 'alert',
'automattcher': 'atsign'
},
createNoteContainer: function( note, id_prefix ) {
var note_container = $('
', {
id : id_prefix + '-note-' + note.id,
'class' : 'wpn-note wpn-' + note.type + ' ' + ( ( note.unread > 0 ) ? 'wpn-unread' : 'wpn-read' )
}).data( {
id: parseInt( note.id, 10 ),
type: note.type
});
var note_body = $('
', { "class":"wpn-note-body wpn-note-body-empty" } );
var spinner = $( '
', { style : 'position: absolute; left: 180px; top: 60px;' } );
note_body.append( spinner );
spinner.spin( 'medium' );
note_container.append(
this.createNoteSubject( note ),
note_body
);
return note_container;
},
createNoteSubject: function( note ) {
var subj = $('
', { "class":"wpn-note-summary" } ).append(
$(' ', {
"class" : 'wpn-noticon noticon noticon' + note.noticon
}),
$(' ', {
"class" : 'wpn-icon no-grav',
html : $(' ', {
src : note.subject.icon,
width : '24px',
height : '24px',
style : 'display: inline-block; width: 24px; height: 24px; overflow-x: hidden; overflow-y: hidden;'
})
}),
$(' ', {
"class" : 'wpn-subject',
html : note.subject.html
})
);
return subj;
},
createNoteBody: function( note_model ) {
var note_body = $('
', { "class":"wpn-note-body" } );
var note = note_model.toJSON();
var class_prefix = 'wpn-' + note.body.template;
switch( note.body.template ) {
case 'single-line-list' :
case 'multi-line-list' :
note_body.append(
$( '
' ).addClass( class_prefix + '-header' ).html( note.body.header )
);
for ( var i in note.body.items ) {
var item = $('
', {
'class' : class_prefix + '-item ' + class_prefix + '-item-' + i +
( note.body.items[i].icon ? '' : ' ' + class_prefix + '-item-no-icon' )
});
if ( note.body.items[i].icon ) {
item.append(
$(' ', {
"class" : class_prefix + '-item-icon avatar avatar-' + note.body.items[i].icon_width,
height: note.body.items[i].icon_height,
width: note.body.items[i].icon_width,
src: note.body.items[i].icon
} ) );
}
if ( note.body.items[i].header ) {
item.append(
$('
', { 'class' : class_prefix + '-item-header' }
).html( note.body.items[i].header ) );
}
if ( note.body.items[i].action ) {
switch ( note.body.items[i].action.type ) {
case 'follow' :
var button = wpFollowButton.create( note.body.items[i].action );
item.append( button );
// Attach action stat tracking for follows
button.click( function(e) {
if ( $( this ).children('a').hasClass( 'wpcom-follow-rest' ) )
wpNotesCommon.bumpStat( 'notes-click-action', 'unfollow' );
else
wpNotesCommon.bumpStat( 'notes-click-action', 'follow' );
return true;
} );
break;
default :
console.error( "Unsupported " + note.type + " action: " + note.body.items[i].action.type );
break;
}
}
if ( note.body.items[i].html ) {
item.append(
$('
', { 'class' : class_prefix + '-item-body' }
).html( note.body.items[i].html ) );
}
note_body.append( item );
}
if ( note.body.actions ) {
var note_actions = new wpNotesCommentModView( { model: note_model } );
note_actions.render();
note_body.append( note_actions.el );
}
if ( note.body.footer ) {
note_body.append(
$( '
' ).addClass( class_prefix + '-footer' ).html( note.body.footer )
);
}
break;
case 'big-badge' :
if ( note.body.header ) {
note_body.append(
$( '
' ).addClass( class_prefix + '-header' ).html( note.body.header )
);
}
if ( note.body.badge ) {
note_body.append( $('
', {
'class' : class_prefix + '-badge '
}).append( note.body.badge ) );
}
if ( note.body.html !== '' ) {
note_body.append(
$( '
' ).addClass( class_prefix + '-footer' ).html( note.body.html )
);
}
break;
default :
note_body.text( 'Unsupported note body template!' );
break;
}
note_body.find( 'a[notes-data-click]' ).mousedown( function(e) {
var type = $(this).attr( 'notes-data-click' );
wpNotesCommon.bumpStat( 'notes-click-body', type );
return true;
} );
return note_body;
},
getNoteSubjects: function( query_params, success, fail ) {
query_params.fields = 'id,type,unread,noticon,timestamp,subject';
query_params.trap = true;
return this.getNotes( query_params, success, fail );
},
getNotes: function( query_params, success, fail ) {
return this.ajax({
type: 'GET',
path: '/notifications/',
data: query_params,
success: success,
error: fail
});
},
getMentions: function( query_params, success ) {
return this.ajax({
type: 'GET',
path: '/users/suggest',
data: query_params,
success: success
});
},
markNotesSeen: function( timestamp ) {
return this.ajax({
type: 'POST',
path: '/notifications/seen',
data: { time: timestamp }
});
},
markNotesRead: function( unread_cnts ) {
var query_args = {};
var t = this;
for ( var id in unread_cnts ) {
if ( unread_cnts[ id ] > 0 ) {
query_args['counts[' + id + ']'] = unread_cnts[ id ];
}
}
if ( 0 === query_args.length ) {
return (new $.Deferred()).resolve( 'no unread notes' );
}
return this.ajax({
type : 'POST',
path : '/notifications/read',
data : query_args,
success : function( res ) { },
error : function( res ) { }
});
},
ajax: function( options ) {
var t = this;
var request = {
path: options.path,
method: options.type
};
if ( options.type.toLowerCase() == 'post' )
request.body = options.data;
else
request.query = options.data;
return $.Deferred( function( dfd ) {
var makeProxyCall = function() {
$.wpcom_proxy_request( request, function( response, statusCode ) {
if ( 200 == statusCode ) {
if ( 'function' == typeof options.success ) {
options.success( response );
}
return dfd.resolve( response );
}
if ( 'function' == typeof options.error ) {
options.error( statusCode );
}
else {
console.error( statusCode );
}
return dfd.reject( statusCode );
});
};
if ( t.hasUpgradedProxy ) {
return makeProxyCall();
}
return $.wpcom_proxy_request( { metaAPI: { accessAllUsersBlogs: true } } ).done( function() {
t.hasUpgradedProxy = true;
makeProxyCall();
} );
});
},
bumpStat: function( group, names ) {
if ( 'undefined' != typeof wpNotesIsJetpackClient && wpNotesIsJetpackClient ) {
var jpStats = [ 'notes-menu-impressions', 'notes-menu-clicks' ];
if ( _.contains( jpStats, group ) ) {
names = names.replace( /(,|$)/g, '-jetpack$1' );
}
}
new Image().src = document.location.protocol + '//pixel.wp.com/g.gif?v=wpcom-no-pv&x_' + group + '=' + names + '&baba=' + Math.random();
},
getKeycode: function( key_event ) {
//determine if we can use this key event to trigger the menu
key_event = key_event || window.event;
if ( key_event.target )
element = key_event.target;
else if ( key_event.srcElement )
element = key_event.srcElement;
if( element.nodeType == 3 ) //text node, check the parent
element = element.parentNode;
if( key_event.ctrlKey === true || key_event.altKey === true || key_event.metaKey === true )
return false;
var keyCode = ( key_event.keyCode ) ? key_event.keyCode : key_event.which;
if ( keyCode && ( element.tagName == 'INPUT' || element.tagName == 'TEXTAREA' || element.tagName == 'SELECT' ) )
return false;
if ( keyCode && element.contentEditable == "true" )
return false;
return keyCode;
}
};
wpNoteModel = Backbone.Model.extend({
defaults: {
summary: "",
unread: true
},
_reloadBlocked: false,
initialize: function() {
},
markRead: function() {
var unread_cnt = this.get( 'unread' );
if ( Boolean( parseInt( unread_cnt, 10 ) ) ) {
var notes = {};
notes[ this.id ] = unread_cnt;
wpNotesCommon.markNotesRead( notes );
wpNotesCommon.bumpStat( 'notes-read-type', this.get( 'type' ) );
}
},
loadBody: function() {
wpNotesCommon.createNoteBody( this );
},
reload: function() {
var t = this;
var fields = 'id,type,unread,noticon,subject,body,date,timestamp,status';
if ( 'comment' == t.get( 'type' ) ) {
fields += ',approval_status,has_replied';
}
if (!force && this.isReloadingBlocked()) {
return $.Deferred().reject('reloading blocked');
}
return wpNotesCommon.getNotes( {
fields: fields,
trap: true,
ids: [ t.get('id') ]
}, function ( res ) {
var notes = res.notes;
if ( typeof notes[0] !== 'undefined' ) {
t.set( notes[ 0 ] );
}
}, function() {
//ignore failure
} );
},
resize: function() {
this.trigger( 'resize' );
},
/* Block the model from being reloaded for a specified number of seconds
* needed b/c in the case of Jetpack, it takes a while for the new status to sync back to wpcom
* & this prevents it flashing back and forth
*/
blockReloading: function(seconds) {
var _this = this;
this._reloadBlocked = true;
clearTimeout(this.reloadBlockerTimeout);
return this.reloadBlockerTimeout = setTimeout(function() {
return _this._reloadBlocked = false;
}, seconds * 1000);
},
isReloadingBlocked: function() {
return this._reloadBlocked;
}
});
wpNoteList = Backbone.Collection.extend({
model: wpNoteModel,
lastMarkedSeenTimestamp : false,
newNotes: false,
maxNotes : false,
loading: false,
hasLoaded: false,
allBodiesLoaded: false,
//always sort by timpstamp
comparator: function( note ) {
return -note.get( 'timestamp' );
},
addNotes: function( notes ) {
// Filter out any notes that have no subject
notes = _.filter( notes, function(note) { return typeof( note.subject ) === "object"; } );
var models = _.map( notes, function(o) { return new wpNoteModel(o); });
this.add( models );
this.sort(); //ensure we maintain sorted order
if ( this.maxNotes ) {
while( this.length > this.maxNotes ) {
this.pop();
}
}
this.trigger( 'loadNotes:change' );
},
getMostRecentTimestamp: function() {
if ( !this.length ) {
return false;
}
//ensure we maintain sorted order see the comparator function
this.sort();
return parseInt( this.at(0).get( 'timestamp' ), 10 );
},
// load notes from the server
loadNotes: function( query_args ) {
var t = this;
t.loading = true;
t.trigger( 'loadNotes:beginLoading' );
var fields = query_args.fields;
var number = parseInt( query_args.number, 10 );
var before = parseInt( query_args.before, 10 );
var since = parseInt( query_args.since, 10 );
var timeout = parseInt( query_args.timeout, 10 ) || 7000;
var type = 'undefined' == typeof query_args.type ? null : query_args.type;
var unread = 'undefined' == typeof query_args.unread ? null : query_args.unread;
query_args = {
timeout: timeout
};
if ( ! fields ) {
fields = 'id,type,unread,noticon,subject,body,date,timestamp,status';
}
if ( isNaN( number ) ) {
number = 9;
}
if ( ! isNaN( before ) ) {
query_args.before = before;
}
if ( ! isNaN( since ) ) {
query_args.since = since;
}
if ( unread !== null ) {
query_args.unread = unread;
}
if ( type !== null && type != "unread" && type != "latest" ) {
query_args.type = type;
}
query_args.number = number;
query_args.fields = fields;
query_args.trap = true;
return wpNotesCommon.getNotes( query_args ).done( function ( res ) {
var qt;
var notes = res.notes;
var notes_changed = false;
if ( !t.lastMarkedSeenTimestamp || ( res.last_seen_time > t.lastMarkedSeenTimestamp ) ) {
notes_changed = true;
t.lastMarkedSeenTimestamp = parseInt( res.last_seen_time, 10 );
}
for( var idx in notes ) {
var note_model = t.get( notes[idx].id );
if ( note_model ) {
// Remove notes that have no subject
if ( typeof( notes[idx].subject ) != 'object' ) {
t.remove( notes[idx].id );
notes_changed = true;
continue;
}
if ( type ) {
qt = note_model.get( 'queried_types' ) || {};
qt[ type ] = true;
notes[idx].queried_types = qt;
}
note_model.set( notes[ idx ] );
}
else {
// Skip notes that have no subject
if ( typeof( notes[idx].subject ) != 'object' ) {
continue;
}
if ( type ) {
qt = {};
qt[ type ] = true;
notes[idx].queried_types = qt;
}
note_model = new wpNoteModel( notes[ idx ] );
t.add( note_model );
}
if ( ! note_model.has('body') )
t.allBodiesLoaded = false;
notes_changed = true;
}
if ( t.maxNotes ) {
while( t.length > t.maxNotes ) {
t.pop();
}
}
if ( notes_changed ) {
t.sort(); //ensure we maintain sorted order
t.trigger( 'loadNotes:change' );
}
t.loading = false;
t.hasLoaded = true;
t.trigger( 'loadNotes:endLoading' );
}).fail( function( e ) {
t.loading = false;
t.trigger( 'loadNotes:failed' );
});
},
loadNoteBodies: function( filter ) {
var t = this;
if ( t.allBodiesLoaded ) {
return (new $.Deferred()).resolve();
}
// Only load the note bodies that pass the caller supplied filter.
// If no filter is supplied, all notes in the collection are fetched.
var ids = t.getNoteIds( filter );
if ( 0 == ids.length ) {
return (new $.Deferred()).reject();
}
var doneFunc = function( res ) {
var notes = res.notes;
for( var idx in notes ) {
// Skip notes that have no subject
if ( typeof( notes[idx].subject ) != 'object' ) {
continue;
}
var note_model = t.get( notes[idx].id );
if ( note_model ) {
note_model.set( notes[idx] );
} else {
note_model = new wpNoteModel( notes[ idx ] );
t.add( note_model );
}
}
};
var failFunc = function ( e ) {
if ( typeof console != 'undefined' && typeof console.error == 'function' )
console.error( 'body loading error!' );
}
//get each note body as a separate request so we can get them in parallel
//to speed up loading when there are many new notes
var deferreds = [];
//split into 3 requests (3 most recent notes, and then any others into one request)
var count = 3
for ( var i=0; i count ) {
var query_params = {};
// loads subject & meta data also so all are consistent
query_params.fields = 'id,type,unread,noticon,timestamp,subject,body,meta,status';
query_params.trap = true;
for ( var i=count; i this.lastMarkedSeenTimestamp ) {
wpNotesCommon.markNotesSeen( mostRecentTs ).done( function() {
t.lastMarkedSeenTimestamp = false;
});
}
},
unreadCount: function() {
return this.reduce( function( num, note ) { return num + ( note.get('unread') ? 1 : 0 ); }, 0 );
},
numberNewNotes: function() {
var t = this;
if ( ! t.lastMarkedSeenTimestamp )
return 0;
return t.getNewNotes().length;
},
// return notes in this collection which were generated after we last marked it as seen.
getNewNotes: function() {
var t = this;
return t.filter( function( note ) {
return ( note.get('timestamp') > t.lastMarkedSeenTimestamp );
} );
},
// get all unread notes in the collection
getUnreadNotes: function() {
return this.filter( function( note ){ return Boolean( parseInt( note.get( "unread" ), 10 ) ); } );
},
// get all notes in the collection of specified type
getNotesOfType: function( typeName ) {
var t = this;
switch( typeName ){
case 'unread':
return t.getUnreadNotes();
case 'latest':
return t.filter( function( note ) {
var qt = note.get( 'queried_types' );
return 'undefined' != typeof qt && 'undefined' != typeof qt.latest && qt.latest;
});
default:
return t.filter( function( note ) {
var note_type = note.get( "type" );
if ( "undefined" == typeof wpNotesCommon.noteTypes[ typeName ] ) {
return false;
}
else if ( "string" == typeof wpNotesCommon.noteTypes[ typeName ] ) {
return typeName == note_type;
}
var len = wpNotesCommon.noteTypes[ typeName ].length;
for ( var i=0; i\
{{reply.text}} \
\
{{/reply}}\
{{#like}}\
\
{{like.text}} \
\
{{/like}}\
\
More \
\
\
{{#approve}}\
\
{{approve.text}} \
\
{{/approve}}\
',
templateReply: '\
',
initialize: function() {
var _this = this;
this.setElement($(''));
this.listenTo(this.model, 'change:status', function(model, status) {
var approvalStatus, prevStatus;
approvalStatus = status.approval_status;
prevStatus = model.previous('status') || {};
if (prevStatus.approval_status && prevStatus.approval_status === approvalStatus) {
return;
}
if (approvalStatus.match(/^trash|spam$/)) {
return _this.setUndoStatus(prevStatus.approval_status);
}
});
this.listenTo(this.model, 'change', this.render);
$(document).on('click', '.wpn-more > a', function(ev) {
var $el;
ev.preventDefault();
ev.stopPropagation();
if (ev.doneMoreToggle) {
return;
}
ev.doneMoreToggle = true;
$el = $(ev.currentTarget);
$el.parent().find('.wpn-more-container').toggle();
return false;
});
this;
$(document).on('click', '.wpn-note-body', function(ev) {
var $el, $note;
$el = $(ev.target);
if (($el.parents('.wpn-more').length)) {
return;
}
$note = $el.closest('.wpn-note-body');
if ($note.find('.wpn-more-container').is(':visible')) {
$note.find('.wpn-more-container').toggle();
}
});
this;
$('.wpn-more-container:not(:has(*))').parents('.wpn-more').hide();
$(document).on('keydown', function(keyEvent) {
var keyCode, status, validActions;
if (_this.$el.is(':hidden')) {
return;
}
if (_this.mode !== 'buttons') {
return;
}
keyCode = wpNotesCommon.getKeycode(keyEvent);
if (!keyCode) {
return;
}
validActions = _this.getValidActions();
status = _this.model.get('status') || {};
if (keyCode === 82) {
if (_.contains(validActions, 'replyto-comment')) {
_this.openReply(keyEvent);
}
}
if (keyCode === 65) {
if (_.contains(validActions, 'approve-comment')) {
_this.modComment('approve-comment');
} else if (_.contains(validActions, 'unapprove-comment')) {
_this.modComment('unapprove-comment');
}
}
if (keyCode === 76) {
if (_.contains(validActions, 'like-comment')) {
_this.likeComment('like-comment');
} else if (_.contains(validActions, 'unlike-comment')) {
_this.likeComment('unlike-comment');
}
}
if (keyCode === 83) {
if (_.contains(validActions, 'spam-comment')) {
_this.modComment('spam-comment');
} else if (_.contains(validActions, 'unspam-comment')) {
_this.modComment('unspam-comment');
}
}
if (keyCode === 84) {
if (_.contains(validActions, 'trash-comment')) {
_this.modComment('trash-comment');
} else if (_.contains(validActions, 'untrash-comment')) {
_this.modComment('untrash-comment');
}
}
return false;
});
return this;
},
render: function() {
var body;
if (this.model._changing && 'reply' === this.mode) {
return this;
}
this.$el.empty();
body = this.model.get('body');
if (!body.actions) {
return this;
}
this.updateActionsMap();
if (this.mode === 'buttons') {
this.$el.html(this.createActionsHTML());
} else {
this.$el.html(this.createReplyBoxHTML());
this.$('textarea').focus();
}
this.delegateEvents();
return this;
},
setUndoStatus: function(status) {
return this._undoStatus = status;
},
getUndoStatus: function() {
var status;
if (this._undoStatus) {
return this._undoStatus;
}
status = this.model.get('status');
if ((status != null) && status.undo_status === '1') {
return 'approved';
}
return 'unapproved';
},
getValidActions: function() {
var actions, status;
status = this.model.get('status') || {};
switch (status.approval_status) {
case 'pending':
case 'unapproved':
return ['replyto-comment', 'approve-comment', 'spam-comment', 'trash-comment'];
case 'approved':
actions = ['replyto-comment', 'unapprove-comment', 'spam-comment', 'trash-comment'];
if (status.i_liked) {
actions.splice(1, 0, 'unlike-comment');
} else {
actions.splice(1, 0, 'like-comment');
}
return actions;
case 'trash':
return ['untrash-comment'];
case 'spam':
return ['unspam-comment'];
default:
return [];
}
},
getResultantStatus: function(actionType) {
switch (actionType) {
case 'approve-comment':
return 'approved';
case 'unapprove-comment':
return 'unapproved';
case 'spam-comment':
return 'spam';
case 'trash-comment':
return 'trash';
case 'unspam-comment':
case 'untrash-comment':
return this.getUndoStatus();
default:
return void 0;
}
},
getStatusParamFromActionType: function(actionType) {
if (!actionType) {
return void 0;
}
switch (actionType) {
case 'approve-comment':
return 'approved';
case 'unapprove-comment':
return 'unapproved';
default:
return actionType.split('-')[0];
}
},
getComplementaryActionType: function(actionType) {
switch (actionType) {
case 'approve-comment':
return 'unapprove-comment';
case 'unapprove-comment':
return 'approve-comment';
case 'like-comment':
return 'unlike-comment';
case 'unlike-comment':
return 'like-comment';
case 'spam-comment':
return 'unspam-comment';
case 'trash-comment':
return 'untrash-comment';
case 'unspam-comment':
return 'spam-comment';
case 'untrash-comment':
return 'trash-comment';
default:
return void 0;
}
},
getTranslation: function(string) {
if (typeof notes_i18n === 'undefined' || !notes_i18n.translate) {
return string;
}
return notes_i18n.translate(string).fetch();
},
getTranslationsForActionType: function(actionType) {
var gt;
gt = this.getTranslation;
if (!this._translationsByActionType) {
this._translationsByActionType = {
'approve-comment': {
buttonText: gt('Approve'),
titleText: gt('Approve this comment.')
},
'like-comment': {
buttonText: gt('Like'),
titleText: gt('Like this comment.')
},
'replyto-comment': {
buttonText: gt('Reply'),
titleText: gt('Reply to this comment.')
},
'spam-comment': {
buttonText: gt('Spam'),
titleText: gt('Mark this comment as spam.')
},
'trash-comment': {
buttonText: gt('Trash'),
titleText: gt('Move this comment to the trash.')
},
'unapprove-comment': {
buttonText: gt('Unapprove'),
titleText: gt('Unapprove this comment.')
},
'unlike-comment': {
buttonText: gt('Liked'),
titleText: gt('Unlike this comment.')
},
'unspam-comment': {
buttonText: gt('Unspam'),
titleText: gt('Unmark this comment as spam.')
},
'untrash-comment': {
buttonText: gt('Untrash'),
titleText: gt('Restore this comment from the trash.')
}
};
}
return this._translationsByActionType[actionType];
},
updateActionsMap: function() {
var action, actionType, actions, body, _fn, _i, _j, _len, _len1, _ref, _results,
_this = this;
body = this.model.get('body');
actions = body.actions || [];
this.actionsByName = this.actionsByName || {};
_fn = function(action) {
if (!action.type || !action.params) {
return;
}
return _this.actionsByName[action.type] = $.extend({}, action.params, {
actionType: action.type
});
};
for (_i = 0, _len = actions.length; _i < _len; _i++) {
action = actions[_i];
_fn(action);
}
_ref = this.possibleActions;
_results = [];
for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) {
actionType = _ref[_j];
_results.push((function(actionType) {
var actionObj, complementObj, status, statusParam, submitText, translations;
actionObj = _this.actionsByName[actionType];
statusParam = _this.getStatusParamFromActionType(actionType);
translations = _this.getTranslationsForActionType(actionType);
if (!actionObj) {
complementObj = _this.actionsByName[_this.getComplementaryActionType(actionType)];
if (complementObj) {
_this.actionsByName[actionType] = $.extend({}, complementObj, {
actionType: actionType,
ajax_arg: statusParam,
rest_body: {
status: statusParam
},
text: translations.buttonText,
title_text: translations.titleText
});
}
}
if (actionType === 'replyto-comment') {
status = _this.model.get('status' || {});
submitText = status.approval_status === 'approved' ? _this.getTranslation('Reply') : _this.getTranslation('Approve and Reply');
return $.extend(_this.actionsByName['replyto-comment'], {
button_text: translations.buttonText,
submit_button_text: submitText,
text: translations.buttonText,
title_text: translations.titleText
});
}
})(actionType));
}
return _results;
},
createActionsHTML: function() {
var actionType, status, templateData, _fn, _i, _len, _ref,
_this = this;
status = this.model.get('status').approval_status;
templateData = {};
_ref = this.getValidActions();
_fn = function(actionType) {
var action, button_data;
action = _this.actionsByName[actionType];
if (!action) {
return;
}
button_data = {
"class": 'wpn-' + actionType + '-button',
"actionType": actionType,
"text": action.text || action.button_text
};
switch (actionType) {
case 'replyto-comment':
return templateData.reply = $.extend({}, button_data, {
"class": 'wpn-replyto-comment-button-open',
"title": (action.title_text || action.button_title_text) + ' [r]'
});
case 'like-comment':
case 'unlike-comment':
return templateData.like = $.extend({}, button_data, {
"title": (action.title_text || action.button_title_text) + ' [l]'
});
case 'approve-comment':
case 'unapprove-comment':
if (_.contains(['spam', 'trash'], status)) {
break;
}
return templateData.approve = $.extend({}, button_data, {
"title": (action.title_text || action.button_title_text) + ' [a]'
});
case 'spam-comment':
case 'unspam-comment':
if (status === 'trash') {
break;
}
return templateData.spam = $.extend({}, button_data, {
"title": (action.title_text || action.button_title_text) + ' [s]'
});
case 'trash-comment':
case 'untrash-comment':
if (status === 'spam') {
break;
}
return templateData.trash = $.extend({}, button_data, {
"title": (action.title_text || action.button_title_text) + ' [t]'
});
}
};
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
actionType = _ref[_i];
_fn(actionType);
}
return Mustache.render(this.templateActions, templateData);
},
createReplyBoxHTML: function() {
var action, blog_id, comment_id;
action = this.actionsByName['replyto-comment'];
if (!action) {
return;
}
blog_id = action.site_id || 0;
comment_id = this.model.id || 0;
return Mustache.render(this.templateReply, {
reply_header_text: action.reply_header_text,
submit_button_text: action.submit_button_text
});
},
closeReply: function(ev) {
if (ev) {
ev.preventDefault();
}
this.mode = 'buttons';
this.model.currentReplyText = this.$el.children('.wpn-note-comment-reply').children('.wpn-note-comment-reply-text').val();
this.render();
return this.model.resize();
},
openReply: function(ev) {
var action, gettingMentions, query_args,
_this = this;
if (ev) {
ev.preventDefault();
}
this.mode = 'reply';
this.render();
this.$el.children('.wpn-note-comment-reply').children('.wpn-note-comment-reply-text').val(this.model.currentReplyText);
$('.selected .wpn-note-body p.submitconfirm').remove();
this.model.resize();
if (!window.mentionDataCache) {
window.mentionDataCache = [];
}
action = this.actionsByName['replyto-comment'];
if (action.site_id != null) {
if (window.mentionDataCache[action.site_id] != null) {
return this.$el.children('.wpn-note-comment-reply').children('.wpn-note-comment-reply-text').mentions(window.mentionDataCache[action.site_id]);
} else {
window.mentionDataCache[action.site_id] = [];
query_args = {
site_id: action.site_id,
client: 'notes-widget'
};
gettingMentions = wpNotesCommon.getMentions(query_args);
return gettingMentions.done(function(res) {
window.mentionDataCache[action.site_id] = res.suggestions;
return _this.$el.children('.wpn-note-comment-reply').children('.wpn-note-comment-reply-text').mentions(window.mentionDataCache[action.site_id]);
});
}
}
},
sendReply: function(ev) {
var $submitWrap, action, blog_id, comment_id, comment_reply_el, content, doSend,
_this = this;
if (ev) {
ev.preventDefault();
}
action = this.actionsByName['replyto-comment'];
if (!action) {
return $.Deferred().reject('Invalid replyto-comment action');
}
comment_reply_el = this.$el.children('.wpn-note-comment-reply');
this.model.currentReplyText = comment_reply_el.children('.wpn-note-comment-reply-text').val();
blog_id = action.site_id || 0;
comment_id = action.comment_id || 0;
content = this.model.currentReplyText || 0;
if (!(blog_id && comment_id && content)) {
return $.Deferred().reject('Invalid sendReply params');
}
$submitWrap = comment_reply_el.children('.wpn-comment-submit');
$submitWrap.children('.wpn-comment-submit-error').hide();
$submitWrap.children('.wpn-comment-reply-button-send').hide();
$submitWrap.children('.wpn-comment-submit-waiting').gifspin('small').show();
wpNotesCommon.bumpStat('notes-click-action', 'replyto-comment');
doSend = function() {
return wpNotesCommon.ajax({
type: 'POST',
path: '/sites/' + blog_id + '/comments/' + comment_id + '/replies/new',
data: {
content: content
},
success: function(r) {
if (typeof r === 'string') {
_this.errorReply(r);
return false;
}
_this.closeReply();
_this.model.currentReplyText = '';
return _this.model.reload(true).done(function() {
var tries;
if (!_this.model.get('status').i_replied) {
tries = 0;
return _this.replyCommentInterval = setInterval(function() {
return _this.model.reload(true).done(function() {
if (_this.model.get('status').i_replied || tries++ >= 10) {
return clearInterval(_this.replyCommentInterval);
}
});
}, 3000);
}
});
},
error: function(r) {
return _this.errorReply(r);
}
}).done(function() {
var commentPermalink, submitConfirm;
commentPermalink = $('.selected .wpn-comment-date a').attr('href');
submitConfirm = '';
submitConfirm += notes_i18n.translate('Reply successful, view thread ').fetch('target="_blank" href="' + commentPermalink + '"');
submitConfirm += '
';
return $('.selected .wpn-note-body').append(submitConfirm);
});
};
if (this.model.get('status').approval_status !== 'approved') {
return this.modComment('approve-comment').done(doSend);
} else {
return doSend();
}
},
errorReply: function(r) {
var comment_reply_el, er, o;
er = r;
if (typeof r === 'object') {
if (r.responseText) {
o = $.parseJSON(r.responseText);
er = o.error + ': ' + o.message;
} else if (r.statusText) {
er = r.statusText;
} else {
er = 'Unknown Error';
}
}
comment_reply_el = this.$el.children('.wpn-note-comment-reply');
comment_reply_el.children('.wpn-comment-submit').children('.wpn-comment-submit-waiting').hide();
if (er) {
return comment_reply_el.children('.wpn-comment-submit').children('.wpn-comment-submit-error').text(er).show();
}
},
clickModComment: function(ev) {
if (ev) {
ev.preventDefault();
} else {
return $.Deferred.reject('invalid click event');
}
return this.modComment($(ev.currentTarget).data('action-type'));
},
modComment: function(actionType) {
var moderating,
_this = this;
this.$('.wpn-comment-mod-waiting').show().gifspin('small');
moderating = $.Deferred().always(function() {
return _this.$('.wpn-comment-mod-waiting').empty().hide();
}).fail(function(error, code) {
if ((typeof console !== "undefined" && console !== null) && typeof console.error === 'function') {
console.error('Comment moderation error');
if (error) {
console.error(error);
}
}
if (!code || code !== 'too_soon') {
return _this.model.reload();
}
});
if (this.modPromise && typeof this.modPromise.state === 'function' && this.modPromise.state() === 'pending') {
moderating.always(function() {
return _this.$('.wpn-comment-mod-waiting').show().gifspin('small');
});
return moderating.reject('Moderation already in progress', 'too_soon');
}
this.modPromise = moderating.promise();
if (!actionType || !actionType.length || !_.contains(this.getValidActions(), actionType)) {
return moderating.reject('Invalid actionType');
}
$.Deferred(function() {
var action, anticipatedNewStatus;
wpNotesCommon.bumpStat('notes-click-action', actionType);
action = _this.actionsByName[actionType];
if (!action) {
return moderating.reject('Undefined action params for type: ' + actionType);
}
anticipatedNewStatus = _this.getResultantStatus(actionType);
if (anticipatedNewStatus) {
_this.model.set('status', $.extend({}, _this.model.get('status'), {
approval_status: anticipatedNewStatus
}));
_this.$('.wpn-comment-mod-waiting').show().gifspin('small');
}
return wpNotesCommon.ajax({
type: 'POST',
path: action.rest_path,
data: action.rest_body
}).done(function(r) {
var rStatus;
rStatus = (r != null ? r.status : void 0) ? r.status : 'undefined';
if (_.contains(_this.possibleStatuses, rStatus)) {
_this.model.set('status', $.extend({}, _this.model.get('status'), {
approval_status: rStatus
}));
_this.model.blockReloading(15);
return moderating.resolve();
} else {
return moderating.reject('Invalid status: "' + rStatus + '" received from moderation POST');
}
}).fail(function(error) {
return moderating.reject(error);
});
});
return this.modPromise;
},
clickLikeComment: function(ev) {
var $button, actionType;
ev.preventDefault();
$button = $(ev.currentTarget);
actionType = $button.data('action-type');
return this.likeComment(actionType);
},
likeComment: function(actionType) {
var action, i_liked, rest_path,
_this = this;
action = this.actionsByName[actionType];
if ('like-comment' === actionType) {
i_liked = true;
rest_path = action.rest_path + 'new/';
} else {
i_liked = false;
rest_path = action.rest_path + 'mine/delete/';
}
this.model.set('status', $.extend({}, this.model.get('status'), {
i_liked: i_liked
}));
this.$('.wpn-comment-mod-waiting').show().gifspin('small');
return wpNotesCommon.ajax({
type: 'POST',
path: rest_path
}).done(function(r) {
return _this.$('.wpn-comment-mod-waiting').empty().hide();
});
}
});
})(jQuery);
(function() {
(function(window, $) {
/*
* Show an animated gif spinner
* Replaces the contents of the selected jQuery elements with the image
*/
return $.fn.gifspin = function(size) {
var $el, $spinner, len;
$el = $(this);
if (_.isFinite(size) && size > 0) {
len = Math.min(~~size, 128);
} else {
switch (size) {
case 'tiny':
len = 8;
break;
case 'small':
len = 16;
break;
case 'medium':
len = 32;
break;
case 'large':
len = 64;
break;
default:
len = 128;
}
}
$spinner = $(' ');
$spinner.css({
height: len,
width: len
});
$el.html($spinner);
return $el;
};
})(typeof exports !== "undefined" && exports !== null ? exports : this, window.jQuery);
}).call(this);
;
if ( 'undefined' == typeof wpcom ) {
wpcom = {};
}
if ( 'undefined' == typeof wpcom.events ) {
wpcom.events = _.extend( {}, Backbone.Events );
}
(function($) {
// Auto-generated: do not edit!
var __autoCacheBusterNotesPanel = '@automattic/jetpack-blocks@13.1.0-5015-gd57f427480';
// End auto-generated area:
var wpNotesArgs = window.wpNotesArgs || {},
cacheBuster = wpNotesArgs.cacheBuster || __autoCacheBusterNotesPanel,
iframeUrl = wpNotesArgs.iframeUrl || 'https://widgets.wp.com/notes/',
iframeAppend = wpNotesArgs.iframeAppend || '',
iframeScroll = wpNotesArgs.iframeScroll || "no",
wideScreen = wpNotesArgs.wide || false,
hasToggledPanel = false,
iframePanelId, iframeFrameId;
var wpntView = Backbone.View.extend({
el: '#wp-admin-bar-notes',
hasUnseen: null,
initialLoad: true,
count: null,
iframe: null,
iframeWindow: null,
messageQ: [],
iframeSpinnerShown: false,
isJetpack: false,
linkAccountsURL: false,
currentMasterbarActive: false,
initialize: function() {
var t = this;
// graceful fallback for IE <= 7
var matches = navigator.appVersion.match( /MSIE (\d+)/ );
if ( matches && parseInt( matches[1], 10 ) < 8 ) {
var $panel = t.$( '#'+iframePanelId );
var $menuItem = t.$( '.ab-empty-item' );
if ( !$panel.length || !$menuItem.length ) {
return;
}
var offset = t.$el.offset();
t.$( '.ab-item' ).removeClass( 'ab-item' );
t.$( '#wpnt-notes-unread-count' ).html( '?' );
// @todo localize
$panel.html( ' \
\
\
\
Please upgrade your browser to keep using notifications. \
'
).addClass( 'browse-happy' );
t.$el.on( 'mouseenter', function(e) {
clearTimeout( t.fadeOutTimeout );
if ( $panel.is( ':visible:animated' ) ) {
$panel.stop().css( 'opacity', '' );
}
$menuItem.css({ 'background-color': '#eee' });
$panel.show();
});
t.$el.on( 'mouseleave', function() {
t.fadeOutTimeout = setTimeout( function() {
clearTimeout( t.fadeOutTimeout );
if ( $panel.is( ':animated' ) ) {
return;
}
$panel.fadeOut( 250, function() {
$menuItem.css({ 'background-color': 'transparent' });
});
}, 350 );
});
return;
}
// don't break notifications if jquery.spin isn't available
if ( 'function' != typeof $.fn.spin ) {
$.fn.spin = function(x){};
}
this.isRtl = $('#wpadminbar').hasClass('rtl');
this.count = $('#wpnt-notes-unread-count');
this.panel = $( '#'+iframePanelId );
this.hasUnseen = this.count.hasClass( 'wpn-unread' );
if ( 'undefined' != typeof wpNotesIsJetpackClient && wpNotesIsJetpackClient )
t.isJetpack = true;
if ( t.isJetpack && 'undefined' != typeof wpNotesLinkAccountsURL )
t.linkAccountsURL = wpNotesLinkAccountsURL;
this.$el.children('.ab-item').on( 'click touchstart', function(e){
e.preventDefault();
t.togglePanel();
return false;
} );
this.preventDefault = function(e) {
if (e) e.preventDefault();
return false;
};
if ( iframeAppend == '2' ) {
// Disable scrolling on main page when cursor in notifications
this.panel.mouseenter( function() {
document.body.addEventListener( 'mousewheel', t.preventDefault );
});
this.panel.mouseleave( function() {
document.body.removeEventListener( 'mousewheel', t.preventDefault );
});
if ( typeof document.hidden !== 'undefined' ) {
document.addEventListener( 'visibilitychange', function() {
t.postMessage( { action: "toggleVisibility", hidden: document.hidden } );
} );
}
}
// Click outside the panel to close the panel.
$(document).bind( "mousedown focus", function(e) {
var $clicked;
// Don't fire if the panel isn't showing
if ( ! t.showingPanel )
return true;
$clicked = $(e.target);
/**
* Don't fire if there's no real click target
* Prevents Firefox issue described here: http://datap2.wordpress.com/2013/08/15/running-in-to-some-strange/
*/
if ( $clicked.is( document ) )
return true;
// Don't fire on clicks in the panel.
if ( $clicked.closest( '#wp-admin-bar-notes' ).length )
return true;
t.hidePanel();
return false;
});
$(document).on( 'keydown.notes', function (e) {
var keyCode = wpNotesCommon.getKeycode( e );
if ( !keyCode )
return;
if ( ( keyCode == 27 ) ) //ESC close only
t.hidePanel();
if ( ( keyCode == 78 ) ) //n open/close
t.togglePanel();
//ignore other commands if the iframe hasn't been loaded yet
if ( this.iframeWindow === null )
return;
/**
* @TODO these appear to be unnecessary as the iframe doesn't
* listen for these actions and doesn't appear to need
* to. it handles its own keyboard trapping
*/
if ( t.showingPanel && ( ( keyCode == 74 ) || ( keyCode == 40 ) ) ) { //j and down arrow
t.postMessage( { action:"selectNextNote" } );
return false; //prevent default
}
if ( t.showingPanel && ( ( keyCode == 75 ) || ( keyCode == 38 ) ) ) { //k and up arrow
t.postMessage( { action:"selectPrevNote" } );
return false; //prevent default
}
if ( t.showingPanel && ( ( keyCode == 82 ) || ( keyCode == 65 ) ||
( keyCode == 83 ) || ( keyCode == 84 ) ) ) { //mod keys (r,a,s,t) to pass to iframe
t.postMessage( { action:"keyEvent", keyCode: keyCode } );
return false; //prevent default
}
/**
* End TODO section
*/
});
wpcom.events.on( 'notes:togglePanel', function() {
t.togglePanel();
} );
if ( t.isJetpack )
t.loadIframe();
else {
setTimeout(function() {
t.loadIframe();
}, 3000);
}
if ( t.count.hasClass( 'wpn-unread' ) )
wpNotesCommon.bumpStat( 'notes-menu-impressions', 'non-zero' );
else
wpNotesCommon.bumpStat( 'notes-menu-impressions', 'zero' );
// listen for postMessage events from the iframe
$(window).on( 'message', function( event ) {
if ( !event.data && event.originalEvent.data ) {
event = event.originalEvent;
}
if ( event.origin != 'https://widgets.wp.com' ) {
return;
}
try {
var data = ( 'string' == typeof event.data ) ? JSON.parse( event.data ) : event.data;
if ( data.type != 'notesIframeMessage' ) {
return;
}
t.handleEvent( data );
} catch(e){}
});
},
// Done this way, "this" refers to the wpntView object instead of the window.
handleEvent: function( event ) {
var inNewdash = ( 'undefined' !== typeof wpcomNewdash && 'undefined' !== typeof wpcomNewdash.router && 'undefined' !== wpcomNewdash.router.setRoute );
if ( !event || !event.action ) {
return;
}
switch ( event.action ) {
case "togglePanel":
this.togglePanel();
break;
case "render":
this.render( event.num_new, event.latest_type );
break;
case "renderAllSeen":
this.renderAllSeen();
break;
case "iFrameReady":
this.iFrameReady(event);
break;
/**
* @TODO I don't think this action is fired anymore
*/
case "goToNotesPage":
if ( inNewdash ) {
wpcomNewdash.router.setRoute( '/notifications' );
} else {
window.location.href = '//wordpress.com/me/notifications/';
}
break;
/**
* End TODO section
*/
case "widescreen":
var iframe = $( '#'+iframeFrameId );
if ( event.widescreen && ! iframe.hasClass( 'widescreen' ) ) {
iframe.addClass( 'widescreen' );
} else if ( ! event.widescreen && iframe.hasClass( 'widescreen' ) ) {
iframe.removeClass( 'widescreen' );
}
break;
}
},
render: function( num_new, latest_type ) {
var t = this, flash = false;
if ( ( false === this.hasUnseen ) && ( 0 === num_new ) )
return;
//assume the icon is correct on initial load, prevents fading in and out for no reason
if ( this.initialLoad && this.hasUnseen && ( 0 !== num_new ) ) {
this.initialLoad = false;
return;
}
if ( ! this.hasUnseen && ( 0 !== num_new ) ) {
wpNotesCommon.bumpStat( 'notes-menu-impressions', 'non-zero-async' );
}
var latest_icon_type = wpNotesCommon.noteType2Noticon[ latest_type ];
if ( typeof latest_icon_type == 'undefined' )
latest_icon_type = 'notification';
var latest_img_el = $(' ', {
'class' : 'noticon noticon-' + latest_icon_type + ''
});
var status_img_el = this.getStatusIcon( num_new );
if ( 0 === num_new || this.showingPanel ) {
this.hasUnseen = false;
t.count.fadeOut( 200, function() {
t.count.empty();
t.count.removeClass('wpn-unread').addClass('wpn-read');
t.count.html( status_img_el );
t.count.fadeIn( 500 );
} );
if ( wpcom && wpcom.masterbar ) {
wpcom.masterbar.hasUnreadNotifications( false );
}
} else {
if ( this.hasUnseen ) {
// Blink the indicator if it's already on
t.count.fadeOut( 400, function() {
t.count.empty();
t.count.removeClass('wpn-unread' ).addClass('wpn-read');
t.count.html( latest_img_el );
t.count.fadeIn( 400 );
} );
}
this.hasUnseen = true;
t.count.fadeOut( 400, function() {
t.count.empty();
t.count.removeClass('wpn-read').addClass('wpn-unread');
t.count.html( latest_img_el );
t.count.fadeIn( 400, function() { });
});
if ( wpcom && wpcom.masterbar ) {
wpcom.masterbar.hasUnreadNotifications( true );
}
}
},
renderAllSeen: function() {
if ( !this.hasToggledPanel ) {
return;
}
var img_el = this.getStatusIcon(0);
this.count.removeClass('wpn-unread').addClass('wpn-read');
this.count.empty();
this.count.html( img_el );
this.hasUnseen = false;
if ( wpcom && wpcom.masterbar ) {
wpcom.masterbar.hasUnreadNotifications( false );
}
},
getStatusIcon: function( number ) {
var new_icon = '';
switch ( number ) {
case 0:
new_icon = 'noticon noticon-notification';
break;
case 1:
new_icon = 'noticon noticon-notification';
break;
case 2:
new_icon = 'noticon noticon-notification';
break;
default:
new_icon = 'noticon noticon-notification';
}
return $(' ', {
'class' : new_icon
});
},
togglePanel: function() {
if ( !this.hasToggledPanel ) {
this.hasToggledPanel = true;
}
var t = this;
this.loadIframe();
// temp hack until 3.3 merge to highlight toolbar number
//this.$el.removeClass('wpnt-stayopen');
this.$el.toggleClass('wpnt-stayopen');
this.$el.toggleClass('wpnt-show');
this.showingPanel = this.$el.hasClass('wpnt-show');
$( '.ab-active' ).removeClass( 'ab-active' );
if ( this.showingPanel ) {
var $unread = this.$( '.wpn-unread' );
if ( $unread.length ) {
$unread.removeClass( 'wpn-unread' ).addClass( 'wpn-read' );
}
this.reportIframeDelay();
if ( this.hasUnseen )
wpNotesCommon.bumpStat( 'notes-menu-clicks', 'non-zero' );
else
wpNotesCommon.bumpStat( 'notes-menu-clicks', 'zero' );
this.hasUnseen = false;
}
// tell the iframe we are opening it
this.postMessage( { action:"togglePanel", showing:this.showingPanel } );
var focusNotesIframe = function( iframe ) {
if ( null === iframe.contentWindow ) {
iframe.addEventListener( 'load', function() {
iframe.contentWindow.focus();
} );
} else {
iframe.contentWindow.focus();
}
};
if ( this.showingPanel ) {
focusNotesIframe( this.iframe[0] );
} else {
window.focus();
}
this.setActive( this.showingPanel );
},
// Handle juggling the .active state of the masterbar
setActive: function( active ) {
if ( active ) {
this.currentMasterbarActive = $( '.masterbar li.active' );
this.currentMasterbarActive.removeClass( 'active' );
this.$el.addClass( 'active' );
} else {
this.$el.removeClass( 'active' );
this.currentMasterbarActive.addClass( 'active' );
this.currentMasterbarActive = false;
}
this.$el.find( 'a' ).first().blur();
},
loadIframe: function() {
var t = this,
args = [],
src,
lang,
queries,
panelRtl;
if ( t.iframe === null ) {
// Removed spinner here because it shows up so briefly, and is replaced by the iframe spinner in a different spot
// t.panel.addClass('loadingIframe').find('.wpnt-notes-panel-header').spin('large');
t.panel.addClass('loadingIframe');
if ( t.isJetpack ) {
args.push( 'jetpack=true' );
if ( t.linkAccountsURL ) {
args.push( 'link_accounts_url=' + escape( t.linkAccountsURL ) );
}
}
// Attempt to detect if browser is a touch device, similar code
// in Calypso. The class adds CSS needed for mobile Safari to allow
// scrolling of iframe.
if (('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) {
t.panel.addClass( 'touch' );
}
panelRtl = $( '#'+iframePanelId ).attr( 'dir' ) == 'rtl';
lang = $( '#'+iframePanelId ).attr( 'lang' ) || 'en';
args.push( 'v=' + cacheBuster );
args.push( 'locale=' + lang );
queries = ( args.length ) ? '?' + args.join( '&' ) : '';
src = iframeUrl;
if ( iframeAppend == '2' && ( t.isRtl || panelRtl ) && ! /rtl.html$/.test(iframeUrl) ) {
src = iframeUrl + 'rtl.html';
}
src = src + queries + '#' + document.location.toString();
if ( $( '#'+iframePanelId ).attr( 'dir' ) == 'rtl' ) {
src += '&rtl=1';
}
if ( !lang.match( /^en/ ) ) {
src += ( '&lang=' + lang );
}
// Add the iframe (invisible until iFrameReady)
t.iframe = $('');
t.iframe.attr( 'src', src );
if ( wideScreen ) {
t.panel.addClass( 'wide' );
t.iframe.addClass( 'wide' );
}
t.panel.append(t.iframe);
}
},
reportIframeDelay: function() {
if ( !this.iframeWindow ) {
if ( !this.iframeSpinnerShown )
this.iframeSpinnerShown = (new Date()).getTime();
return;
}
if ( this.iframeSpinnerShown !== null ) {
var delay = 0;
if ( this.iframeSpinnerShown )
delay = (new Date()).getTime() - this.iframeSpinnerShown;
if ( delay === 0 )
wpNotesCommon.bumpStat( 'notes_iframe_perceived_delay', '0' );
else if ( delay < 1000 )
wpNotesCommon.bumpStat( 'notes_iframe_perceived_delay', '0-1' );
else if ( delay < 2000 )
wpNotesCommon.bumpStat( 'notes_iframe_perceived_delay', '1-2' );
else if ( delay < 4000 )
wpNotesCommon.bumpStat( 'notes_iframe_perceived_delay', '2-4' );
else if ( delay < 8000 )
wpNotesCommon.bumpStat( 'notes_iframe_perceived_delay', '4-8' );
else
wpNotesCommon.bumpStat( 'notes_iframe_perceived_delay', '8-N' );
this.iframeSpinnerShown = null;
}
},
iFrameReady: function(event) {
var t = this;
var url_parser = document.createElement( 'a' );
url_parser.href = this.iframe.get(0).src;
this.iframeOrigin = url_parser.protocol + '//' + url_parser.host;
this.iframeWindow = this.iframe.get(0).contentWindow;
if ( "num_new" in event )
this.render( event.num_new, event.latest_type );
this.panel.removeClass('loadingIframe').find('.wpnt-notes-panel-header').remove();
this.iframe.show();
if ( this.showingPanel )
this.reportIframeDelay();
// detect user activity and trigger a refresh event in the iframe
$( window ).on( 'focus keydown mousemove scroll', function() {
// Throttle postMessages since the overhead is pretty high & these events fire a lot
var now = ( new Date() ).getTime();
if ( !t.lastActivityRefresh || t.lastActivityRefresh < now - 5000 ) {
t.lastActivityRefresh = now;
t.postMessage( { action: "refreshNotes" } );
}
} );
this.sendQueuedMessages();
},
hidePanel: function() {
if ( this.showingPanel ) {
this.togglePanel();
}
},
postMessage: function( message ) {
var t = this;
try{
var _msg = ( 'string' == typeof message ) ? JSON.parse( message ) : message;
if ( !_.isObject( _msg ) ) {
return;
}
_msg = _.extend( { type: 'notesIframeMessage' }, _msg );
var targetOrigin = this.iframeOrigin;
if ( this.iframeWindow && this.iframeWindow.postMessage ) {
this.iframeWindow.postMessage( JSON.stringify( _msg ), targetOrigin );
} else {
this.messageQ.push( _msg );
}
}
catch(e){}
},
sendQueuedMessages: function() {
var t = this;
_.forEach( this.messageQ, function( m ) {
t.postMessage( m );
} );
this.messageQ = [];
}
});
$(function(){
if ( ( $( '#wpnt-notes-panel' ).length == 0 && $( '#wpnt-notes-panel2' ).length ) &&
( 'undefined' != typeof wpNotesIsJetpackClientV2 && wpNotesIsJetpackClientV2 ) ) {
iframeUrl = 'https://widgets.wp.com/notifications/';
iframeAppend = '2';
iframeScroll = 'yes';
wideScreen = true;
}
iframePanelId = "wpnt-notes-panel" + iframeAppend;
iframeFrameId = "wpnt-notes-iframe" + iframeAppend;
new wpntView();
});
})(jQuery);
;
jQuery(document).ready( function($){
var tosform = {};
tosform.loaded = false;
tosform.setup = function() {
tosform.report_type ='';
tosform.ajaxurl = wpcom_tos_report_form.ajaxurl;
tosform.isLoggedoutUser = wpcom_tos_report_form.isLoggedoutUser;
tosform.$step1 = $( '#report-step-1' );
tosform.$types = tosform.$step1.find( 'input:radio' );
tosform.$step2 = $( '#report-step-2' );
tosform.$step2_details = $( '.step-2-details' );
tosform.$next = $( '#step1-submit' );
tosform.$submit = $( '#step2-submit' );
tosform.$report_url = $('#report-url');
tosform.$report_email = $('#report-email');
tosform.$step3 = $( '#report-confirm' );
tosform.$step3_error = $( '#report-error' );
tosform.$step3.hide();
tosform.$step3_error.hide();
tosform.$step2.hide();
tosform.$step1.show();
tosform.$step2_details.hide();
tosform.$types.attr( 'checked', false );
tosform.$next.attr( 'disabled', true );
tosform.$submit.attr( 'disabled', true );
}
tosform.setup();
tosform.setup_step2 = function() {
$( '#report-step-1' ).fadeOut( 'fast', function(){
tosform.report_type = tosform.$types.filter( ':checked' ).val();
tosform.$step2.fadeIn( 'fast' );
// Show step 2 description depending on type of report
tosform.$step2_details.hide();
if( tosform.report_type == 'copyright' )
$('#step2-submit').hide();
$( '#step-2-' + tosform.report_type).show();
$( '#TB_ajaxContent' ).css( 'height', 'auto' );
});
}
// Enable continue button when an option is selected, if url has been entered and the email is available
$(document).on( 'change.tos_report_form', '#report-step-1 input:radio', function(){
tosform.report_type = tosform.$types.filter( ':checked' ).val();
if ( $.trim( tosform.$report_url.val() ).length != 0 && tosform.report_type.length != 0 && $.trim( tosform.$report_email.val() ).length != 0 )
tosform.$next.attr( 'disabled', false );
else
tosform.$next.attr( 'disabled', true );
});
// Enable continue button when a url has been entered, if an option has been selected and the email is available
$(document).on( 'change.tos_report_form', '#report-url', function(){
if ( $.trim( tosform.$report_url.val() ).length != 0 && tosform.report_type.length != 0 && $.trim( tosform.$report_email.val() ).length != 0 )
tosform.$next.attr( 'disabled', false );
else
tosform.$next.attr( 'disabled', true );
});
// Enable continue button when an email has been entered, if an option is selected and url has been entered
$(document).on( 'change.tos_report_form', '#report-email', function(){
if ( $.trim( tosform.$report_url.val() ).length != 0 && tosform.report_type.length != 0 && $.trim( tosform.$report_email.val() ).length != 0 )
tosform.validateUrl( tosform.$report_url.val() );
else
tosform.$next.attr( 'disabled', true );
});
// Move to step 2
$(document).on( 'click.tos_report_form', '#step1-submit', function(){
if( tosform.isLoggedoutUser) {
$('#step1-submit').val('validating..');
$.ajax( {
url: tosform.ajaxurl,
type : 'POST',
dataType: 'json',
data : {
action: 'tos_validate_report_fields',
report_url: $.trim( tosform.$report_url.val() ),
report_email: $.trim( tosform.$report_email.val() )
},
success: function( errorMessages ) {
$( '#tos-email-error-message' ).empty();
$( '#tos-url-error-message' ).empty();
if( Object.keys(errorMessages.errors).length === 0 ) {
tosform.setup_step2();
} else {
if( typeof errorMessages.errors.email_error_message != 'undefined' )
$( '#tos-email-error-message' ).append( '' + errorMessages.errors.email_error_message + '
' );
if( typeof errorMessages.errors.url_error_message != 'undefined' )
$( '#tos-url-error-message' ).append( '' + errorMessages.errors.url_error_message + '
' );
$( '#step1-submit' ).val( 'Submit' );
}
}
});
} else {
tosform.setup_step2();
}
});
// Enable form submission when reason textarea is field
$(document).on( 'change.tos_report_form input.tos_report_form paste.tos_report_form', 'textarea.step-2-confirm', function(){
if ( $.trim( $(this).val() ).length != 0 )
tosform.$submit.attr( 'disabled', false );
else
tosform.$submit.attr( 'disabled', true );
});
// close window on cancel button click or overlay click
$(document).on( 'click.tos_report_form', '#TB_ajaxContent .tosform-cancel, #TB_overlay', function(e) {
//e.preventDefault();
tb_remove();
});
// close window on 'esc' keypress
$(document).keyup( function(e) {
if ( e.keyCode == 27 ) {
tb_remove();
}
});
// Open form function
var openForm = function(e){
e.preventDefault();
tb_show( wpcom_tos_report_form.report_this_content, '#TB_inline?width=auto&inlineId=report-form-window&modal=true', '' );
$( '#TB_window, #TB_overlay, #TB_load, #TB_ajaxContent' ).addClass( 'tos-report-form' );
var $tb_ajax_content = $( '#TB_ajaxContent.tos-report-form' );
if ( ! tosform.loaded ) {
$tb_ajax_content.spin( 'large' );
$.ajax( {
url: tosform.ajaxurl,
data : {
action: 'tos_form',
post_id: wpcom_tos_report_form.post_ID,
report_url: wpcom_tos_report_form.current_url
},
success: function( form ) {
$( '#TB_ajaxContent' ).html( form ).css( 'height', 'auto' );
tosform.setup();
tosform.loaded = true;
},
xhrFields: {
withCredentials: true
}
} );
} else {
$tb_ajax_content.find( '.spinner' ).remove();
tosform.setup();
}
return false;
};
// open the form
$(document).on( 'click.tos_report_form', '#wp-admin-bar-wpcom_report_url', openForm );
$(document).on( 'click.tos_report_form', '.flb-report a', openForm );
// submit the form
$(document).on( 'submit.tos_report_form', '#report-form', function(e){
e.preventDefault();
// set the reason according to the form type
$( '#report-form input[name=reason]' ).val( $( '#confirm-' + tosform.report_type ).val() );
var formData = $( '#report-form' ).serialize();
$.ajax( {
url: tosform.ajaxurl,
data : formData,
type : 'POST',
success: function(result) {
if ( result.success == true ) {
tosform.$step2.hide();
tosform.$step3.show();
}
else {
tosform.$step2.hide();
tosform.$step3_error.show();
}
},
xhrFields: {
withCredentials: true
}
});
$( '#TB_ajaxContent.tos-report-form' ).spin( 'large' );
setTimeout(function(){
tb_remove();
}, 2000);
})
});
;
/***
* Warning: This file is remotely enqueued in Jetpack's Masterbar module.
* Changing it will also affect Jetpack sites.
*/
jQuery( document ).ready( function( $, wpcom ) {
var masterbar,
menupops = $( 'li#wp-admin-bar-blog.menupop, li#wp-admin-bar-newdash.menupop, li#wp-admin-bar-my-account.menupop' ),
newmenu = $( '#wp-admin-bar-new-post-types' );
// Unbind hoverIntent, we want clickable menus.
menupops
.unbind( 'mouseenter mouseleave' )
.removeProp( 'hoverIntent_t' )
.removeProp( 'hoverIntent_s' )
.on( 'mouseover', function(e) {
var li = $(e.target).closest( 'li.menupop' );
menupops.not(li).removeClass( 'ab-hover' );
li.toggleClass( 'ab-hover' );
} )
.on( 'click touchstart', function(e) {
var $target = $( e.target );
if ( masterbar.focusSubMenus( $target ) ) {
return;
}
e.preventDefault();
masterbar.toggleMenu( $target );
} );
masterbar = {
focusSubMenus: function( $target ) {
// Handle selection of menu items
if ( ! $target.closest( 'ul' ).hasClass( 'ab-top-menu' ) ) {
$target
.closest( 'li' );
return true;
}
return false;
},
toggleMenu: function( $target ) {
var $li = $target.closest( 'li.menupop' ),
$html = $( 'html' );
$( 'body' ).off( 'click.ab-menu' );
$( '#wpadminbar li.menupop' ).not($li).removeClass( 'ab-active wpnt-stayopen wpnt-show' );
if ( $li.hasClass( 'ab-active' ) ) {
$li.removeClass( 'ab-active' );
$html.removeClass( 'ab-menu-open' );
} else {
$li.addClass( 'ab-active' );
$html.addClass( 'ab-menu-open' );
$( 'body' ).on( 'click.ab-menu', function( e ) {
if ( ! $( e.target ).parents( '#wpadminbar' ).length ) {
e.preventDefault();
masterbar.toggleMenu( $li );
$( 'body' ).off( 'click.ab-menu' );
}
} );
}
}
};
} );;
/*globals JSON */
( function( $ ) {
var eventName = 'wpcom_masterbar_click';
var linksTracksEvents = {
//top level items
'wp-admin-bar-blog' : 'my_sites',
'wp-admin-bar-newdash' : 'reader',
'wp-admin-bar-ab-new-post' : 'write_button',
'wp-admin-bar-my-account' : 'my_account',
'wp-admin-bar-notes' : 'notifications',
//my sites - top items
'wp-admin-bar-switch-site' : 'my_sites_switch_site',
'wp-admin-bar-blog-info' : 'my_sites_site_info',
'wp-admin-bar-site-view' : 'my_sites_view_site',
'wp-admin-bar-blog-stats' : 'my_sites_site_stats',
'wp-admin-bar-plan' : 'my_sites_plan',
'wp-admin-bar-plan-badge' : 'my_sites_plan_badge',
//my sites - manage
'wp-admin-bar-edit-page' : 'my_sites_manage_site_pages',
'wp-admin-bar-new-page-badge' : 'my_sites_manage_add_page',
'wp-admin-bar-edit-post' : 'my_sites_manage_blog_posts',
'wp-admin-bar-new-post-badge' : 'my_sites_manage_add_post',
'wp-admin-bar-edit-attachment' : 'my_sites_manage_media',
'wp-admin-bar-new-attachment-badge' : 'my_sites_manage_add_media',
'wp-admin-bar-comments' : 'my_sites_manage_comments',
'wp-admin-bar-edit-jetpack-testimonial' : 'my_sites_manage_testimonials',
'wp-admin-bar-new-jetpack-testimonial' : 'my_sites_manage_add_testimonial',
'wp-admin-bar-edit-jetpack-portfolio' : 'my_sites_manage_portfolio',
'wp-admin-bar-new-jetpack-portfolio' : 'my_sites_manage_add_portfolio',
//my sites - personalize
'wp-admin-bar-themes' : 'my_sites_personalize_themes',
'wp-admin-bar-cmz' : 'my_sites_personalize_themes_customize',
//my sites - configure
'wp-admin-bar-sharing' : 'my_sites_configure_sharing',
'wp-admin-bar-people' : 'my_sites_configure_people',
'wp-admin-bar-people-add' : 'my_sites_configure_people_add_button',
'wp-admin-bar-plugins' : 'my_sites_configure_plugins',
'wp-admin-bar-domains' : 'my_sites_configure_domains',
'wp-admin-bar-domains-add' : 'my_sites_configure_add_domain',
'wp-admin-bar-blog-settings' : 'my_sites_configure_settings',
'wp-admin-bar-legacy-dashboard' : 'my_sites_configure_wp_admin',
//reader
'wp-admin-bar-followed-sites' : 'reader_followed_sites',
'wp-admin-bar-reader-followed-sites-manage': 'reader_manage_followed_sites',
'wp-admin-bar-discover-discover' : 'reader_discover',
'wp-admin-bar-discover-search' : 'reader_search',
'wp-admin-bar-my-activity-my-likes' : 'reader_my_likes',
//account
'wp-admin-bar-user-info' : 'my_account_user_name',
// account - profile
'wp-admin-bar-my-profile' : 'my_account_profile_my_profile',
'wp-admin-bar-account-settings' : 'my_account_profile_account_settings',
'wp-admin-bar-billing' : 'my_account_profile_manage_purchases',
'wp-admin-bar-security' : 'my_account_profile_security',
'wp-admin-bar-notifications' : 'my_account_profile_notifications',
//account - special
'wp-admin-bar-get-apps' : 'my_account_special_get_apps',
'wp-admin-bar-next-steps' : 'my_account_special_next_steps',
'wp-admin-bar-help' : 'my_account_special_help',
};
var notesTracksEvents = {
openSite: function( data ) {
return {
clicked: 'masterbar_notifications_panel_site',
site_id: data.siteId
};
},
openPost: function( data ) {
return {
clicked: 'masterbar_notifications_panel_post',
site_id: data.siteId,
post_id: data.postId
};
},
openComment: function( data ) {
return {
clicked: 'masterbar_notifications_panel_comment',
site_id: data.siteId,
post_id: data.postId,
comment_id: data.commentId
};
}
};
function recordTracksEvent( eventProps ) {
eventProps = eventProps || {};
window._tkq = window._tkq || [];
window._tkq.push( [ 'recordEvent', eventName, eventProps ] );
}
function parseJson( s, defaultValue ) {
try {
return JSON.parse( s );
} catch ( e ) {
return defaultValue;
}
}
$( document ).ready( function() {
var trackableLinks = '.mb-trackable .ab-item:not(div),' +
'#wp-admin-bar-notes .ab-item,' +
'#wp-admin-bar-user-info .ab-item,' +
'.mb-trackable .ab-secondary';
$( trackableLinks ).on( 'click touchstart', function( e ) {
var $target = $( e.target ),
$parent = $target.closest( 'li' );
if ( ! $parent ) {
return;
}
var trackingId = $target.attr( 'ID' ) || $parent.attr( 'ID' );
if ( ! linksTracksEvents.hasOwnProperty( trackingId ) ) {
return;
}
var eventProps = { 'clicked': linksTracksEvents[ trackingId ] };
recordTracksEvent( eventProps );
} );
} );
// listen for postMessage events from the notifications iframe
$( window ).on( 'message', function( e ) {
var event = ! e.data && e.originalEvent.data ? e.originalEvent : e;
if ( event.origin !== 'https://widgets.wp.com' ) {
return;
}
var data = ( 'string' === typeof event.data ) ? parseJson( event.data, {} ) : event.data;
if ( 'notesIframeMessage' !== data.type ) {
return;
}
var eventData = notesTracksEvents[ data.action ];
if ( ! eventData ) {
return;
}
recordTracksEvent( eventData( data ) );
} );
} )( jQuery );
;
var wpcom = window.wpcom || {};
wpcom.actionbar = {};
wpcom.actionbar.data = actionbardata;
// This might be better in another file, but is here for now
(function($){
var fbd = wpcom.actionbar.data,
d = document,
docHeight = $( d ).height(),
b = d.getElementsByTagName( 'body' )[0],
lastScrollTop = 0,
lastScrollDir, fb, fhtml, fbhtml, fbHtmlLi,
followingbtn, followbtn, fbdf, action,
slkhtml = '', foldhtml = '', reporthtml = '',
customizeIcon, editIcon, statsIcon, themeHtml = '', signupHtml = '', loginHtml = '',
viewReaderHtml = '', editSubsHtml = '', editFollowsHtml = '',
toggleactionbar, $actionbar;
// Don't show actionbar when iframed
if ( window != window.top ) {
return;
}
fhtml = '';
fbdf = d.createElement( 'div' );
fbdf.id = 'actionbar';
fbdf.innerHTML = fhtml;
b.appendChild( fbdf );
$actionbar = $( '#actionbar' ).addClass( 'actnbr-' + fbd.themeSlug.replace( '/', '-' ) );
// Add classes based on contents
if ( fbd.canCustomizeSite ) {
$actionbar.addClass( 'actnbr-has-customize' );
}
if ( fbd.canEditPost ) {
$actionbar.addClass( 'actnbr-has-edit' );
}
if ( ! fbd.canCustomizeSite ) {
$actionbar.addClass( 'actnbr-has-follow' );
}
if ( fbd.isFolded ) {
$actionbar.addClass( 'actnbr-folded' );
}
// Show status message if available
if ( fbd.statusMessage ) {
showActionBarStatusMessage( fbd.statusMessage );
}
// *** Actions *****************
// Follow Site
$actionbar.on( 'click', '.actnbr-actn-follow', function(e) {
e.preventDefault();
if ( fbd.isLoggedIn ) {
showActionBarStatusMessage( '' + fbd.i18n.followedText + '
' );
bumpStat( 'followed' );
var eventProps = {
'follow_source': 'actionbar',
'url': fbd.siteURL
};
recordTracksEvent( 'wpcom_actionbar_site_followed', eventProps );
request( 'ab_subscribe_to_blog' );
} else {
showActionBarFollowForm();
}
} )
// UnFollow Site
.on( 'click', '.actnbr-actn-following', function(e) {
e.preventDefault();
$( '#actionbar .actnbr-actn-following' ).replaceWith( '' + followbtn + '' + fbd.i18n.follow + ' ' );
bumpStat( 'unfollowed' );
var eventProps = {
'follow_source': 'actionbar',
'url': fbd.siteURL
};
recordTracksEvent( 'wpcom_actionbar_site_unfollowed', eventProps );
request( 'ab_unsubscribe_from_blog' );
} )
// Show shortlink prompt
.on( 'click', '.actnbr-shortlink a', function(e) {
e.preventDefault();
window.prompt( "Shortlink: ", fbd.shortlink );
} )
// Toggle more menu
.on( 'click', '.actnbr-ellipsis', function(e) {
if ( $( e.target ).closest( 'a' ).hasClass( 'actnbr-action' ) ) {
return false;
}
var popoverLi = $( '#actionbar .actnbr-ellipsis' );
popoverLi.toggleClass( 'actnbr-hidden' );
setTimeout( function() {
if ( ! popoverLi.hasClass( 'actnbr-hidden' ) ) {
bumpStat( 'show_more_menu' );
$( document ).on( 'click.actnbr-body-click', function() {
popoverLi.addClass( 'actnbr-hidden' );
$( document ).off( 'click.actnbr-body-click' );
} );
}
}, 10 );
})
// Fold/Unfold
.on( 'click', '.actnbr-fold', function(e) {
e.preventDefault();
if ( $( '#actionbar' ).hasClass( 'actnbr-folded' ) ) {
$( '.actnbr-fold a' ).html( fbd.i18n.foldBar );
$( '#actionbar' ).removeClass( 'actnbr-folded' );
$.post( fbd.xhrURL, { 'action': 'unfold_actionbar' } );
} else {
$( '.actnbr-fold a' ).html( fbd.i18n.unfoldBar );
$( '#actionbar' ).addClass( 'actnbr-folded' );
$.post( fbd.xhrURL, { 'action': 'fold_actionbar' } );
}
})
// Record stats for clicks
.on( 'click', '.actnbr-sitename a', createStatsBumperEventHandler( 'clicked_site_title' ) )
.on( 'click', '.actnbr-customize a', createStatsBumperEventHandler( 'customized' ) )
.on( 'click', '.actnbr-folded-customize a', createStatsBumperEventHandler( 'customized' ) )
.on( 'click', '.actnbr-theme a', createStatsBumperEventHandler( 'explored_theme' ) )
.on( 'click', '.actnbr-edit a', createStatsBumperEventHandler( 'edited' ) )
.on( 'click', '.actnbr-stats a', createStatsBumperEventHandler( 'clicked_stats' ) )
.on( 'click', '.flb-report a', createStatsBumperEventHandler( 'reported_content' ) )
.on( 'click', '.actnbr-follows a', createStatsBumperEventHandler( 'managed_following' ) )
.on( 'click', '.actnbr-shortlink a', function() {
bumpStat( 'copied_shortlink' );
} )
.on( 'click', '.actnbr-reader a', createStatsBumperEventHandler( 'view_reader' ) )
.on( 'submit', '.actnbr-follow-bubble form', createStatsBumperEventHandler( 'submit_follow_form', function() {
$( '#actionbar .actnbr-follow-bubble form button' ).attr( 'disabled', true );
} ) )
.on( 'click', '.actnbr-login-nudge a', createStatsBumperEventHandler( 'clicked_login_nudge' ) )
.on( 'click', '.actnbr-signup a', createStatsBumperEventHandler( 'clicked_signup_link' ) )
.on( 'click', '.actnbr-login a', createStatsBumperEventHandler( 'clicked_login_link' ) )
.on( 'click', '.actnbr-subs a', createStatsBumperEventHandler( 'clicked_manage_subs_link' ) );
// Make Follow/Unfollow requests
var request = function( action ) {
$.post( fbd.xhrURL, {
'action': action,
'_wpnonce': fbd.nonce,
'source': 'actionbar',
'blog_id': fbd.siteID
});
};
// Show/Hide actionbar on scroll
fb = $('#actionbar');
toggleactionbar = function() {
var st = $(window).scrollTop(),
topOffset = 0;
if ( $(window).scrollTop() < 0 ) {
return;
}
// Still
if ( lastScrollTop == 0 || ( ( st == lastScrollTop ) && lastScrollDir == 'up' ) ) {
fb.removeClass( 'actnbr-hidden' );
// Moving
} else {
// Scrolling Up
if ( st < lastScrollTop ){
fb.removeClass( 'actnbr-hidden' );
lastScrollDir = 'up';
// Scrolling Down
} else {
// check if there are any popovers open, and only hide action bar if not
if ( $( '#actionbar > ul > li:not(.actnbr-hidden) > .actnbr-popover' ).length === 0 ) {
fb.addClass( 'actnbr-hidden' );
lastScrollDir = 'down';
// Hide any menus
$( '#actionbar li' ).addClass( 'actnbr-hidden' );
}
}
}
lastScrollTop = st;
};
setInterval( toggleactionbar, 100 );
var bumpStat = function( stat ) {
return $.post( fbd.xhrURL, {
'action': 'actionbar_stats',
'stat': stat
} );
};
var recordTracksEvent = function( eventName, eventProps ) {
eventProps = eventProps || {};
window._tkq = window._tkq || [];
window._tkq.push( [ 'recordEvent', eventName, eventProps ] );
};
/**
* A factory method for creating an event handler function that will bump a specific stat and ONLY THEN re-dispatch
* the event. This will ensure that the bumped stat is indeed recorded before navigating the page away, as otherwise
* some browsers may very well decide to cancel the stat request in that case.
*
* @param {String} stat the name of the stat to bump
* @param {Function} additionalEffect an additional function that should be called after the stat is bumped
*/
function createStatsBumperEventHandler( stat, additionalEffect ) {
var completedEvents = {};
return function eventHandler( event ) {
if ( completedEvents[ event.timeStamp ] ) {
delete completedEvents[ event.timeStamp ];
// hack-around to submit forms, dispatching "submit" event is not enough for them
if ( event.type === 'submit' ) {
event.target.submit();
}
if ( typeof additionalEffect === 'function' ) {
return additionalEffect( event );
}
return true;
}
event.preventDefault();
event.stopPropagation();
function dispatchOriginalEvent() {
var newEvent;
// Retrieves the native event object created by the browser from the jQuery event object
var originalEvent = event.originalEvent;
/**
* Handles Internet Explorer that doesn't support Event nor CustomEvent constructors
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/Event/Event
* @see https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent
* @see https://stackoverflow.com/questions/26596123/internet-explorer-9-10-11-event-constructor-doesnt-work/
*/
if ( typeof window.CustomEvent !== 'function' ) {
newEvent = document.createEvent( 'CustomEvent' );
newEvent.initCustomEvent(
originalEvent.type,
originalEvent.bubbles,
originalEvent.cancelable,
originalEvent.detail
);
} else {
newEvent = new originalEvent.constructor( originalEvent.type, originalEvent );
}
completedEvents[ newEvent.timeStamp ] = true;
originalEvent.target.dispatchEvent( newEvent );
}
bumpStat( stat ).then( dispatchOriginalEvent, dispatchOriginalEvent );
}
}
function actionBarEscapeHtml(string) {
return String(string).replace(/[&<>"'\/]/g, function (s) {
var entityMap = {
"&": "&",
"<": "<",
">": ">",
'"': '"',
"'": ''',
"/": '/'
};
return entityMap[s];
});
}
function showActionBarStatusMessage( message ) {
$( '#actionbar .actnbr-actn-follow' ).replaceWith( '' + followingbtn + '' + fbd.i18n.following + ' ' );
$( '#actionbar .actnbr-follow-bubble' ).html( ' \
\
');
var btn = $( '#actionbar .actnbr-btn' );
btn.removeClass( 'actnbr-hidden' );
setTimeout( function() {
if ( ! btn.hasClass( 'actnbr-hidden' ) ) {
$( '#actionbar .actnbr-email-field' ).focus();
$( document ).on( 'click.actnbr-body-click', function(e) {
if ( $( e.target ).closest( '.actnbr-popover' )[0] ) {
return;
}
btn.addClass( 'actnbr-hidden' );
$( document ).off( 'click.actnbr-body-click' );
} );
}
}, 10 );
}
function showActionBarFollowForm() {
var btn = $( '#actionbar .actnbr-btn' );
btn.toggleClass( 'actnbr-hidden' );
var form = $('
{{reply_header_text}}
\ \\ \ \ \ \
\