code stringlengths 1 2.08M | language stringclasses 1 value |
|---|---|
/*
* jFlip plugin for jQuery v0.4 (28/2/2009)
*
* A plugin to make a page flipping gallery
*
* Copyright (c) 2008-2009 Renato Formato (rformato@gmail.com)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
*/
;(function($){
var Flip = function(canvas,width,height,images,opts) {
//private vars
opts = $.extend({background:"green",cornersTop:true,scale:"noresize"},opts);
var obj = this,
el = canvas.prev(),
index = 0,
init = false,
background = opts.background,
cornersTop = opts.cornersTop,
gradientColors = opts.gradientColors || ['#4F2727','#FF8F8F','#F00'],
curlSize = opts.curlSize || 0.1,
scale = opts.scale,
patterns = [],
canvas2 = canvas.clone(),
ctx2 = $.browser.msie?null:canvas2[0].getContext("2d"),
canvas = $.browser.msie?$(G_vmlCanvasManager.initElement(canvas[0])):canvas,
ctx = canvas[0].getContext("2d"),
loaded = 0;
var images = images.each(function(i){
if(patterns[i]) return;
var img = this;
img.onload = function() {
var r = 1;
if(scale!="noresize") {
var rx = width/this.width,
ry = height/this.height;
if(scale=="fit")
r = (rx<1 || ry<1)?Math.min(rx,ry):1;
if(scale=="fill") {
r = Math.min(rx,ry);
}
};
$(img).data("flip.scale",r);
patterns[i] = ctx.createPattern(img,"no-repeat");
loaded++;
if(loaded==images.length && !init) {
init = true;
draw();
}
};
if(img.complete)
window.setTimeout(function(){img.onload()},10);
}).get();
var
width = width,height = height,mX = width,mY = height,
basemX = mX*(1-curlSize), basemY = mY*curlSize,sideLeft = false,
off = $.browser.msie?canvas.offset():null,
onCorner = false,
curlDuration=400,curling = false,
animationTimer,startDate,
flipDuration=700,flipping = false,baseFlipX,baseFlipY,
lastmX,lastmY,
inCanvas = false,
mousedown = false,
dragging = false;
$(window).scroll(function(){
//off = canvas.offset(); //update offset on scroll
});
//IE can't handle correctly mouseenter and mouseleave on VML
var c = $.browser.msie?(function(){
var div = $("<div>").width(width).height(height).css({position:"absolute",cursor:"default",zIndex:1}).appendTo("body");
//second hack for IE7 that can't handle correctly mouseenter and mouseleave if the div has no background color
if(parseInt($.browser.version)==7)
div.css({opacity:0.000001,background:"#FFF"});
var positionDiv = function() {
off = canvas.offset();
return div.css({left:off.left+'px',top:off.top+'px'});
}
$(window).resize(positionDiv);
return positionDiv();
})():canvas;
c.mousemove(function(e){
//track the mouse
/*
if(!off) off = canvas.offset(); //safari can't calculate correctly offset at DOM ready
mX = e.clientX-off.left;
mY = e.clientY-off.top;
window.setTimeout(draw,0);
return;
*/
if(!off)
off = canvas.offset(); //safari can't calculate correctly offset at DOM ready
if(mousedown && onCorner) {
if(!dragging) {
dragging = true;
window.clearInterval(animationTimer);
}
mX = !sideLeft?e.pageX-off.left:width-(e.pageX-off.left);
mY = cornersTop?e.pageY-off.top:height-(e.pageY-off.top);
window.setTimeout(draw,0);
return false;
}
lastmX = e.pageX||lastmX, lastmY = e.pageY||lastmY;
if(!flipping) {
sideLeft = (lastmX-off.left)<width/2;
//cornersTop = (lastmY-off.top)<height/2;
}
if(!flipping &&
((lastmX-off.left)>basemX || (lastmX-off.left)<(width-basemX)) &&
((cornersTop && (lastmY-off.top)<basemY) || (!cornersTop && (lastmY-off.top)>(height-basemY)))) {
if(!onCorner) {
onCorner= true;
c.css("cursor","pointer");
}
} else {
if(onCorner) {
onCorner= false;
c.css("cursor","default");
}
};
return false;
}).bind("mouseenter",function(e){
inCanvas = true;
if(flipping) return;
window.clearInterval(animationTimer);
startDate = new Date().getTime();
animationTimer = window.setInterval(cornerCurlIn,10);
return false;
}).bind("mouseleave",function(e){
inCanvas = false;
dragging = false;
mousedown = false;
if(flipping) return;
window.clearInterval(animationTimer);
startDate = new Date().getTime();
animationTimer = window.setInterval(cornerCurlOut,10);
return false;
}).click(function(){
if(onCorner && !flipping) {
flipping = true;
c.triggerHandler("mousemove");
window.clearInterval(animationTimer);
startDate = new Date().getTime();
baseFlipX = mX;
baseFlipY = mY;
animationTimer = window.setInterval(flip,10);
index += sideLeft?-1:1;
if(index<0) index = images.length-1;
if(index==images.length) index = 0;
el.trigger("flip.jflip",[index,images.length]);
}
return false;
}).mousedown(function(){
dragging = false;
mousedown = true;
return false;
}).mouseup(function(){
mousedown = false;
return false;
});
var flip = function() {
var date = new Date(),delta = date.getTime()-startDate;
if(delta>=flipDuration) {
window.clearInterval(animationTimer);
if(sideLeft) {
images.unshift(images.pop());
patterns.unshift(patterns.pop());
} else {
images.push(images.shift());
patterns.push(patterns.shift());
}
mX = width;
mY = height;
draw();
flipping = false;
//init corner move if still in Canvas
if(inCanvas) {
startDate = new Date().getTime();
animationTimer = window.setInterval(cornerCurlIn,10);
c.triggerHandler("mousemove");
}
return;
}
//da mX a -width (mX+width) in duration millisecondi
mX = baseFlipX-2*(width)*delta/flipDuration;
mY = baseFlipY+2*(height)*delta/flipDuration;
draw();
},
cornerMove = function() {
var date = new Date(),delta = date.getTime()-startDate;
mX = basemX+Math.sin(Math.PI*2*delta/1000);
mY = basemY+Math.cos(Math.PI*2*delta/1000);
drawing = true;
window.setTimeout(draw,0);
},
cornerCurlIn = function() {
var date = new Date(),delta = date.getTime()-startDate;
if(delta>=curlDuration) {
window.clearInterval(animationTimer);
startDate = new Date().getTime();
animationTimer = window.setInterval(cornerMove,10);
}
mX = width-(width-basemX)*delta/curlDuration;
mY = basemY*delta/curlDuration;
draw();
},
cornerCurlOut = function() {
var date = new Date(),delta = date.getTime()-startDate;
if(delta>=curlDuration) {
window.clearInterval(animationTimer);
}
mX = basemX+(width-basemX)*delta/curlDuration;
mY = basemY-basemY*delta/curlDuration;
draw();
},
curlShape = function(m,q) {
//cannot draw outside the viewport because of IE blurring the pattern
var intyW = m*width+q,intx0 = -q/m;
if($.browser.msie) {
intyW = Math.round(intyW);
intx0 = Math.round(intx0);
};
ctx.beginPath();
ctx.moveTo(width,Math.min(intyW,height));
ctx.lineTo(width,0);
ctx.lineTo(Math.max(intx0,0),0);
if(intx0<0) {
ctx.lineTo(0,Math.min(q,height));
if(q<height) {
ctx.lineTo((height-q)/m,height);
}
ctx.lineTo(width,height);
} else {
if(intyW<height)
ctx.lineTo(width,intyW);
else {
ctx.lineTo((height-q)/m,height);
ctx.lineTo(width,height);
}
}
},
draw = function() {
if(!init) return;
if($.browser.msie)
ctx.clearRect(0,0,width,height);
ctx.fillStyle = background;
ctx.fillRect(0,0,width,height);
var img = images[0], r = $(img).data("flip.scale");
if($.browser.msie) {
ctx.fillStyle = patterns[0];
ctx.fillStyle.width2 = ctx.fillStyle.width*r;
ctx.fillStyle.height2 = ctx.fillStyle.height*r;
ctx.fillRect(0,0,width,height);
} else {
ctx.drawImage(img,(width-img.width*r)/2,(height-img.height*r)/2,img.width*r,img.height*r);
}
if(mY && mX!=width) {
var m = 2,
q = (mY-m*(mX+width))/2;
m2 = mY/(width-mX),
q2 = mX*m2;
if(m==m2) return;
var sx=1,sy=1,tx=0,ty=0;
ctx.save();
if(sideLeft) {
tx = width;
sx = -1;
}
if(!cornersTop) {
ty = height;
sy = -1;
}
ctx.translate(tx,ty);
ctx.scale(sx,sy);
//draw page flip
//intx,inty is the intersection between the line of the curl and the line
//from the canvas corner to the curl point
var intx = (q2-q)/(m-m2);
var inty = m*intx+q;
//y=m*x+mY-m*mX line per (mX,mY) parallel to the curl line
//y=-x/m+inty+intx/m line perpendicular to the curl line
//intersection x between the 2 lines = int2x
//y of perpendicular for the intersection x = int2y
//opera do not fill a shape if gradient is finished
var int2x = (2*inty+intx+2*m*mX-2*mY)/(2*m+1);
var int2y = -int2x/m+inty+intx/m;
var d = Math.sqrt(Math.pow(intx-int2x,2)+Math.pow(inty-int2y,2));
var stopHighlight = Math.min(d*0.5,30);
var c;
if(!($.browser.mozilla && parseFloat($.browser.version)<1.9)) {
c = ctx;
} else {
c = ctx2;
c.clearRect(0,0,width,height);
c.save();
c.translate(1,0); //the curl shapes do not overlap perfeclty
}
var gradient = c.createLinearGradient(intx,inty,int2x,int2y);
gradient.addColorStop(0, gradientColors[0]);
gradient.addColorStop(stopHighlight/d, gradientColors[1]);
gradient.addColorStop(1, gradientColors[2]);
c.fillStyle = gradient;
c.beginPath();
c.moveTo(-q/m,0);
c.quadraticCurveTo((-q/m+mX)/2+0.02*mX,mY/2,mX,mY);
c.quadraticCurveTo((width+mX)/2,(m*width+q+mY)/2-0.02*(height-mY),width,m*width+q);
if(!($.browser.mozilla && parseFloat($.browser.version)<1.9)) {
c.fill();
} else {
//for ff 2.0 use a clip region on a second canvas and copy all its content (much faster)
c.save();
c.clip();
c.fillRect(0,0,width,height);
c.restore();
ctx.drawImage(canvas2[0],0,0);
c.restore();
}
//can't understand why this doesn't work on ff 2, fill is slow
/*
ctx.save();
ctx.clip();
ctx.fillRect(0,0,width,height);
ctx.restore();
*/
gradient = null;
//draw solid color background
ctx.fillStyle = background;
curlShape(m,q);
ctx.fill();
//draw back image
curlShape(m,q);
//safari and opera delete the path when doing restore
if(!$.browser.safari && !$.browser.opera)
ctx.restore();
var img = sideLeft?images[images.length-1]:images[1];
r = $(img).data("flip.scale");
if($.browser.msie) {
//excanvas does not support clip
ctx.fillStyle = sideLeft?patterns[patterns.length-1]:patterns[1];
//hack to scale the pattern on IE (modified excanvas)
ctx.fillStyle.width2 = ctx.fillStyle.width*r;
ctx.fillStyle.height2 = ctx.fillStyle.height*r;
ctx.fill();
} else {
ctx.save();
ctx.clip();
//safari and opera delete the path when doing restore
//at this point we have not reverted the trasform
if($.browser.safari || $.browser.opera) {
//revert transform
ctx.scale(1/sx,1/sy);
ctx.translate(-tx,-ty);
}
ctx.drawImage(img,(width-img.width*r)/2,(height-img.height*r)/2,img.width*r,img.height*r);
//ctx.drawImage(img,(width-img.width)/2,(height-img.height)/2);
ctx.restore();
if($.browser.safari || $.browser.opera)
ctx.restore()
}
}
}
}
$.fn.jFlip = function(width,height,opts){
return this.each(function() {
$(this).wrap("<div class='flip_gallery'>");
var images = $(this).find("img");
//cannot hide because explorer does not give the image dimensions if hidden
var canvas = $(document.createElement("canvas")).attr({width:width,height:height}).css({margin:0,width:width+"px",height:height+"px"})
$(this).css({position:"absolute",left:"-9000px",top:"-9000px"}).after(canvas);
new Flip($(this).next(),width || 300,height || 300,images,opts);
});
};
})(jQuery);
| JavaScript |
$(document).ready(function() {
//Sidebar Accordion Menu:
$("#main-nav li ul").hide(); //Hide all sub menus
$("#main-nav li a.current").parent().find("ul").slideToggle("slow"); // Slide down the current menu item's sub menu
$("#main-nav li a.nav-top-item").click( // When a top menu item is clicked...
function() {
$(this).parent().siblings().find("ul").slideUp("normal"); // Slide up all sub menus except the one clicked
$(this).next().slideToggle("normal"); // Slide down the clicked sub menu
if ($(this).attr("href") == null || $(this).attr("href") == "" || $(this).attr("href") == "#") {
return false;
}
}
);
// Sidebar Accordion Menu Hover Effect:
$("#main-nav li .nav-top-item").hover(
function() {
$(this).stop();
$(this).animate({ paddingRight: "25px" }, 200);
},
function() {
$(this).stop();
$(this).animate({ paddingRight: "15px" });
}
);
//Minimize Content Box
$(".content-box-header h3").css({ "cursor": "s-resize" }); // Give the h3 in Content Box Header a different cursor
$(".content-box-header-toggled").next().hide(); // Hide the content of the header if it has the class "content-box-header-toggled"
$(".content-box-header h3").click( // When the h3 is clicked...
function() {
$(this).parent().parent().find(".content-box-content").toggle(); // Toggle the Content Box
$(this).parent().toggleClass("content-box-header-toggled"); // Give the Content Box Header a special class for styling and hiding
$(this).parent().find(".content-box-tabs").toggle(); // Toggle the tabs
}
);
// Content box tabs:
$('.content-box .content-box-content div.tab-content').hide(); // Hide the content divs
$('.content-box-content div.default-tab').show(); // Show the div with class "default-tab"
$('ul.content-box-tabs li a.default-tab').addClass('current'); // Set the class of the default tab link to "current"
$('.content-box ul.content-box-tabs li a').click( //When a tab is clicked...
function() {
$(this).parent().siblings().find("a").removeClass('current'); // Remove "current" class from all tabs
$(this).addClass('current'); // Add class "current" to clicked tab
var currentTab = $(this).attr('href'); // Set variable "currentTab" to the value of href of clicked tab
$(currentTab).siblings().hide(); // Hide all content divs
$(currentTab).show(); // Show the content div with the id equal to the id of clicked tab
return false;
}
);
// Check all checkboxes when the one in a table head is checked:
$('.check-all').click(
function() {
$(this).parent().parent().parent().parent().find("input[type='checkbox']").attr('checked', $(this).is(':checked'));
}
)
});
| JavaScript |
// JavaScript Document
$(document).ready(function(){
$("ul.subnav").parent().append("<span></span>"); //Only shows drop down trigger when js is enabled (Adds empty span tag after ul.subnav*)
$("ul.topnav li span").hover(function() { //When trigger is clicked...
//Following events are applied to the subnav itself (moving subnav up and down)
$(this).parent().find("ul.subnav").slideDown('fast').show(); //Drop down the subnav on click
$(this).parent().hover(function() {
}, function(){
$(this).parent().find("ul.subnav").slideUp('slow'); //When the mouse hovers out of the subnav, move it back up
});
//Following events are applied to the trigger (Hover events for the trigger)
}).hover(function() {
$(this).addClass("subhover"); //On hover over, add class "subhover"
}, function(){ //On Hover Out
$(this).removeClass("subhover"); //On hover out, remove class "subhover"
});
$("#dropped").hover(function() { //When trigger is clicked...
//Following events are applied to the subnav itself (moving subnav up and down)
$(this).parent().find("ul.subnav").slideDown('fast').show(); //Drop down the subnav on click
$(this).parent().hover(function() {
}, function(){
$(this).parent().find("ul.subnav").slideUp('slow'); //When the mouse hovers out of the subnav, move it back up
});
//Following events are applied to the trigger (Hover events for the trigger)
}).hover(function() {
$(this).addClass("subhover"); //On hover over, add class "subhover"
}, function(){ //On Hover Out
$(this).removeClass("subhover"); //On hover out, remove class "subhover"
});
$("#dropped2").hover(function() { //When trigger is clicked...
//Following events are applied to the subnav itself (moving subnav up and down)
$(this).parent().find("ul.subnav").slideDown('fast').show(); //Drop down the subnav on click
$(this).parent().hover(function() {
}, function(){
$(this).parent().find("ul.subnav").slideUp('slow'); //When the mouse hovers out of the subnav, move it back up
});
//Following events are applied to the trigger (Hover events for the trigger)
}).hover(function() {
$(this).addClass("subhover"); //On hover over, add class "subhover"
}, function(){ //On Hover Out
$(this).removeClass("subhover"); //On hover out, remove class "subhover"
});
}); | JavaScript |
// JavaScript Document
function inputfocus(){
document.search.search.value="";
} | JavaScript |
// JavaScript Document
$(document).ready(function()
{//8
$('form#loginform').submit(function()
{//7
$('form#loginform .error').remove();
var hasError = false;
$('.required').each(function()
{//4
if(jQuery.trim($(this).val()) == '')
{//1
var labelText = $(this).prev('label').text();
$(this).parent().append('<span class="error">Can not be blank'+labelText+'</span>');
$(this).addClass('inputError');
hasError = true;
}
else if($(this).hasClass('email'))
{//3
var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
if(!emailReg.test(jQuery.trim($(this).val())))
{//2
var labelText = $(this).prev('label').text();
$(this).parent().append('<span class="error">Invalid Email</span>');
$(this).addClass('inputError');
hasError = true;
}//2//
}//3//
else if($(this).hasClass('ans'))
{
var name=/^(5)+$/;
if(!name.test(jQuery.trim($(this).val())))
{
var labettext = $(this).prev('label').text();
$(this).parent().append('<span class="error">Incorrect code<span>');
$(this).addClass('inputError');
hasError = true;
}
}
//phone
else if($(this).hasClass('phone'))
{
var phone=/^([0,9][0-9]{8,9}$)/;
if(!phone.test(jQuery.trim($(this).val())))
{
var labeltext = $(this).prev('label').text();
$(this).parent().append('<span class="error">Invalid phone number</span>');
$(this).addClass('inputError');
hasError = true;
}}//phone
//
else if($(this).hasClass('code'))
{
var phone=/^([0][0-9]{2,4}$)/;
if(!phone.test(jQuery.trim($(this).val())))
{
var labeltext = $(this).prev('label').text();
$(this).parent().append('<span class="error">Invalid ZIP code</span>');
$(this).addClass('inputError');
hasError = true;
}}//phone
else if($(this).hasClass('name'))
{
var name=/^([aA-zZ ])+$/;
/*/^[^\s]+\s[^\s]+$/*/
if(!name.test(jQuery.trim($(this).val())))
{
var labettext = $(this).prev('label').text();
$(this).parent().append('<span class="error">This is not your real name</span>');
$(this).addClass('inputError');
hasError = true;
}
}
}//4//
);
if(!hasError) {
$('form#loginform input.submit').fadeOut('normal', function()
{//6
$(this).parent().append('');
});
var formInput = $(this).serialize();
$.post($(this).attr('action'),formInput, function(data){
$('form#loginform').slideUp("fast", function()
{//5
$(this).before('<p class="success"><strong>Done!</strong> Thank you for contacting us. Your message has been sent. Our customer representative will contact you shortly.</span>')
}//5//
);
}//6//
);
}//7//
return false;
}//8//
);
}
);
| JavaScript |
(function() {
function getScript(src) {
document.write('<' + 'script src="' + src + '"' +
' type="text/javascript"><' + '/script>');
}
getScript("http://api-maps.yandex.ru/1.1/index.xml?key=AJy6-U0BAAAAJr_5MgIAbUmUfURJX0QfQef4pLZO5vNlHjsAAAAAAAAAAACsZenVuLEihxbcpybjyqyczHDMyA==");
})();
function isMarkerVisible() {
return (marker != null);
}
function fillUrls() {
var markerlat = null;
var markerlng = null;
if (isMarkerVisible()) {
markerlat = marker.getCoordPoint().getY();
markerlng = marker.getCoordPoint().getX();
}
var maptype = (map.getType().getName() == 'Схема' ? 'map' : 'sat');
fillUrlsCommon(map.getCenter().getY(), map.getCenter().getX(), map.getZoom(), maptype, markerlat, markerlng);
}
function processMarker(isGPS) {
if (isGPS) {
if (isMarkerVisible()) {
map.removeOverlay(marker);
marker = null;
}
gps_coords = new YMaps.GeoPoint(gps_lng, gps_lat);
addMarker(gps_coords);
map.setCenter(gps_coords, map.getZoom(), map.getType());
} else {
if (isMarkerVisible()) {
map.removeOverlay(marker);
marker = null;
} else {
var markerCoordinates = new YMaps.GeoPoint(map.getCenter().getX(), map.getCenter().getY());
addMarker(markerCoordinates);
}
}
fillUrls();
markerButtons(isGPS);
}
function addMarker(markerCoordinates) {
marker = new YMaps.Placemark(markerCoordinates, {draggable: true});
map.addOverlay(marker);
YMaps.Events.observe(marker, marker.Events.DragEnd, fillUrls);
YMaps.Events.observe(marker, marker.Events.BalloonOpen, function () {
marker.closeBalloon();
});
}
function initialize() {
initMapCanvasSize();
var lat = getParameter('lat');
if (lat == null || isNaN(lat))
lat = def_lat;
var lng = getParameter('lng');
if (lng == null || isNaN(lat))
lng = def_lng;
var z = parseInt(getParameter('z'));
if (z == null || isNaN(z))
z = def_zoom;
var mapType = getParameter('t');
if (mapType == null)
mapType = YMaps.MapType.MAP;
else
if (mapType == 'sat')
mapType = YMaps.MapType.HYBRID;
else
mapType = YMaps.MapType.MAP;
var mlat = getParameter('mlat');
var mlng = getParameter('mlng');
var markerCoordinates = null;
if (mlat != null && !isNaN(mlat) && mlng != null && !isNaN(mlng)) {
markerCoordinates = new YMaps.GeoPoint(mlng, mlat);
}
var mapCenter = new YMaps.GeoPoint(lng,lat);
map = new YMaps.Map(document.getElementById("map_canvas"));
map.setCenter(mapCenter, z, mapType);
map.addControl(new YMaps.TypeControl());
map.addControl(new YMaps.Zoom());
map.addControl(new YMaps.ScaleLine());
map.enableScrollZoom();
YMaps.Events.observe(map, map.Events.Update, fillUrls);
YMaps.Events.observe(map, map.Events.MoveEnd, fillUrls);
YMaps.Events.observe(map, map.Events.DragEnd, fillUrls);
YMaps.Events.observe(map, map.Events.MultiTouchEnd, fillUrls);
YMaps.Events.observe(map, map.Events.SmoothZoomEnd, fillUrls);
YMaps.Events.observe(map, map.Events.TypeChange, fillUrls);
// MARKER
if (markerCoordinates != null) {
addMarker(markerCoordinates);
}
// init methods
fillUrls();
initMarkerButtons(isMarkerVisible());
pageOnLoad();
}
function resizeMap() {
map.redraw(true, null);
fillUrls();
} | JavaScript |
(function() {
function getScript(src) {
document.write('<' + 'script src="' + src + '"' +
' type="text/javascript"><' + '/script>');
}
getScript("http://maps.visicom.ua/api/2.0.0/map/world_ru.js");
})();
function isMarkerVisible() {
return (marker.visible());
}
function fillUrls() {
var markerlat = null;
var markerlng = null;
if (isMarkerVisible()) {
markerlat = marker.coords()[0].lat;
markerlng = marker.coords()[0].lng;
}
var maptype = 'map';
fillUrlsCommon(map.center().lat, map.center().lng, map.zoom(), maptype, markerlat, markerlng);
}
function processMarker(isGPS) {
if (isGPS) {
if (marker.visible()) {
marker.visible(false);
}
gps_coords = {lng: gps_lng, lat: gps_lat};
marker.coords(gps_coords);
marker.visible(true);
map.center(gps_coords);
} else {
if (marker.visible()) {
marker.visible(false);
} else {
marker.coords(map.center());
marker.visible(true);
}
}
fillUrls();
markerButtons(isGPS);
map.repaint();
}
function initialize() {
initMapCanvasSize();
var lat = getParameter('lat');
if (lat == null || isNaN(lat))
lat = def_lat;
var lng = getParameter('lng');
if (lng == null || isNaN(lat))
lng = def_lng;
var z = parseInt(getParameter('z'));
if (z == null || isNaN(z))
z = def_zoom;
var mapCenter = {lng: lng, lat: lat};
var mlat = getParameter('mlat');
var mlng = getParameter('mlng');
var markerCoordinates = null;
if (mlat != null && !isNaN(mlat) && mlng != null && !isNaN(mlng)) {
markerCoordinates = {lng: mlng, lat: mlat};
}
map = new VMap(document.getElementById('map_canvas'));
map.center(mapCenter, z);
// Create marker
marker = new VMarker(markerCoordinates);
marker.visible(markerCoordinates != null ? true : false);
// Set draggable option
marker.draggable(true);
// The hint
//marker.hint('Hint');
// Set header and description of information window
//marker.info('header', 'Description');
// Add a marker on the map
map.add(marker);
// Repaint the map
map.repaint();
marker.enddrag(fillUrls);
// init methods
fillUrls();
initMarkerButtons(marker.visible());
pageOnLoad();
map.enddrag(fillUrls);
map.onzoomchange(fillUrls);
}
function resizeMap() {
map.repaint();
fillUrls();
} | JavaScript |
(function() {
function getScript(src) {
document.write('<' + 'script src="' + src + '"' +
' type="text/javascript"><' + '/script>');
}
getScript("http://maps.google.com/maps/api/js?sensor=false");
})();
function isMarkerVisible() {
return (marker.getVisible());
}
function fillUrls() {
marker.setPosition(map.getCenter());
var markerlat = null;
var markerlng = null;
if (isMarkerVisible()) {
markerlat = marker.getPosition().lat();
markerlng = marker.getPosition().lng();
}
var maptype = (map.getMapTypeId() == 'roadmap' ? 'map' : 'sat');
fillUrlsCommon(map.getCenter().lat(), map.getCenter().lng(), map.getZoom(), maptype, markerlat, markerlng);
}
function processMarker(isGPS) {
if (isGPS) {
if (marker.getVisible()) {
marker.setVisible(false);
}
gps_coords = new google.maps.LatLng(gps_lat, gps_lng);
marker.setPosition(gps_coords);
marker.setVisible(true);
map.setCenter(gps_coords);
} else {
if (marker.getVisible()) {
marker.setVisible(false);
} else {
marker.setPosition(map.getCenter());
marker.setVisible(true);
}
}
fillUrls();
markerButtons(isGPS);
}
function UpControl(controlDiv, map) {
controlDiv.style.padding = '5px';
// Set CSS for the control border
var controlUI = document.createElement('DIV');
controlUI.style.backgroundColor = 'white';
controlUI.style.borderStyle = 'solid';
controlUI.style.borderWidth = '2px';
controlUI.style.cursor = 'pointer';
controlUI.style.textAlign = 'center';
controlUI.title = 'Click to UP the maps';
controlDiv.appendChild(controlUI);
// Set CSS for the control interior
var controlText = document.createElement('DIV');
controlText.style.fontFamily = 'Arial,sans-serif';
controlText.style.fontSize = '22px';
controlText.style.paddingLeft = '4px';
controlText.style.paddingRight = '4px';
controlText.innerHTML = ' UP ';
controlUI.appendChild(controlText);
google.maps.event.addDomListener(controlUI, 'click', function() {
map.panBy(0, -panOffset);
fillUrls();
});
}
function DownControl(controlDiv, map) {
controlDiv.style.padding = '5px';
// Set CSS for the control border
var controlUI = document.createElement('DIV');
controlUI.style.backgroundColor = 'white';
controlUI.style.borderStyle = 'solid';
controlUI.style.borderWidth = '2px';
controlUI.style.cursor = 'pointer';
controlUI.style.textAlign = 'center';
controlUI.title = 'Click to Down the maps';
controlDiv.appendChild(controlUI);
// Set CSS for the control interior
var controlText = document.createElement('DIV');
controlText.style.fontFamily = 'Arial,sans-serif';
controlText.style.fontSize = '22px';
controlText.style.paddingLeft = '4px';
controlText.style.paddingRight = '4px';
controlText.innerHTML = 'DOWN';
controlUI.appendChild(controlText);
google.maps.event.addDomListener(controlUI, 'click', function() {
map.panBy(0, panOffset);
fillUrls();
});
}
function LeftControl(controlDiv, map) {
controlDiv.style.padding = '5px';
// Set CSS for the control border
var controlUI = document.createElement('DIV');
controlUI.style.backgroundColor = 'white';
controlUI.style.borderStyle = 'solid';
controlUI.style.borderWidth = '2px';
controlUI.style.cursor = 'pointer';
controlUI.style.textAlign = 'center';
controlUI.title = 'Click to Left the maps';
controlDiv.appendChild(controlUI);
// Set CSS for the control interior
var controlText = document.createElement('DIV');
controlText.style.fontFamily = 'Arial,sans-serif';
controlText.style.fontSize = '22px';
controlText.style.paddingLeft = '4px';
controlText.style.paddingRight = '4px';
controlText.innerHTML = 'LEFT';
controlUI.appendChild(controlText);
google.maps.event.addDomListener(controlUI, 'click', function() {
map.panBy(-panOffset, 0);
fillUrls();
});
}
function RightControl(controlDiv, map) {
controlDiv.style.padding = '5px';
// Set CSS for the control border
var controlUI = document.createElement('DIV');
controlUI.style.backgroundColor = 'white';
controlUI.style.borderStyle = 'solid';
controlUI.style.borderWidth = '2px';
controlUI.style.cursor = 'pointer';
controlUI.style.textAlign = 'center';
controlUI.title = 'Click to Right the maps';
controlDiv.appendChild(controlUI);
// Set CSS for the control interior
var controlText = document.createElement('DIV');
controlText.style.fontFamily = 'Arial,sans-serif';
controlText.style.fontSize = '22px';
controlText.style.paddingLeft = '4px';
controlText.style.paddingRight = '4px';
controlText.innerHTML = 'RIGHT';
controlUI.appendChild(controlText);
google.maps.event.addDomListener(controlUI, 'click', function() {
map.panBy(panOffset, 0);
fillUrls();
});
}
function ZoomInControl(controlDiv, map) {
controlDiv.style.padding = '5px';
// Set CSS for the control border
var controlUI = document.createElement('DIV');
controlUI.style.backgroundColor = 'white';
controlUI.style.borderStyle = 'solid';
controlUI.style.borderWidth = '2px';
controlUI.style.cursor = 'pointer';
controlUI.style.textAlign = 'center';
controlUI.title = 'Click to Zoom In the maps';
controlDiv.appendChild(controlUI);
// Set CSS for the control interior
var controlText = document.createElement('DIV');
controlText.style.fontFamily = 'Arial,sans-serif';
controlText.style.fontSize = '22px';
controlText.style.paddingLeft = '4px';
controlText.style.paddingRight = '4px';
controlText.innerHTML = 'Zoom In';
controlUI.appendChild(controlText);
google.maps.event.addDomListener(controlUI, 'click', function() {
map.setZoom(map.getZoom() + 1);
fillUrls();
});
}
function ZoomOutControl(controlDiv, map) {
controlDiv.style.padding = '5px';
// Set CSS for the control border
var controlUI = document.createElement('DIV');
controlUI.style.backgroundColor = 'white';
controlUI.style.borderStyle = 'solid';
controlUI.style.borderWidth = '2px';
controlUI.style.cursor = 'pointer';
controlUI.style.textAlign = 'center';
controlUI.title = 'Click to Zoom In the maps';
controlDiv.appendChild(controlUI);
// Set CSS for the control interior
var controlText = document.createElement('DIV');
controlText.style.fontFamily = 'Arial,sans-serif';
controlText.style.fontSize = '22px';
controlText.style.paddingLeft = '4px';
controlText.style.paddingRight = '4px';
controlText.innerHTML = 'Zoom Out';
controlUI.appendChild(controlText);
google.maps.event.addDomListener(controlUI, 'click', function() {
map.setZoom(map.getZoom() - 1);
fillUrls();
});
}
function RoadmapControl(controlDiv, map) {
controlDiv.style.padding = '5px';
// Set CSS for the control border
var controlUI = document.createElement('DIV');
controlUI.style.backgroundColor = 'white';
controlUI.style.borderStyle = 'solid';
controlUI.style.borderWidth = '2px';
controlUI.style.cursor = 'pointer';
controlUI.style.textAlign = 'center';
controlUI.title = 'Click to Roadmap In the maps';
controlDiv.appendChild(controlUI);
// Set CSS for the control interior
var controlText = document.createElement('DIV');
controlText.style.fontFamily = 'Arial,sans-serif';
controlText.style.fontSize = '22px';
controlText.style.paddingLeft = '4px';
controlText.style.paddingRight = '4px';
controlText.innerHTML = 'Roadmap';
controlUI.appendChild(controlText);
google.maps.event.addDomListener(controlUI, 'click', function() {
map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
fillUrls();
});
}
function HybridControl(controlDiv, map) {
controlDiv.style.padding = '5px';
// Set CSS for the control border
var controlUI = document.createElement('DIV');
controlUI.style.backgroundColor = 'white';
controlUI.style.borderStyle = 'solid';
controlUI.style.borderWidth = '2px';
controlUI.style.cursor = 'pointer';
controlUI.style.textAlign = 'center';
controlUI.title = 'Click to Hybrid the maps';
controlDiv.appendChild(controlUI);
// Set CSS for the control interior
var controlText = document.createElement('DIV');
controlText.style.fontFamily = 'Arial,sans-serif';
controlText.style.fontSize = '22px';
controlText.style.paddingLeft = '4px';
controlText.style.paddingRight = '4px';
controlText.innerHTML = 'Hybrid';
controlUI.appendChild(controlText);
google.maps.event.addDomListener(controlUI, 'click', function() {
map.setMapTypeId(google.maps.MapTypeId.HYBRID);
fillUrls();
});
}
function initialize() {
initMapCanvasSize();
var lat = getParameter('lat');
if (lat == null || isNaN(lat))
lat = def_lat;
var lng = getParameter('lng');
if (lng == null || isNaN(lat))
lng = def_lng;
var z = parseInt(getParameter('z'));
if (z == null || isNaN(z))
z = def_zoom;
var mapType = getParameter('t');
if (mapType == null)
mapType = google.maps.MapTypeId.ROADMAP;
else
if (mapType == 'sat')
mapType = google.maps.MapTypeId.HYBRID;
else
mapType = google.maps.MapTypeId.ROADMAP;
var mlat = getParameter('mlat');
var mlng = getParameter('mlng');
var markerCoordinates = null;
if (mlat != null && !isNaN(mlat) && mlng != null && !isNaN(mlng)) {
lng = mlng;
lat = mlat;
markerCoordinates = new google.maps.LatLng(mlat, mlng);
}
var mapCenter = new google.maps.LatLng(lat, lng);
var myOptions = {
zoom: z,
center: mapCenter,
mapTypeId: mapType,
scaleControl: true,
scaleControlOptions: {
position: google.maps.ControlPosition.BOTTOM_LEFT
},
mapTypeControl: false,
panControl: false,
zoomControl: false,
streetViewControl: false,
disableDoubleClickZoom: true,
draggable: false,
scrollwheel: false,
};
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
// Create the DIV to hold the control and call the UpControl() constructor
// passing in this DIV.
var upControlDiv = document.createElement('DIV');
var upControl = new UpControl(upControlDiv, map);
upControlDiv.index = 1;
map.controls[google.maps.ControlPosition.TOP_CENTER].push(upControlDiv);
// Create the DIV to hold the control and call the DownControl() constructor
// passing in this DIV.
var downControlDiv = document.createElement('DIV');
var downControl = new DownControl(downControlDiv, map);
downControlDiv.index = 1;
map.controls[google.maps.ControlPosition.BOTTOM_CENTER].push(downControlDiv);
// Create the DIV to hold the control and call the LeftControl() constructor
// passing in this DIV.
var leftControlDiv = document.createElement('DIV');
var leftControl = new LeftControl(leftControlDiv, map);
leftControlDiv.index = 2;
map.controls[google.maps.ControlPosition.LEFT_CENTER].push(leftControlDiv);
// Create the DIV to hold the control and call the RightControl() constructor
// passing in this DIV.
var rightControlDiv = document.createElement('DIV');
var rightControl = new RightControl(rightControlDiv, map);
rightControlDiv.index = 3;
map.controls[google.maps.ControlPosition.RIGHT_CENTER].push(rightControlDiv);
// Create the DIV to hold the control and call the ZoomInControl() constructor
// passing in this DIV.
var zoomInControlDiv = document.createElement('DIV');
var zoomInControl = new ZoomInControl(zoomInControlDiv, map);
zoomInControlDiv.index = 4;
map.controls[google.maps.ControlPosition.TOP_LEFT].push(zoomInControlDiv);
// Create the DIV to hold the control and call the ZoomOutControl() constructor
// passing in this DIV.
var zoomOutControlDiv = document.createElement('DIV');
var zoomOutControl = new ZoomOutControl(zoomOutControlDiv, map);
zoomOutControlDiv.index = 5;
map.controls[google.maps.ControlPosition.LEFT_TOP].push(zoomOutControlDiv);
// Create the DIV to hold the control and call the RoadmapControl() constructor
// passing in this DIV.
var roadmapControlDiv = document.createElement('DIV');
var roadmapControl = new RoadmapControl(roadmapControlDiv, map);
roadmapControlDiv.index = 5;
map.controls[google.maps.ControlPosition.TOP_RIGHT].push(roadmapControlDiv);
// Create the DIV to hold the control and call the HybridControl() constructor
// passing in this DIV.
var hybridControlDiv = document.createElement('DIV');
var hybridControl = new HybridControl(hybridControlDiv, map);
hybridControlDiv.index = 5;
map.controls[google.maps.ControlPosition.RIGHT_TOP].push(hybridControlDiv);
// MARKER
marker = new google.maps.Marker({
map: map,
draggable: false,
position: markerCoordinates,
visible: (markerCoordinates != null ? true : false)
});
// init methods
fillUrls();
initMarkerButtons(marker.getVisible());
pageOnLoad();
}
function resizeMap() {
google.maps.event.trigger(map, 'resize');
fillUrls();
} | JavaScript |
(function() {
function getScript(src) {
document.write('<' + 'script src="' + src + '"' +
' type="text/javascript"><' + '/script>');
}
getScript("http://maps.google.com/maps/api/js?sensor=false");
})();
function isMarkerVisible() {
return (marker.getVisible());
}
function fillUrls() {
var markerlat = null;
var markerlng = null;
if (isMarkerVisible()) {
markerlat = marker.getPosition().lat();
markerlng = marker.getPosition().lng();
}
var maptype = (map.getMapTypeId() == 'roadmap' ? 'map' : 'sat');
fillUrlsCommon(map.getCenter().lat(), map.getCenter().lng(), map.getZoom(), maptype, markerlat, markerlng);
}
function processMarker(isGPS) {
if (isGPS) {
if (marker.getVisible()) {
marker.setVisible(false);
}
gps_coords = new google.maps.LatLng(gps_lat, gps_lng);
marker.setPosition(gps_coords);
marker.setVisible(true);
map.setCenter(gps_coords);
} else {
if (marker.getVisible()) {
marker.setVisible(false);
} else {
marker.setPosition(map.getCenter());
marker.setVisible(true);
}
}
fillUrls();
markerButtons(isGPS);
}
function initialize() {
initMapCanvasSize();
var lat = getParameter('lat');
if (lat == null || isNaN(lat))
lat = def_lat;
var lng = getParameter('lng');
if (lng == null || isNaN(lat))
lng = def_lng;
var z = parseInt(getParameter('z'));
if (z == null || isNaN(z))
z = def_zoom;
var mapType = getParameter('t');
if (mapType == null)
mapType = google.maps.MapTypeId.ROADMAP;
else
if (mapType == 'sat')
mapType = google.maps.MapTypeId.HYBRID;
else
mapType = google.maps.MapTypeId.ROADMAP;
var mlat = getParameter('mlat');
var mlng = getParameter('mlng');
var markerCoordinates = null;
if (mlat != null && !isNaN(mlat) && mlng != null && !isNaN(mlng)) {
markerCoordinates = new google.maps.LatLng(mlat, mlng);
}
var mapCenter = new google.maps.LatLng(lat, lng);
var myOptions = {
zoom: z,
center: mapCenter,
mapTypeId: mapType,
scaleControl: true,
scaleControlOptions: {
position: google.maps.ControlPosition.BOTTOM_LEFT
},
mapTypeControl: true,
panControl: true,
panControlOptions: {
position: google.maps.ControlPosition.RIGHT_TOP,
},
zoomControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.LEFT_BOTTOM,
style: google.maps.ZoomControlStyle.LARGE
},
rotateControl: true,
rotateControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
},
streetViewControl: false,
};
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
google.maps.event.addDomListener(map, 'zoom_changed', fillUrls);
google.maps.event.addDomListener(map, 'center_changed', fillUrls);
google.maps.event.addDomListener(map, 'maptypeid_changed', fillUrls);
// MARKER
marker = new google.maps.Marker({
map: map,
draggable: true,
animation: google.maps.Animation.DROP,
position: markerCoordinates,
visible: (markerCoordinates != null ? true : false)
});
google.maps.event.addListener(marker, 'position_changed', fillUrls);
// init methods
fillUrls();
initMarkerButtons(marker.getVisible());
pageOnLoad();
}
function resizeMap() {
google.maps.event.trigger(map, 'resize');
fillUrls();
}
| JavaScript |
var _gaq = _gaq || [];
_gaq.push( [ '_setAccount', 'UA-1390959-7' ]);
_gaq.push( [ '_trackPageview' ]);
(function() {
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl'
: 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
function getMapProvider() {
var a_elem = location.href;
var mapProvider = null;
if (a_elem.indexOf('google-maps-mobile') > 0) {
mapProvider = 'google-maps-mobile';
} else if (a_elem.indexOf('google-maps') > 0) {
mapProvider = 'google-maps';
} else if (a_elem.indexOf('yandex-maps') > 0) {
mapProvider = 'yandex-maps';
} else if (a_elem.indexOf('visicom-maps') > 0) {
mapProvider = 'visicom-maps';
} else {
mapProvider = 'google-maps';
}
return mapProvider;
}
(function() {
function getScript(src) {
document.write('<' + 'script src="' + src + '"'
+ ' type="text/javascript"><' + '/script>');
}
getScript("js/maps-providers/" + getMapProvider() + ".js");
})();
//map and marker variables
var map;
var marker;
var gps_coords;
// init params
var def_lat = 48.50;
var def_lng = 31.40;
var def_zoom = 6;
// pan offset for mobile maps
var panOffset = 100;
// gps params
var gps_lat = null;
var gps_lng = null;
var gps_defzoom = '15';
var gps_defmaptype = 'sat';
// standard map sizes
var sizeMicro_w = '320px';
var sizeMicro_h = '200px';
var sizeA_w = '500px';
var sizeA_h = '300px';
var sizeB_w = '640px';
var sizeB_h = '360px';
var sizeC_w = '854px';
var sizeC_h = '480px';
// default maps size
var def_w = sizeB_w;
var def_h = sizeB_h;
// current map position
var curr_maplat;
var curr_maplng;
var curr_mapzoom;
var curr_maptype;
function getParameter(name) {
var winloc_href = window.location.href;
if (winloc_href.indexOf('?') == -1 && winloc_href.indexOf('#') == -1)
return null;
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
// if the parameter in the url hash
if (winloc_href.indexOf('#') != -1) {
var hash_href = "?" + winloc_href.substring(winloc_href.indexOf('#') + 1, winloc_href.length);
var results2 = regex.exec(hash_href);
if (results2 != null) {
// if find - return
return results2[1];
}
}
// if the parameter in the url query
if (winloc_href.indexOf('?') != -1) {
var hash_position = (winloc_href.indexOf('#') == -1) ? winloc_href.length : winloc_href.indexOf('#');
var params_href = winloc_href.substring(winloc_href.indexOf('?'), hash_position);
var results = regex.exec(params_href);
if (results != null) {
// if find - return
return results[1];
}
}
return null;
}
function fillUrlsCommon(maplat, maplng, mapzoom, maptype, markerlat, markerlng) {
// fill the document variable fields for current map position
document.curr_maplat = maplat;
document.curr_maplng = maplng;
document.curr_mapzoom = mapzoom;
document.curr_maptype = maptype;
var params = 'lat=' + maplat + '&lng=' + maplng + '&z=' + mapzoom + '&t='
+ maptype;
if (isMarkerVisible()) {
params += '&mlat=' + markerlat + '&mlng=' + markerlng;
}
params += '&w=' + document.getElementById("map_canvas").style.width;
params += '&h=' + document.getElementById("map_canvas").style.height;
fillTheUrl(params, 'google-maps');
fillTheUrl(params, 'google-maps-mobile');
fillTheUrl(params, 'yandex-maps');
fillTheUrl(params, 'visicom-maps');
fillCurrentMapPositionInText();
fillThePageHash(params);
}
function fillCurrentMapPositionInText() {
var a_elem = location.href;
var currentLink = null;
if (a_elem.indexOf('google-maps-mobile') > 0) {
currentLink = document.getElementById('google-maps-mobile').href;
} else if (a_elem.indexOf('google-maps') > 0) {
currentLink = document.getElementById('google-maps').href;
} else if (a_elem.indexOf('yandex-maps') > 0) {
currentLink = document.getElementById('yandex-maps').href;
} else if (a_elem.indexOf('visicom-maps') > 0) {
currentLink = document.getElementById('visicom-maps').href;
} else {
// default
alert('There is no Map Service in the page location.');
return;
}
document.getElementById('textlink').value = currentLink;
document.getElementById('refresh').href = currentLink;
}
function indexPageOnLoad() {
fillIndexPageUrlsWithGPS();
}
function fillIndexPageUrlsWithGPS() {
if (navigator.geolocation) {
navigator.geolocation
.getCurrentPosition(function(position) {
gps_lat = position.coords.latitude;
gps_lng = position.coords.longitude;
document.getElementById("latitude").innerHTML = gps_lat;
document.getElementById("longitude").innerHTML = gps_lng;
var maplat = gps_lat;
var maplng = gps_lng;
var mapzoom = gps_defzoom;
var maptype = gps_defmaptype;
var markerlat = gps_lat;
var markerlng = gps_lng;
var params = 'lat=' + maplat + '&lng=' + maplng + '&z=' + mapzoom + '&t='
+ maptype;
params += '&mlat=' + markerlat + '&mlng=' + markerlng;
params += '&w=' + def_w;
params += '&h=' + def_h;
fillTheUrl(params, 'google-maps');
fillTheUrl(params, 'yandex-maps');
fillTheUrl(params, 'visicom-maps');
fillTheUrl(params, 'google-maps-mobile');
});
}
}
function fillTheUrl(params, urlname) {
var a_elem = document.getElementById(urlname);
if (a_elem.href.indexOf('#') > 0) {
a_elem.href = a_elem.href.substring(0, a_elem.href.indexOf('#'))
}
if (a_elem.href.indexOf('?') > 0) {
a_elem.href = a_elem.href.substring(0, a_elem.href.indexOf('?'))
}
a_elem.href = a_elem.href + '#' + params;
}
function fillThePageHash(params) {
document.location.hash = '#' + params;
}
function markerButtons(isSetMarker) {
if (isSetMarker) {
document.getElementById("setmarker").style.display = "none";
document.getElementById("removemarker").style.display = "block";
} else {
if (document.getElementById("setmarker").style.display == "none") {
document.getElementById("setmarker").style.display = "block";
document.getElementById("removemarker").style.display = "none";
} else {
document.getElementById("setmarker").style.display = "none";
document.getElementById("removemarker").style.display = "block";
}
}
}
function pageOnLoad() {
initGPS();
// we can add something to init here
}
function initMarkerButtons(visibleMarker) {
if (visibleMarker) {
document.getElementById("setmarker").style.display = "none";
document.getElementById("removemarker").style.display = "block";
} else {
document.getElementById("setmarker").style.display = "block";
document.getElementById("removemarker").style.display = "none";
}
}
function resizeMapCanvas(w, h) {
document.getElementById("map_canvas").style.width = w;
document.getElementById("map_canvas").style.height = h;
document.getElementById("div_url").style.width = w;
document.getElementById("map_links").style.width = w;
document.getElementById("marker_links").style.width = w;
}
function initMapCanvasSize() {
var w = getParameter('w');
var h = getParameter('h');
if (w != null || h != null) {
if (w == null)
w = def_w;
if (h == null)
h = def_h;
resizeMapCanvas(w, h);
} else {
resizeMapCanvas(def_w, def_h);
}
}
function viewPort() {
var h = window.innerHeight || document.documentElement.clientHeight
|| document.getElementsByTagName('body')[0].clientHeight;
var w = window.innerWidth || document.documentElement.clientWidth
|| document.getElementsByTagName('body')[0].clientWidth;
return {
width : w,
height : h
}
}
function resizeMapMicro() {
resizeMapCanvas(sizeMicro_w, sizeMicro_h);
resizeMap();
}
function resizeMapA() {
resizeMapCanvas(sizeA_w, sizeA_h);
resizeMap();
}
function resizeMapB() {
resizeMapCanvas(sizeB_w, sizeB_h);
resizeMap();
}
function resizeMapC() {
resizeMapCanvas(sizeC_w, sizeC_h);
resizeMap();
}
function resizeMapMacro() {
resizeMapCanvas(viewPort().width + 'px', viewPort().height + 'px');
resizeMap();
}
function initGPS() {
if (navigator.geolocation) {
navigator.geolocation
.getCurrentPosition(function(position) {
gps_lat = position.coords.latitude;
gps_lng = position.coords.longitude;
});
}
}
| JavaScript |
(function() {
function getScript(src) {
document.write('<' + 'script src="' + src + '"' +
' type="text/javascript"><' + '/script>');
}
getScript("js/moyakarta-0.3.js");
})();
| JavaScript |
var def_lat = 49.44;
var def_lng = 32.06;
var def_zoom = 13;
var panOffset = 100;
var def_w = '640px';
var def_h = '360px';
var size0_w = '320px';
var size0_h = '200px';
var sizeA_w = def_w;
var sizeA_h = def_h;
var sizeB_w = '854px';
var sizeB_h = '480px';
var map;
var marker;
function getParameter(name)
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return null;
else
return results[1];
}
function fillUrlsCommon(maplat, maplng, mapzoom, maptype, markerlat, markerlng) {
var params = 'lat=' + maplat
+ '&lng=' + maplng
+ '&z=' + mapzoom
+ '&t=' + maptype;
if (isMarkerVisible()) {
params += '&mlat=' + markerlat
+ '&mlng=' + markerlng;
}
//if (document.getElementById("map_canvas").style.width != def_w) {
params += '&w=' + document.getElementById("map_canvas").style.width;
params += '&h=' + document.getElementById("map_canvas").style.height;
//}
fillTheUrl(params, 'google-maps');
fillTheUrl(params, 'google-maps-mobile');
fillTheUrl(params, 'yandex-maps');
fillTheUrl(params, 'visicom-maps');
fillTextLinkUrl();
}
function fillTheUrl(params, urlname) {
var a_elem = document.getElementById(urlname);
if (a_elem.href.indexOf('?') > 0) {
a_elem.href = a_elem.href.substring(0, a_elem.href.indexOf('?'))
}
a_elem.href = a_elem.href + '?' + params;
}
function fillTextLinkUrl() {
var a_elem = location.href;
var currentLink = null;
if (a_elem.indexOf('google-maps-mobile') > 0) {
currentLink = document.getElementById('google-maps-mobile').href;
} else if (a_elem.indexOf('google-maps') > 0) {
currentLink = document.getElementById('google-maps').href;
} else if (a_elem.indexOf('yandex-maps') > 0) {
currentLink = document.getElementById('yandex-maps').href;
} else if (a_elem.indexOf('visicom-maps') > 0) {
currentLink = document.getElementById('visicom-maps').href;
} else {
// default
alert('There is no Map Service in the page location.');
return;
}
document.getElementById('textlink').value = currentLink;
document.getElementById('refresh').href = currentLink;
}
function markerButtons() {
if (document.getElementById("setmarker").style.display == "none") {
document.getElementById("setmarker").style.display = "block";
document.getElementById("removemarker").style.display = "none";
} else {
document.getElementById("setmarker").style.display = "none";
document.getElementById("removemarker").style.display = "block";
}
}
function initStyleButtons() {
styleButtons();
}
function styleButtons() {
if (document.getElementById("newstyle").style.display != "none") {
// get new style
document.getElementById("newstyle").style.display = "none";
document.getElementById("oldstyle").style.display = "block";
document.getElementById("map_links").style.display = "block";
document.getElementById("map_links_old").style.display = "none";
} else {
// get old style
document.getElementById("newstyle").style.display = "block";
document.getElementById("oldstyle").style.display = "none";
document.getElementById("map_links").style.display = "none";
document.getElementById("map_links_old").style.display = "block";
}
}
function initMarkerButtons(visibleMarker) {
if (visibleMarker) {
document.getElementById("setmarker").style.display = "none";
document.getElementById("removemarker").style.display = "block";
} else {
document.getElementById("setmarker").style.display = "block";
document.getElementById("removemarker").style.display = "none";
}
}
function resizeMapCanvas(w, h) {
document.getElementById("map_canvas").style.width = w;
document.getElementById("map_canvas").style.height = h;
document.getElementById("div_url").style.width = w;
document.getElementById("map_links").style.width = w;
}
function initMapCanvasSize() {
var w = getParameter('w');
var h = getParameter('h');
if (w != null || h != null) {
if (w == null)
w = def_w;
if (h == null)
h = def_h;
resizeMapCanvas(w, h);
}
}
function viewPort() {
var h = window.innerHeight || document.documentElement.clientHeight || document.getElementsByTagName('body')[0].clientHeight;
var w = window.innerWidth || document.documentElement.clientWidth || document.getElementsByTagName('body')[0].clientWidth;
return { width : w , height : h }
}
function resizeMap0() {
resizeMapCanvas(size0_w, size0_h);
resizeMap();
}
function resizeMapA() {
resizeMapCanvas(sizeA_w, sizeA_h);
resizeMap();
}
function resizeMapB() {
resizeMapCanvas(sizeB_w, sizeB_h);
resizeMap();
}
function resizeMapMax() {
resizeMapCanvas(viewPort().width + 'px', viewPort().height + 'px');
resizeMap();
}
| JavaScript |
(function() {
function getScript(src) {
document.write('<' + 'script src="' + src + '"' +
' type="text/javascript"><' + '/script>');
}
getScript("10100ckua-0.3.js");
})();
| JavaScript |
var def_lat = 49.44;
var def_lng = 32.06;
var def_zoom = 13;
var panOffset = 100;
var def_w = '500px';
var def_h = '300px';
var map;
var marker;
function getParameter(name)
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return null;
else
return results[1];
}
function fillUrlsCommon(maplat, maplng, mapzoom, maptype, markerlat, markerlng) {
var params = 'lat=' + maplat
+ '&lng=' + maplng
+ '&z=' + mapzoom
+ '&t=' + maptype;
if (isMarkerVisible()) {
params += '&mlat=' + markerlat
+ '&mlng=' + markerlng;
}
//if (document.getElementById("map_canvas").style.width != def_w) {
params += '&w=' + document.getElementById("map_canvas").style.width;
params += '&h=' + document.getElementById("map_canvas").style.height;
//}
fillTheUrl(params, 'google-maps');
fillTheUrl(params, 'google-maps-mobile');
fillTheUrl(params, 'yandex-maps');
fillTheUrl(params, 'visicom-maps');
fillTextLinkUrl();
}
function fillTheUrl(params, urlname) {
var a_elem = document.getElementById(urlname);
if (a_elem.href.indexOf('?') > 0) {
a_elem.href = a_elem.href.substring(0, a_elem.href.indexOf('?'))
}
a_elem.href = a_elem.href + '?' + params;
}
function fillTextLinkUrl() {
var a_elem = location.href;
var currentLink = null;
if (a_elem.indexOf('google-maps-mobile') > 0) {
currentLink = document.getElementById('google-maps-mobile').href;
} else if (a_elem.indexOf('google-maps') > 0) {
currentLink = document.getElementById('google-maps').href;
} else if (a_elem.indexOf('yandex-maps') > 0) {
currentLink = document.getElementById('yandex-maps').href;
} else if (a_elem.indexOf('visicom-maps') > 0) {
currentLink = document.getElementById('visicom-maps').href;
} else {
// default
alert('There is no Map Service in the page location.');
return;
}
document.getElementById('textlink').value = currentLink;
document.getElementById('refresh').href = currentLink;
}
function markerButtons() {
if (document.getElementById("setmarker").style.display == "none") {
document.getElementById("setmarker").style.display = "block";
document.getElementById("removemarker").style.display = "none";
} else {
document.getElementById("setmarker").style.display = "none";
document.getElementById("removemarker").style.display = "block";
}
}
function initStyleButtons() {
styleButtons();
}
function styleButtons() {
if (document.getElementById("newstyle").style.display != "none") {
// get new style
document.getElementById("newstyle").style.display = "none";
document.getElementById("oldstyle").style.display = "block";
document.getElementById("map_links").style.display = "block";
document.getElementById("map_links_old").style.display = "none";
} else {
// get old style
document.getElementById("newstyle").style.display = "block";
document.getElementById("oldstyle").style.display = "none";
document.getElementById("map_links").style.display = "none";
document.getElementById("map_links_old").style.display = "block";
}
}
function initMarkerButtons(visibleMarker) {
if (visibleMarker) {
document.getElementById("setmarker").style.display = "none";
document.getElementById("removemarker").style.display = "block";
} else {
document.getElementById("setmarker").style.display = "block";
document.getElementById("removemarker").style.display = "none";
}
}
function resizeMapCanvas(w, h) {
document.getElementById("map_canvas").style.width = w;
document.getElementById("map_canvas").style.height = h;
document.getElementById("div_url").style.width = w;
document.getElementById("map_links").style.width = w;
}
function initMapCanvasSize() {
var w = getParameter('w');
var h = getParameter('h');
if (w != null || h != null) {
if (w == null)
w = def_w;
if (h == null)
h = def_h;
resizeMapCanvas(w, h);
}
}
| JavaScript |
(function() {
function getScript(src) {
document.write('<' + 'script src="' + src + '"' +
' type="text/javascript"><' + '/script>');
}
getScript("10100ckua-0.2.js");
})();
| JavaScript |
(function() {
function getScript(src) {
document.write('<' + 'script src="' + src + '"' +
' type="text/javascript"><' + '/script>');
}
getScript("10100ckua-0.1.js");
})();
| JavaScript |
var def_lat = 49.44;
var def_lng = 32.06;
var def_zoom = 13;
var panOffset = 100;
var map;
var marker;
function getParameter(name)
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return null;
else
return results[1];
}
function fillTheUrl(params, urlname) {
var a_elem = document.getElementById(urlname);
if (a_elem.href.indexOf('?') > 0) {
a_elem.href = a_elem.href.substring(0, a_elem.href.indexOf('?'))
}
a_elem.href = a_elem.href + '?' + params;
}
function setLinkUrl() {
var a_elem = location.href;
if (a_elem.indexOf('google-maps-mobile') > 0) {
document.getElementById('textlink').value = document.getElementById('google-maps-mobile').href;
} else if (a_elem.indexOf('google-maps') > 0) {
document.getElementById('textlink').value = document.getElementById('google-maps').href;
} else if (a_elem.indexOf('yandex-maps') > 0) {
document.getElementById('textlink').value = document.getElementById('yandex-maps').href;
} else if (a_elem.indexOf('visicom-maps') > 0) {
document.getElementById('textlink').value = document.getElementById('visicom-maps').href;
} else {
// default
alert('There is no Map Service in the page location.');
}
}
function markerButtons() {
if (document.getElementById("setmarker").style.display == "none") {
document.getElementById("setmarker").style.display = "block";
document.getElementById("removemarker").style.display = "none";
} else {
document.getElementById("setmarker").style.display = "none";
document.getElementById("removemarker").style.display = "block";
}
}
function initStyleButtons() {
styleButtons();
}
function styleButtons() {
if (document.getElementById("newstyle").style.display != "none") {
// get new style
document.getElementById("newstyle").style.display = "none";
document.getElementById("oldstyle").style.display = "block";
document.getElementById("map_links").style.display = "block";
document.getElementById("map_links_old").style.display = "none";
} else {
// get old style
document.getElementById("newstyle").style.display = "block";
document.getElementById("oldstyle").style.display = "none";
document.getElementById("map_links").style.display = "none";
document.getElementById("map_links_old").style.display = "block";
}
}
function initMarkerButtons(visibleMarker) {
if (visibleMarker) {
document.getElementById("setmarker").style.display = "none";
document.getElementById("removemarker").style.display = "block";
} else {
document.getElementById("setmarker").style.display = "block";
document.getElementById("removemarker").style.display = "none";
}
} | JavaScript |
(function() {
function getScript(src) {
document.write('<' + 'script src="' + src + '"' +
' type="text/javascript"><' + '/script>');
}
getScript("http://api-maps.yandex.ru/1.1/index.xml?key=AJy6-U0BAAAAJr_5MgIAbUmUfURJX0QfQef4pLZO5vNlHjsAAAAAAAAAAACsZenVuLEihxbcpybjyqyczHDMyA==");
})();
function isMarkerVisible() {
return (marker != null);
}
function fillUrls() {
var markerlat = null;
var markerlng = null;
if (isMarkerVisible()) {
markerlat = marker.getCoordPoint().getY();
markerlng = marker.getCoordPoint().getX();
}
var maptype = (map.getType().getName() == 'Схема' ? 'map' : 'sat');
fillUrlsCommon(map.getCenter().getY(), map.getCenter().getX(), map.getZoom(), maptype, markerlat, markerlng);
}
function processMarker(isGPS) {
if (isGPS) {
if (isMarkerVisible()) {
map.removeOverlay(marker);
marker = null;
}
gps_coords = new YMaps.GeoPoint(gps_lng, gps_lat);
addMarker(gps_coords);
map.setCenter(gps_coords, map.getZoom(), map.getType());
} else {
if (isMarkerVisible()) {
map.removeOverlay(marker);
marker = null;
} else {
var markerCoordinates = new YMaps.GeoPoint(map.getCenter().getX(), map.getCenter().getY());
addMarker(markerCoordinates);
}
}
fillUrls();
markerButtons(isGPS);
}
function addMarker(markerCoordinates) {
marker = new YMaps.Placemark(markerCoordinates, {draggable: true});
map.addOverlay(marker);
YMaps.Events.observe(marker, marker.Events.DragEnd, fillUrls);
YMaps.Events.observe(marker, marker.Events.BalloonOpen, function () {
marker.closeBalloon();
});
}
function initialize() {
initMapCanvasSize();
var lat = getParameter('lat');
if (lat == null || isNaN(lat))
lat = def_lat;
var lng = getParameter('lng');
if (lng == null || isNaN(lat))
lng = def_lng;
var z = parseInt(getParameter('z'));
if (z == null || isNaN(z))
z = def_zoom;
var mapType = getParameter('t');
if (mapType == null)
mapType = YMaps.MapType.MAP;
else
if (mapType == 'sat')
mapType = YMaps.MapType.HYBRID;
else
mapType = YMaps.MapType.MAP;
var mlat = getParameter('mlat');
var mlng = getParameter('mlng');
var markerCoordinates = null;
if (mlat != null && !isNaN(mlat) && mlng != null && !isNaN(mlng)) {
markerCoordinates = new YMaps.GeoPoint(mlng, mlat);
}
var mapCenter = new YMaps.GeoPoint(lng,lat);
map = new YMaps.Map(document.getElementById("map_canvas"));
map.setCenter(mapCenter, z, mapType);
map.addControl(new YMaps.TypeControl());
map.addControl(new YMaps.Zoom());
map.addControl(new YMaps.ScaleLine());
map.enableScrollZoom();
YMaps.Events.observe(map, map.Events.Update, fillUrls);
YMaps.Events.observe(map, map.Events.MoveEnd, fillUrls);
YMaps.Events.observe(map, map.Events.DragEnd, fillUrls);
YMaps.Events.observe(map, map.Events.MultiTouchEnd, fillUrls);
YMaps.Events.observe(map, map.Events.SmoothZoomEnd, fillUrls);
YMaps.Events.observe(map, map.Events.TypeChange, fillUrls);
// MARKER
if (markerCoordinates != null) {
addMarker(markerCoordinates);
}
// init methods
fillUrls();
initMarkerButtons(isMarkerVisible());
pageOnLoad();
}
function resizeMap() {
map.redraw(true, null);
fillUrls();
} | JavaScript |
(function() {
function getScript(src) {
document.write('<' + 'script src="' + src + '"' +
' type="text/javascript"><' + '/script>');
}
getScript("http://maps.visicom.ua/api/2.0.0/map/world_ru.js");
})();
function isMarkerVisible() {
return (marker.visible());
}
function fillUrls() {
var markerlat = null;
var markerlng = null;
if (isMarkerVisible()) {
markerlat = marker.coords()[0].lat;
markerlng = marker.coords()[0].lng;
}
var maptype = 'map';
fillUrlsCommon(map.center().lat, map.center().lng, map.zoom(), maptype, markerlat, markerlng);
}
function processMarker(isGPS) {
if (isGPS) {
if (marker.visible()) {
marker.visible(false);
}
gps_coords = {lng: gps_lng, lat: gps_lat};
marker.coords(gps_coords);
marker.visible(true);
map.center(gps_coords);
} else {
if (marker.visible()) {
marker.visible(false);
} else {
marker.coords(map.center());
marker.visible(true);
}
}
fillUrls();
markerButtons(isGPS);
map.repaint();
}
function initialize() {
initMapCanvasSize();
var lat = getParameter('lat');
if (lat == null || isNaN(lat))
lat = def_lat;
var lng = getParameter('lng');
if (lng == null || isNaN(lat))
lng = def_lng;
var z = parseInt(getParameter('z'));
if (z == null || isNaN(z))
z = def_zoom;
var mapCenter = {lng: lng, lat: lat};
var mlat = getParameter('mlat');
var mlng = getParameter('mlng');
var markerCoordinates = null;
if (mlat != null && !isNaN(mlat) && mlng != null && !isNaN(mlng)) {
markerCoordinates = {lng: mlng, lat: mlat};
}
map = new VMap(document.getElementById('map_canvas'));
map.center(mapCenter, z);
// Create marker
marker = new VMarker(markerCoordinates);
marker.visible(markerCoordinates != null ? true : false);
// Set draggable option
marker.draggable(true);
// The hint
//marker.hint('Hint');
// Set header and description of information window
//marker.info('header', 'Description');
// Add a marker on the map
map.add(marker);
// Repaint the map
map.repaint();
marker.enddrag(fillUrls);
// init methods
fillUrls();
initMarkerButtons(marker.visible());
pageOnLoad();
map.enddrag(fillUrls);
map.onzoomchange(fillUrls);
}
function resizeMap() {
map.repaint();
fillUrls();
} | JavaScript |
(function() {
function getScript(src) {
document.write('<' + 'script src="' + src + '"' +
' type="text/javascript"><' + '/script>');
}
getScript("http://maps.google.com/maps/api/js?sensor=false");
})();
function isMarkerVisible() {
return (marker.getVisible());
}
function fillUrls() {
marker.setPosition(map.getCenter());
var markerlat = null;
var markerlng = null;
if (isMarkerVisible()) {
markerlat = marker.getPosition().lat();
markerlng = marker.getPosition().lng();
}
var maptype = (map.getMapTypeId() == 'roadmap' ? 'map' : 'sat');
fillUrlsCommon(map.getCenter().lat(), map.getCenter().lng(), map.getZoom(), maptype, markerlat, markerlng);
}
function processMarker(isGPS) {
if (isGPS) {
if (marker.getVisible()) {
marker.setVisible(false);
}
gps_coords = new google.maps.LatLng(gps_lat, gps_lng);
marker.setPosition(gps_coords);
marker.setVisible(true);
map.setCenter(gps_coords);
} else {
if (marker.getVisible()) {
marker.setVisible(false);
} else {
marker.setPosition(map.getCenter());
marker.setVisible(true);
}
}
fillUrls();
markerButtons(isGPS);
}
function UpControl(controlDiv, map) {
controlDiv.style.padding = '5px';
// Set CSS for the control border
var controlUI = document.createElement('DIV');
controlUI.style.backgroundColor = 'white';
controlUI.style.borderStyle = 'solid';
controlUI.style.borderWidth = '2px';
controlUI.style.cursor = 'pointer';
controlUI.style.textAlign = 'center';
controlUI.title = 'Click to UP the maps';
controlDiv.appendChild(controlUI);
// Set CSS for the control interior
var controlText = document.createElement('DIV');
controlText.style.fontFamily = 'Arial,sans-serif';
controlText.style.fontSize = '22px';
controlText.style.paddingLeft = '4px';
controlText.style.paddingRight = '4px';
controlText.innerHTML = ' UP ';
controlUI.appendChild(controlText);
google.maps.event.addDomListener(controlUI, 'click', function() {
map.panBy(0, -panOffset);
fillUrls();
});
}
function DownControl(controlDiv, map) {
controlDiv.style.padding = '5px';
// Set CSS for the control border
var controlUI = document.createElement('DIV');
controlUI.style.backgroundColor = 'white';
controlUI.style.borderStyle = 'solid';
controlUI.style.borderWidth = '2px';
controlUI.style.cursor = 'pointer';
controlUI.style.textAlign = 'center';
controlUI.title = 'Click to Down the maps';
controlDiv.appendChild(controlUI);
// Set CSS for the control interior
var controlText = document.createElement('DIV');
controlText.style.fontFamily = 'Arial,sans-serif';
controlText.style.fontSize = '22px';
controlText.style.paddingLeft = '4px';
controlText.style.paddingRight = '4px';
controlText.innerHTML = 'DOWN';
controlUI.appendChild(controlText);
google.maps.event.addDomListener(controlUI, 'click', function() {
map.panBy(0, panOffset);
fillUrls();
});
}
function LeftControl(controlDiv, map) {
controlDiv.style.padding = '5px';
// Set CSS for the control border
var controlUI = document.createElement('DIV');
controlUI.style.backgroundColor = 'white';
controlUI.style.borderStyle = 'solid';
controlUI.style.borderWidth = '2px';
controlUI.style.cursor = 'pointer';
controlUI.style.textAlign = 'center';
controlUI.title = 'Click to Left the maps';
controlDiv.appendChild(controlUI);
// Set CSS for the control interior
var controlText = document.createElement('DIV');
controlText.style.fontFamily = 'Arial,sans-serif';
controlText.style.fontSize = '22px';
controlText.style.paddingLeft = '4px';
controlText.style.paddingRight = '4px';
controlText.innerHTML = 'LEFT';
controlUI.appendChild(controlText);
google.maps.event.addDomListener(controlUI, 'click', function() {
map.panBy(-panOffset, 0);
fillUrls();
});
}
function RightControl(controlDiv, map) {
controlDiv.style.padding = '5px';
// Set CSS for the control border
var controlUI = document.createElement('DIV');
controlUI.style.backgroundColor = 'white';
controlUI.style.borderStyle = 'solid';
controlUI.style.borderWidth = '2px';
controlUI.style.cursor = 'pointer';
controlUI.style.textAlign = 'center';
controlUI.title = 'Click to Right the maps';
controlDiv.appendChild(controlUI);
// Set CSS for the control interior
var controlText = document.createElement('DIV');
controlText.style.fontFamily = 'Arial,sans-serif';
controlText.style.fontSize = '22px';
controlText.style.paddingLeft = '4px';
controlText.style.paddingRight = '4px';
controlText.innerHTML = 'RIGHT';
controlUI.appendChild(controlText);
google.maps.event.addDomListener(controlUI, 'click', function() {
map.panBy(panOffset, 0);
fillUrls();
});
}
function ZoomInControl(controlDiv, map) {
controlDiv.style.padding = '5px';
// Set CSS for the control border
var controlUI = document.createElement('DIV');
controlUI.style.backgroundColor = 'white';
controlUI.style.borderStyle = 'solid';
controlUI.style.borderWidth = '2px';
controlUI.style.cursor = 'pointer';
controlUI.style.textAlign = 'center';
controlUI.title = 'Click to Zoom In the maps';
controlDiv.appendChild(controlUI);
// Set CSS for the control interior
var controlText = document.createElement('DIV');
controlText.style.fontFamily = 'Arial,sans-serif';
controlText.style.fontSize = '22px';
controlText.style.paddingLeft = '4px';
controlText.style.paddingRight = '4px';
controlText.innerHTML = 'Zoom In';
controlUI.appendChild(controlText);
google.maps.event.addDomListener(controlUI, 'click', function() {
map.setZoom(map.getZoom() + 1);
fillUrls();
});
}
function ZoomOutControl(controlDiv, map) {
controlDiv.style.padding = '5px';
// Set CSS for the control border
var controlUI = document.createElement('DIV');
controlUI.style.backgroundColor = 'white';
controlUI.style.borderStyle = 'solid';
controlUI.style.borderWidth = '2px';
controlUI.style.cursor = 'pointer';
controlUI.style.textAlign = 'center';
controlUI.title = 'Click to Zoom In the maps';
controlDiv.appendChild(controlUI);
// Set CSS for the control interior
var controlText = document.createElement('DIV');
controlText.style.fontFamily = 'Arial,sans-serif';
controlText.style.fontSize = '22px';
controlText.style.paddingLeft = '4px';
controlText.style.paddingRight = '4px';
controlText.innerHTML = 'Zoom Out';
controlUI.appendChild(controlText);
google.maps.event.addDomListener(controlUI, 'click', function() {
map.setZoom(map.getZoom() - 1);
fillUrls();
});
}
function RoadmapControl(controlDiv, map) {
controlDiv.style.padding = '5px';
// Set CSS for the control border
var controlUI = document.createElement('DIV');
controlUI.style.backgroundColor = 'white';
controlUI.style.borderStyle = 'solid';
controlUI.style.borderWidth = '2px';
controlUI.style.cursor = 'pointer';
controlUI.style.textAlign = 'center';
controlUI.title = 'Click to Roadmap In the maps';
controlDiv.appendChild(controlUI);
// Set CSS for the control interior
var controlText = document.createElement('DIV');
controlText.style.fontFamily = 'Arial,sans-serif';
controlText.style.fontSize = '22px';
controlText.style.paddingLeft = '4px';
controlText.style.paddingRight = '4px';
controlText.innerHTML = 'Roadmap';
controlUI.appendChild(controlText);
google.maps.event.addDomListener(controlUI, 'click', function() {
map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
fillUrls();
});
}
function HybridControl(controlDiv, map) {
controlDiv.style.padding = '5px';
// Set CSS for the control border
var controlUI = document.createElement('DIV');
controlUI.style.backgroundColor = 'white';
controlUI.style.borderStyle = 'solid';
controlUI.style.borderWidth = '2px';
controlUI.style.cursor = 'pointer';
controlUI.style.textAlign = 'center';
controlUI.title = 'Click to Hybrid the maps';
controlDiv.appendChild(controlUI);
// Set CSS for the control interior
var controlText = document.createElement('DIV');
controlText.style.fontFamily = 'Arial,sans-serif';
controlText.style.fontSize = '22px';
controlText.style.paddingLeft = '4px';
controlText.style.paddingRight = '4px';
controlText.innerHTML = 'Hybrid';
controlUI.appendChild(controlText);
google.maps.event.addDomListener(controlUI, 'click', function() {
map.setMapTypeId(google.maps.MapTypeId.HYBRID);
fillUrls();
});
}
function initialize() {
initMapCanvasSize();
var lat = getParameter('lat');
if (lat == null || isNaN(lat))
lat = def_lat;
var lng = getParameter('lng');
if (lng == null || isNaN(lat))
lng = def_lng;
var z = parseInt(getParameter('z'));
if (z == null || isNaN(z))
z = def_zoom;
var mapType = getParameter('t');
if (mapType == null)
mapType = google.maps.MapTypeId.ROADMAP;
else
if (mapType == 'sat')
mapType = google.maps.MapTypeId.HYBRID;
else
mapType = google.maps.MapTypeId.ROADMAP;
var mlat = getParameter('mlat');
var mlng = getParameter('mlng');
var markerCoordinates = null;
if (mlat != null && !isNaN(mlat) && mlng != null && !isNaN(mlng)) {
lng = mlng;
lat = mlat;
markerCoordinates = new google.maps.LatLng(mlat, mlng);
}
var mapCenter = new google.maps.LatLng(lat, lng);
var myOptions = {
zoom: z,
center: mapCenter,
mapTypeId: mapType,
scaleControl: true,
scaleControlOptions: {
position: google.maps.ControlPosition.BOTTOM_LEFT
},
mapTypeControl: false,
panControl: false,
zoomControl: false,
streetViewControl: false,
disableDoubleClickZoom: true,
draggable: false,
scrollwheel: false,
};
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
// Create the DIV to hold the control and call the UpControl() constructor
// passing in this DIV.
var upControlDiv = document.createElement('DIV');
var upControl = new UpControl(upControlDiv, map);
upControlDiv.index = 1;
map.controls[google.maps.ControlPosition.TOP_CENTER].push(upControlDiv);
// Create the DIV to hold the control and call the DownControl() constructor
// passing in this DIV.
var downControlDiv = document.createElement('DIV');
var downControl = new DownControl(downControlDiv, map);
downControlDiv.index = 1;
map.controls[google.maps.ControlPosition.BOTTOM_CENTER].push(downControlDiv);
// Create the DIV to hold the control and call the LeftControl() constructor
// passing in this DIV.
var leftControlDiv = document.createElement('DIV');
var leftControl = new LeftControl(leftControlDiv, map);
leftControlDiv.index = 2;
map.controls[google.maps.ControlPosition.LEFT_CENTER].push(leftControlDiv);
// Create the DIV to hold the control and call the RightControl() constructor
// passing in this DIV.
var rightControlDiv = document.createElement('DIV');
var rightControl = new RightControl(rightControlDiv, map);
rightControlDiv.index = 3;
map.controls[google.maps.ControlPosition.RIGHT_CENTER].push(rightControlDiv);
// Create the DIV to hold the control and call the ZoomInControl() constructor
// passing in this DIV.
var zoomInControlDiv = document.createElement('DIV');
var zoomInControl = new ZoomInControl(zoomInControlDiv, map);
zoomInControlDiv.index = 4;
map.controls[google.maps.ControlPosition.TOP_LEFT].push(zoomInControlDiv);
// Create the DIV to hold the control and call the ZoomOutControl() constructor
// passing in this DIV.
var zoomOutControlDiv = document.createElement('DIV');
var zoomOutControl = new ZoomOutControl(zoomOutControlDiv, map);
zoomOutControlDiv.index = 5;
map.controls[google.maps.ControlPosition.LEFT_TOP].push(zoomOutControlDiv);
// Create the DIV to hold the control and call the RoadmapControl() constructor
// passing in this DIV.
var roadmapControlDiv = document.createElement('DIV');
var roadmapControl = new RoadmapControl(roadmapControlDiv, map);
roadmapControlDiv.index = 5;
map.controls[google.maps.ControlPosition.TOP_RIGHT].push(roadmapControlDiv);
// Create the DIV to hold the control and call the HybridControl() constructor
// passing in this DIV.
var hybridControlDiv = document.createElement('DIV');
var hybridControl = new HybridControl(hybridControlDiv, map);
hybridControlDiv.index = 5;
map.controls[google.maps.ControlPosition.RIGHT_TOP].push(hybridControlDiv);
// MARKER
marker = new google.maps.Marker({
map: map,
draggable: false,
position: markerCoordinates,
visible: (markerCoordinates != null ? true : false)
});
// init methods
fillUrls();
initMarkerButtons(marker.getVisible());
pageOnLoad();
}
function resizeMap() {
google.maps.event.trigger(map, 'resize');
fillUrls();
} | JavaScript |
(function() {
function getScript(src) {
document.write('<' + 'script src="' + src + '"' +
' type="text/javascript"><' + '/script>');
}
getScript("http://maps.google.com/maps/api/js?sensor=false");
})();
function isMarkerVisible() {
return (marker.getVisible());
}
function fillUrls() {
var markerlat = null;
var markerlng = null;
if (isMarkerVisible()) {
markerlat = marker.getPosition().lat();
markerlng = marker.getPosition().lng();
}
var maptype = (map.getMapTypeId() == 'roadmap' ? 'map' : 'sat');
fillUrlsCommon(map.getCenter().lat(), map.getCenter().lng(), map.getZoom(), maptype, markerlat, markerlng);
}
function processMarker(isGPS) {
if (isGPS) {
if (marker.getVisible()) {
marker.setVisible(false);
}
gps_coords = new google.maps.LatLng(gps_lat, gps_lng);
marker.setPosition(gps_coords);
marker.setVisible(true);
map.setCenter(gps_coords);
} else {
if (marker.getVisible()) {
marker.setVisible(false);
} else {
marker.setPosition(map.getCenter());
marker.setVisible(true);
}
}
fillUrls();
markerButtons(isGPS);
}
function initialize() {
initMapCanvasSize();
var lat = getParameter('lat');
if (lat == null || isNaN(lat))
lat = def_lat;
var lng = getParameter('lng');
if (lng == null || isNaN(lat))
lng = def_lng;
var z = parseInt(getParameter('z'));
if (z == null || isNaN(z))
z = def_zoom;
var mapType = getParameter('t');
if (mapType == null)
mapType = google.maps.MapTypeId.ROADMAP;
else
if (mapType == 'sat')
mapType = google.maps.MapTypeId.HYBRID;
else
mapType = google.maps.MapTypeId.ROADMAP;
var mlat = getParameter('mlat');
var mlng = getParameter('mlng');
var markerCoordinates = null;
if (mlat != null && !isNaN(mlat) && mlng != null && !isNaN(mlng)) {
markerCoordinates = new google.maps.LatLng(mlat, mlng);
}
var mapCenter = new google.maps.LatLng(lat, lng);
var myOptions = {
zoom: z,
center: mapCenter,
mapTypeId: mapType,
scaleControl: true,
scaleControlOptions: {
position: google.maps.ControlPosition.BOTTOM_LEFT
},
mapTypeControl: true,
panControl: true,
panControlOptions: {
position: google.maps.ControlPosition.RIGHT_TOP,
},
zoomControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.LEFT_BOTTOM,
style: google.maps.ZoomControlStyle.LARGE
},
rotateControl: true,
rotateControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
},
streetViewControl: false,
};
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
google.maps.event.addDomListener(map, 'zoom_changed', fillUrls);
google.maps.event.addDomListener(map, 'center_changed', fillUrls);
google.maps.event.addDomListener(map, 'maptypeid_changed', fillUrls);
// MARKER
marker = new google.maps.Marker({
map: map,
draggable: true,
animation: google.maps.Animation.DROP,
position: markerCoordinates,
visible: (markerCoordinates != null ? true : false)
});
google.maps.event.addListener(marker, 'position_changed', fillUrls);
// init methods
fillUrls();
initMarkerButtons(marker.getVisible());
pageOnLoad();
}
function resizeMap() {
google.maps.event.trigger(map, 'resize');
fillUrls();
}
| JavaScript |
var _gaq = _gaq || [];
_gaq.push( [ '_setAccount', 'UA-1390959-7' ]);
_gaq.push( [ '_trackPageview' ]);
(function() {
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl'
: 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
function getMapProvider() {
var a_elem = location.href;
var mapProvider = null;
if (a_elem.indexOf('google-maps-mobile') > 0) {
mapProvider = 'google-maps-mobile';
} else if (a_elem.indexOf('google-maps') > 0) {
mapProvider = 'google-maps';
} else if (a_elem.indexOf('yandex-maps') > 0) {
mapProvider = 'yandex-maps';
} else if (a_elem.indexOf('visicom-maps') > 0) {
mapProvider = 'visicom-maps';
} else {
mapProvider = 'google-maps';
}
return mapProvider;
}
(function() {
function getScript(src) {
document.write('<' + 'script src="' + src + '"'
+ ' type="text/javascript"><' + '/script>');
}
getScript("js/maps-providers/" + getMapProvider() + ".js");
})();
//map and marker variables
var map;
var marker;
var gps_coords;
// init params
var def_lat = 48.50;
var def_lng = 31.40;
var def_zoom = 6;
// pan offset for mobile maps
var panOffset = 100;
// gps params
var gps_lat = null;
var gps_lng = null;
var gps_defzoom = '15';
var gps_defmaptype = 'sat';
// standard map sizes
var sizeMicro_w = '320px';
var sizeMicro_h = '200px';
var sizeA_w = '500px';
var sizeA_h = '300px';
var sizeB_w = '640px';
var sizeB_h = '360px';
var sizeC_w = '854px';
var sizeC_h = '480px';
// default maps size
var def_w = sizeB_w;
var def_h = sizeB_h;
// current map position
var curr_maplat;
var curr_maplng;
var curr_mapzoom;
var curr_maptype;
function getParameter(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results == null)
return null;
else
return results[1];
}
function fillUrlsCommon(maplat, maplng, mapzoom, maptype, markerlat, markerlng) {
// fill the document variable fields for current map position
document.curr_maplat = maplat;
document.curr_maplng = maplng;
document.curr_mapzoom = mapzoom;
document.curr_maptype = maptype;
var params = 'lat=' + maplat + '&lng=' + maplng + '&z=' + mapzoom + '&t='
+ maptype;
if (isMarkerVisible()) {
params += '&mlat=' + markerlat + '&mlng=' + markerlng;
}
params += '&w=' + document.getElementById("map_canvas").style.width;
params += '&h=' + document.getElementById("map_canvas").style.height;
fillTheUrl(params, 'google-maps');
fillTheUrl(params, 'google-maps-mobile');
fillTheUrl(params, 'yandex-maps');
fillTheUrl(params, 'visicom-maps');
fillCurrentMapPositionInText();
}
function fillCurrentMapPositionInText() {
var a_elem = location.href;
var currentLink = null;
if (a_elem.indexOf('google-maps-mobile') > 0) {
currentLink = document.getElementById('google-maps-mobile').href;
} else if (a_elem.indexOf('google-maps') > 0) {
currentLink = document.getElementById('google-maps').href;
} else if (a_elem.indexOf('yandex-maps') > 0) {
currentLink = document.getElementById('yandex-maps').href;
} else if (a_elem.indexOf('visicom-maps') > 0) {
currentLink = document.getElementById('visicom-maps').href;
} else {
// default
alert('There is no Map Service in the page location.');
return;
}
document.getElementById('textlink').value = currentLink;
document.getElementById('refresh').href = currentLink;
}
function indexPageOnLoad() {
fillIndexPageUrlsWithGPS();
}
function fillIndexPageUrlsWithGPS() {
if (navigator.geolocation) {
navigator.geolocation
.getCurrentPosition(function(position) {
gps_lat = position.coords.latitude;
gps_lng = position.coords.longitude;
document.getElementById("latitude").innerHTML = gps_lat;
document.getElementById("longitude").innerHTML = gps_lng;
var maplat = gps_lat;
var maplng = gps_lng;
var mapzoom = gps_defzoom;
var maptype = gps_defmaptype;
var markerlat = gps_lat;
var markerlng = gps_lng;
var params = 'lat=' + maplat + '&lng=' + maplng + '&z=' + mapzoom + '&t='
+ maptype;
params += '&mlat=' + markerlat + '&mlng=' + markerlng;
params += '&w=' + def_w;
params += '&h=' + def_h;
fillTheUrl(params, 'google-maps');
fillTheUrl(params, 'yandex-maps');
fillTheUrl(params, 'visicom-maps');
fillTheUrl(params, 'google-maps-mobile');
});
}
}
/*
function fillGPSLink() {
if (navigator.geolocation) {
navigator.geolocation
.getCurrentPosition(function(position) {
gps_lat = position.coords.latitude;
gps_lng = position.coords.longitude;
document.getElementById("gpslink").style.display = "block";
var maplat = gps_lat;
var maplng = gps_lng;
var mapzoom = document.curr_mapzoom;
var maptype = document.curr_maptype;
var markerlat = gps_lat;
var markerlng = gps_lng;
var params = 'lat=' + maplat + '&lng=' + maplng + '&z=' + mapzoom + '&t='
+ maptype;
params += '&mlat=' + markerlat + '&mlng=' + markerlng;
params += '&w=' + document.getElementById("map_canvas").style.width;
params += '&h=' + document.getElementById("map_canvas").style.height;
var a_elem = document.getElementById('gpslink');
var elem = location.href;
if (elem.indexOf('?') > 0) {
a_elem.href = elem.substring(0, elem.indexOf('?'))
}
a_elem.href = a_elem.href + '?' + params;
});
} else {
document.getElementById("gpslink").style.display = "none";
}
}
*/
function fillTheUrl(params, urlname) {
var a_elem = document.getElementById(urlname);
if (a_elem.href.indexOf('?') > 0) {
a_elem.href = a_elem.href.substring(0, a_elem.href.indexOf('?'))
}
a_elem.href = a_elem.href + '?' + params;
}
function markerButtons(isSetMarker) {
if (isSetMarker) {
document.getElementById("setmarker").style.display = "none";
document.getElementById("removemarker").style.display = "block";
} else {
if (document.getElementById("setmarker").style.display == "none") {
document.getElementById("setmarker").style.display = "block";
document.getElementById("removemarker").style.display = "none";
} else {
document.getElementById("setmarker").style.display = "none";
document.getElementById("removemarker").style.display = "block";
}
}
}
function pageOnLoad() {
initGPS(); // TODO
}
function initMarkerButtons(visibleMarker) {
if (visibleMarker) {
document.getElementById("setmarker").style.display = "none";
document.getElementById("removemarker").style.display = "block";
} else {
document.getElementById("setmarker").style.display = "block";
document.getElementById("removemarker").style.display = "none";
}
}
function resizeMapCanvas(w, h) {
document.getElementById("map_canvas").style.width = w;
document.getElementById("map_canvas").style.height = h;
document.getElementById("div_url").style.width = w;
document.getElementById("map_links").style.width = w;
document.getElementById("marker_links").style.width = w;
}
function initMapCanvasSize() {
var w = getParameter('w');
var h = getParameter('h');
if (w != null || h != null) {
if (w == null)
w = def_w;
if (h == null)
h = def_h;
resizeMapCanvas(w, h);
} else {
resizeMapCanvas(def_w, def_h);
}
}
function viewPort() {
var h = window.innerHeight || document.documentElement.clientHeight
|| document.getElementsByTagName('body')[0].clientHeight;
var w = window.innerWidth || document.documentElement.clientWidth
|| document.getElementsByTagName('body')[0].clientWidth;
return {
width : w,
height : h
}
}
function resizeMapMicro() {
resizeMapCanvas(sizeMicro_w, sizeMicro_h);
resizeMap();
}
function resizeMapA() {
resizeMapCanvas(sizeA_w, sizeA_h);
resizeMap();
}
function resizeMapB() {
resizeMapCanvas(sizeB_w, sizeB_h);
resizeMap();
}
function resizeMapC() {
resizeMapCanvas(sizeC_w, sizeC_h);
resizeMap();
}
function resizeMapMacro() {
resizeMapCanvas(viewPort().width + 'px', viewPort().height + 'px');
resizeMap();
}
function initGPS() {
if (navigator.geolocation) {
navigator.geolocation
.getCurrentPosition(function(position) {
gps_lat = position.coords.latitude;
gps_lng = position.coords.longitude;
});
}
}
| JavaScript |
(function() {
function getScript(src) {
document.write('<' + 'script src="' + src + '"' +
' type="text/javascript"><' + '/script>');
}
getScript("js/moyakarta-0.3.js");
})();
| JavaScript |
var def_lat = 49.44;
var def_lng = 32.06;
var def_zoom = 13;
var panOffset = 100;
var def_w = '640px';
var def_h = '360px';
var size0_w = '320px';
var size0_h = '200px';
var sizeA_w = def_w;
var sizeA_h = def_h;
var sizeB_w = '854px';
var sizeB_h = '480px';
var map;
var marker;
function getParameter(name)
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return null;
else
return results[1];
}
function fillUrlsCommon(maplat, maplng, mapzoom, maptype, markerlat, markerlng) {
var params = 'lat=' + maplat
+ '&lng=' + maplng
+ '&z=' + mapzoom
+ '&t=' + maptype;
if (isMarkerVisible()) {
params += '&mlat=' + markerlat
+ '&mlng=' + markerlng;
}
//if (document.getElementById("map_canvas").style.width != def_w) {
params += '&w=' + document.getElementById("map_canvas").style.width;
params += '&h=' + document.getElementById("map_canvas").style.height;
//}
fillTheUrl(params, 'google-maps');
fillTheUrl(params, 'google-maps-mobile');
fillTheUrl(params, 'yandex-maps');
fillTheUrl(params, 'visicom-maps');
fillTextLinkUrl();
}
function fillTheUrl(params, urlname) {
var a_elem = document.getElementById(urlname);
if (a_elem.href.indexOf('?') > 0) {
a_elem.href = a_elem.href.substring(0, a_elem.href.indexOf('?'))
}
a_elem.href = a_elem.href + '?' + params;
}
function fillTextLinkUrl() {
var a_elem = location.href;
var currentLink = null;
if (a_elem.indexOf('google-maps-mobile') > 0) {
currentLink = document.getElementById('google-maps-mobile').href;
} else if (a_elem.indexOf('google-maps') > 0) {
currentLink = document.getElementById('google-maps').href;
} else if (a_elem.indexOf('yandex-maps') > 0) {
currentLink = document.getElementById('yandex-maps').href;
} else if (a_elem.indexOf('visicom-maps') > 0) {
currentLink = document.getElementById('visicom-maps').href;
} else {
// default
alert('There is no Map Service in the page location.');
return;
}
document.getElementById('textlink').value = currentLink;
document.getElementById('refresh').href = currentLink;
}
function markerButtons() {
if (document.getElementById("setmarker").style.display == "none") {
document.getElementById("setmarker").style.display = "block";
document.getElementById("removemarker").style.display = "none";
} else {
document.getElementById("setmarker").style.display = "none";
document.getElementById("removemarker").style.display = "block";
}
}
function initStyleButtons() {
styleButtons();
}
function styleButtons() {
if (document.getElementById("newstyle").style.display != "none") {
// get new style
document.getElementById("newstyle").style.display = "none";
document.getElementById("oldstyle").style.display = "block";
document.getElementById("map_links").style.display = "block";
document.getElementById("map_links_old").style.display = "none";
} else {
// get old style
document.getElementById("newstyle").style.display = "block";
document.getElementById("oldstyle").style.display = "none";
document.getElementById("map_links").style.display = "none";
document.getElementById("map_links_old").style.display = "block";
}
}
function initMarkerButtons(visibleMarker) {
if (visibleMarker) {
document.getElementById("setmarker").style.display = "none";
document.getElementById("removemarker").style.display = "block";
} else {
document.getElementById("setmarker").style.display = "block";
document.getElementById("removemarker").style.display = "none";
}
}
function resizeMapCanvas(w, h) {
document.getElementById("map_canvas").style.width = w;
document.getElementById("map_canvas").style.height = h;
document.getElementById("div_url").style.width = w;
document.getElementById("map_links").style.width = w;
}
function initMapCanvasSize() {
var w = getParameter('w');
var h = getParameter('h');
if (w != null || h != null) {
if (w == null)
w = def_w;
if (h == null)
h = def_h;
resizeMapCanvas(w, h);
}
}
function viewPort() {
var h = window.innerHeight || document.documentElement.clientHeight || document.getElementsByTagName('body')[0].clientHeight;
var w = window.innerWidth || document.documentElement.clientWidth || document.getElementsByTagName('body')[0].clientWidth;
return { width : w , height : h }
}
function resizeMap0() {
resizeMapCanvas(size0_w, size0_h);
resizeMap();
}
function resizeMapA() {
resizeMapCanvas(sizeA_w, sizeA_h);
resizeMap();
}
function resizeMapB() {
resizeMapCanvas(sizeB_w, sizeB_h);
resizeMap();
}
function resizeMapMax() {
resizeMapCanvas(viewPort().width + 'px', viewPort().height + 'px');
resizeMap();
}
| JavaScript |
(function() {
function getScript(src) {
document.write('<' + 'script src="' + src + '"' +
' type="text/javascript"><' + '/script>');
}
getScript("10100ckua-0.3.js");
})();
| JavaScript |
// send html to the post editor
var wpActiveEditor;
function send_to_editor(h) {
var ed, mce = typeof(tinymce) != 'undefined', qt = typeof(QTags) != 'undefined';
if ( !wpActiveEditor ) {
if ( mce && tinymce.activeEditor ) {
ed = tinymce.activeEditor;
wpActiveEditor = ed.id;
} else if ( !qt ) {
return false;
}
} else if ( mce ) {
if ( tinymce.activeEditor && (tinymce.activeEditor.id == 'mce_fullscreen' || tinymce.activeEditor.id == 'wp_mce_fullscreen') )
ed = tinymce.activeEditor;
else
ed = tinymce.get(wpActiveEditor);
}
if ( ed && !ed.isHidden() ) {
// restore caret position on IE
if ( tinymce.isIE && ed.windowManager.insertimagebookmark )
ed.selection.moveToBookmark(ed.windowManager.insertimagebookmark);
if ( h.indexOf('[caption') === 0 ) {
if ( ed.wpSetImgCaption )
h = ed.wpSetImgCaption(h);
} else if ( h.indexOf('[gallery') === 0 ) {
if ( ed.plugins.wpgallery )
h = ed.plugins.wpgallery._do_gallery(h);
} else if ( h.indexOf('[embed') === 0 ) {
if ( ed.plugins.wordpress )
h = ed.plugins.wordpress._setEmbed(h);
}
ed.execCommand('mceInsertContent', false, h);
} else if ( qt ) {
QTags.insertContent(h);
} else {
document.getElementById(wpActiveEditor).value += h;
}
try{tb_remove();}catch(e){};
}
// thickbox settings
var tb_position;
(function($) {
tb_position = function() {
var tbWindow = $('#TB_window'), width = $(window).width(), H = $(window).height(), W = ( 720 < width ) ? 720 : width, adminbar_height = 0;
if ( $('body.admin-bar').length )
adminbar_height = 28;
if ( tbWindow.size() ) {
tbWindow.width( W - 50 ).height( H - 45 - adminbar_height );
$('#TB_iframeContent').width( W - 50 ).height( H - 75 - adminbar_height );
tbWindow.css({'margin-left': '-' + parseInt((( W - 50 ) / 2),10) + 'px'});
if ( typeof document.body.style.maxWidth != 'undefined' )
tbWindow.css({'top': 20 + adminbar_height + 'px','margin-top':'0'});
};
return $('a.thickbox').each( function() {
var href = $(this).attr('href');
if ( ! href ) return;
href = href.replace(/&width=[0-9]+/g, '');
href = href.replace(/&height=[0-9]+/g, '');
$(this).attr( 'href', href + '&width=' + ( W - 80 ) + '&height=' + ( H - 85 - adminbar_height ) );
});
};
$(window).resize(function(){ tb_position(); });
// store caret position in IE
$(document).ready(function($){
$('a.thickbox').click(function(){
var ed;
if ( typeof(tinymce) != 'undefined' && tinymce.isIE && ( ed = tinymce.get(wpActiveEditor) ) && !ed.isHidden() ) {
ed.focus();
ed.windowManager.insertimagebookmark = ed.selection.getBookmark();
}
});
});
})(jQuery);
| JavaScript |
(function($,undefined) {
wpWordCount = {
settings : {
strip : /<[a-zA-Z\/][^<>]*>/g, // strip HTML tags
clean : /[0-9.(),;:!?%#$¿'"_+=\\/-]+/g, // regexp to remove punctuation, etc.
w : /\S\s+/g, // word-counting regexp
c : /\S/g // char-counting regexp for asian languages
},
block : 0,
wc : function(tx, type) {
var t = this, w = $('.word-count'), tc = 0;
if ( type === undefined )
type = wordCountL10n.type;
if ( type !== 'w' && type !== 'c' )
type = 'w';
if ( t.block )
return;
t.block = 1;
setTimeout( function() {
if ( tx ) {
tx = tx.replace( t.settings.strip, ' ' ).replace( / | /gi, ' ' );
tx = tx.replace( t.settings.clean, '' );
tx.replace( t.settings[type], function(){tc++;} );
}
w.html(tc.toString());
setTimeout( function() { t.block = 0; }, 2000 );
}, 1 );
}
}
$(document).bind( 'wpcountwords', function(e, txt) {
wpWordCount.wc(txt);
});
}(jQuery));
| JavaScript |
jQuery(function($){
$( 'body' ).bind( 'click.wp-gallery', function(e){
var target = $( e.target ), id, img_size;
if ( target.hasClass( 'wp-set-header' ) ) {
( window.dialogArguments || opener || parent || top ).location.href = target.data( 'location' );
e.preventDefault();
} else if ( target.hasClass( 'wp-set-background' ) ) {
id = target.data( 'attachment-id' );
img_size = $( 'input[name="attachments[' + id + '][image-size]"]:checked').val();
jQuery.post(ajaxurl, {
action: 'set-background-image',
attachment_id: id,
size: img_size
}, function(){
var win = window.dialogArguments || opener || parent || top;
win.tb_remove();
win.location.reload();
});
e.preventDefault();
}
});
});
| JavaScript |
(function($) {
inlineEditPost = {
init : function(){
var t = this, qeRow = $('#inline-edit'), bulkRow = $('#bulk-edit');
t.type = $('table.widefat').hasClass('pages') ? 'page' : 'post';
t.what = '#post-';
// prepare the edit rows
qeRow.keyup(function(e){
if (e.which == 27)
return inlineEditPost.revert();
});
bulkRow.keyup(function(e){
if (e.which == 27)
return inlineEditPost.revert();
});
$('a.cancel', qeRow).click(function(){
return inlineEditPost.revert();
});
$('a.save', qeRow).click(function(){
return inlineEditPost.save(this);
});
$('td', qeRow).keydown(function(e){
if ( e.which == 13 )
return inlineEditPost.save(this);
});
$('a.cancel', bulkRow).click(function(){
return inlineEditPost.revert();
});
$('#inline-edit .inline-edit-private input[value="private"]').click( function(){
var pw = $('input.inline-edit-password-input');
if ( $(this).prop('checked') ) {
pw.val('').prop('disabled', true);
} else {
pw.prop('disabled', false);
}
});
// add events
$('a.editinline').live('click', function(){
inlineEditPost.edit(this);
return false;
});
$('#bulk-title-div').parents('fieldset').after(
$('#inline-edit fieldset.inline-edit-categories').clone()
).siblings( 'fieldset:last' ).prepend(
$('#inline-edit label.inline-edit-tags').clone()
);
// hiearchical taxonomies expandable?
$('span.catshow').click(function(){
$(this).hide().next().show().parent().next().addClass("cat-hover");
});
$('span.cathide').click(function(){
$(this).hide().prev().show().parent().next().removeClass("cat-hover");
});
$('select[name="_status"] option[value="future"]', bulkRow).remove();
$('#doaction, #doaction2').click(function(e){
var n = $(this).attr('id').substr(2);
if ( $('select[name="'+n+'"]').val() == 'edit' ) {
e.preventDefault();
t.setBulk();
} else if ( $('form#posts-filter tr.inline-editor').length > 0 ) {
t.revert();
}
});
$('#post-query-submit').mousedown(function(e){
t.revert();
$('select[name^="action"]').val('-1');
});
},
toggle : function(el){
var t = this;
$(t.what+t.getId(el)).css('display') == 'none' ? t.revert() : t.edit(el);
},
setBulk : function(){
var te = '', type = this.type, tax, c = true;
this.revert();
$('#bulk-edit td').attr('colspan', $('.widefat:first thead th:visible').length);
$('table.widefat tbody').prepend( $('#bulk-edit') );
$('#bulk-edit').addClass('inline-editor').show();
$('tbody th.check-column input[type="checkbox"]').each(function(i){
if ( $(this).prop('checked') ) {
c = false;
var id = $(this).val(), theTitle;
theTitle = $('#inline_'+id+' .post_title').text() || inlineEditL10n.notitle;
te += '<div id="ttle'+id+'"><a id="_'+id+'" class="ntdelbutton" title="'+inlineEditL10n.ntdeltitle+'">X</a>'+theTitle+'</div>';
}
});
if ( c )
return this.revert();
$('#bulk-titles').html(te);
$('#bulk-titles a').click(function(){
var id = $(this).attr('id').substr(1);
$('table.widefat input[value="' + id + '"]').prop('checked', false);
$('#ttle'+id).remove();
});
// enable autocomplete for tags
if ( 'post' == type ) {
// support multi taxonomies?
tax = 'post_tag';
$('tr.inline-editor textarea[name="tax_input['+tax+']"]').suggest( ajaxurl + '?action=ajax-tag-search&tax=' + tax, { delay: 500, minchars: 2, multiple: true, multipleSep: inlineEditL10n.comma + ' ' } );
}
$('html, body').animate( { scrollTop: 0 }, 'fast' );
},
edit : function(id) {
var t = this, fields, editRow, rowData, status, pageOpt, pageLevel, nextPage, pageLoop = true, nextLevel, cur_format, f;
t.revert();
if ( typeof(id) == 'object' )
id = t.getId(id);
fields = ['post_title', 'post_name', 'post_author', '_status', 'jj', 'mm', 'aa', 'hh', 'mn', 'ss', 'post_password', 'post_format', 'menu_order'];
if ( t.type == 'page' )
fields.push('post_parent', 'page_template');
// add the new blank row
editRow = $('#inline-edit').clone(true);
$('td', editRow).attr('colspan', $('.widefat:first thead th:visible').length);
if ( $(t.what+id).hasClass('alternate') )
$(editRow).addClass('alternate');
$(t.what+id).hide().after(editRow);
// populate the data
rowData = $('#inline_'+id);
if ( !$(':input[name="post_author"] option[value="' + $('.post_author', rowData).text() + '"]', editRow).val() ) {
// author no longer has edit caps, so we need to add them to the list of authors
$(':input[name="post_author"]', editRow).prepend('<option value="' + $('.post_author', rowData).text() + '">' + $('#' + t.type + '-' + id + ' .author').text() + '</option>');
}
if ( $(':input[name="post_author"] option', editRow).length == 1 ) {
$('label.inline-edit-author', editRow).hide();
}
// hide unsupported formats, but leave the current format alone
cur_format = $('.post_format', rowData).text();
$('option.unsupported', editRow).each(function() {
var $this = $(this);
if ( $this.val() != cur_format )
$this.remove();
});
for ( f = 0; f < fields.length; f++ ) {
$(':input[name="' + fields[f] + '"]', editRow).val( $('.'+fields[f], rowData).text() );
}
if ( $('.comment_status', rowData).text() == 'open' )
$('input[name="comment_status"]', editRow).prop("checked", true);
if ( $('.ping_status', rowData).text() == 'open' )
$('input[name="ping_status"]', editRow).prop("checked", true);
if ( $('.sticky', rowData).text() == 'sticky' )
$('input[name="sticky"]', editRow).prop("checked", true);
// hierarchical taxonomies
$('.post_category', rowData).each(function(){
var term_ids = $(this).text();
if ( term_ids ) {
taxname = $(this).attr('id').replace('_'+id, '');
$('ul.'+taxname+'-checklist :checkbox', editRow).val(term_ids.split(','));
}
});
//flat taxonomies
$('.tags_input', rowData).each(function(){
var terms = $(this).text(),
taxname = $(this).attr('id').replace('_' + id, ''),
textarea = $('textarea.tax_input_' + taxname, editRow),
comma = inlineEditL10n.comma;
if ( terms ) {
if ( ',' !== comma )
terms = terms.replace(/,/g, comma);
textarea.val(terms);
}
textarea.suggest( ajaxurl + '?action=ajax-tag-search&tax=' + taxname, { delay: 500, minchars: 2, multiple: true, multipleSep: inlineEditL10n.comma + ' ' } );
});
// handle the post status
status = $('._status', rowData).text();
if ( 'future' != status )
$('select[name="_status"] option[value="future"]', editRow).remove();
if ( 'private' == status ) {
$('input[name="keep_private"]', editRow).prop("checked", true);
$('input.inline-edit-password-input').val('').prop('disabled', true);
}
// remove the current page and children from the parent dropdown
pageOpt = $('select[name="post_parent"] option[value="' + id + '"]', editRow);
if ( pageOpt.length > 0 ) {
pageLevel = pageOpt[0].className.split('-')[1];
nextPage = pageOpt;
while ( pageLoop ) {
nextPage = nextPage.next('option');
if (nextPage.length == 0) break;
nextLevel = nextPage[0].className.split('-')[1];
if ( nextLevel <= pageLevel ) {
pageLoop = false;
} else {
nextPage.remove();
nextPage = pageOpt;
}
}
pageOpt.remove();
}
$(editRow).attr('id', 'edit-'+id).addClass('inline-editor').show();
$('.ptitle', editRow).focus();
return false;
},
save : function(id) {
var params, fields, page = $('.post_status_page').val() || '';
if ( typeof(id) == 'object' )
id = this.getId(id);
$('table.widefat .inline-edit-save .waiting').show();
params = {
action: 'inline-save',
post_type: typenow,
post_ID: id,
edit_date: 'true',
post_status: page
};
fields = $('#edit-'+id+' :input').serialize();
params = fields + '&' + $.param(params);
// make ajax request
$.post( ajaxurl, params,
function(r) {
$('table.widefat .inline-edit-save .waiting').hide();
if (r) {
if ( -1 != r.indexOf('<tr') ) {
$(inlineEditPost.what+id).remove();
$('#edit-'+id).before(r).remove();
$(inlineEditPost.what+id).hide().fadeIn();
} else {
r = r.replace( /<.[^<>]*?>/g, '' );
$('#edit-'+id+' .inline-edit-save .error').html(r).show();
}
} else {
$('#edit-'+id+' .inline-edit-save .error').html(inlineEditL10n.error).show();
}
}
, 'html');
return false;
},
revert : function(){
var id = $('table.widefat tr.inline-editor').attr('id');
if ( id ) {
$('table.widefat .inline-edit-save .waiting').hide();
if ( 'bulk-edit' == id ) {
$('table.widefat #bulk-edit').removeClass('inline-editor').hide();
$('#bulk-titles').html('');
$('#inlineedit').append( $('#bulk-edit') );
} else {
$('#'+id).remove();
id = id.substr( id.lastIndexOf('-') + 1 );
$(this.what+id).show();
}
}
return false;
},
getId : function(o) {
var id = $(o).closest('tr').attr('id'),
parts = id.split('-');
return parts[parts.length - 1];
}
};
$(document).ready(function(){inlineEditPost.init();});
})(jQuery);
| JavaScript |
(function($) {
inlineEditTax = {
init : function() {
var t = this, row = $('#inline-edit');
t.type = $('#the-list').attr('class').substr(5);
t.what = '#'+t.type+'-';
$('.editinline').live('click', function(){
inlineEditTax.edit(this);
return false;
});
// prepare the edit row
row.keyup(function(e) { if(e.which == 27) return inlineEditTax.revert(); });
$('a.cancel', row).click(function() { return inlineEditTax.revert(); });
$('a.save', row).click(function() { return inlineEditTax.save(this); });
$('input, select', row).keydown(function(e) { if(e.which == 13) return inlineEditTax.save(this); });
$('#posts-filter input[type="submit"]').mousedown(function(e){
t.revert();
});
},
toggle : function(el) {
var t = this;
$(t.what+t.getId(el)).css('display') == 'none' ? t.revert() : t.edit(el);
},
edit : function(id) {
var t = this, editRow;
t.revert();
if ( typeof(id) == 'object' )
id = t.getId(id);
editRow = $('#inline-edit').clone(true), rowData = $('#inline_'+id);
$('td', editRow).attr('colspan', $('.widefat:first thead th:visible').length);
if ( $(t.what+id).hasClass('alternate') )
$(editRow).addClass('alternate');
$(t.what+id).hide().after(editRow);
$(':input[name="name"]', editRow).val( $('.name', rowData).text() );
$(':input[name="slug"]', editRow).val( $('.slug', rowData).text() );
$(editRow).attr('id', 'edit-'+id).addClass('inline-editor').show();
$('.ptitle', editRow).eq(0).focus();
return false;
},
save : function(id) {
var params, fields, tax = $('input[name="taxonomy"]').val() || '';
if( typeof(id) == 'object' )
id = this.getId(id);
$('table.widefat .inline-edit-save .waiting').show();
params = {
action: 'inline-save-tax',
tax_type: this.type,
tax_ID: id,
taxonomy: tax
};
fields = $('#edit-'+id+' :input').serialize();
params = fields + '&' + $.param(params);
// make ajax request
$.post( ajaxurl, params,
function(r) {
var row, new_id;
$('table.widefat .inline-edit-save .waiting').hide();
if (r) {
if ( -1 != r.indexOf('<tr') ) {
$(inlineEditTax.what+id).remove();
new_id = $(r).attr('id');
$('#edit-'+id).before(r).remove();
row = new_id ? $('#'+new_id) : $(inlineEditTax.what+id);
row.hide().fadeIn();
} else
$('#edit-'+id+' .inline-edit-save .error').html(r).show();
} else
$('#edit-'+id+' .inline-edit-save .error').html(inlineEditL10n.error).show();
}
);
return false;
},
revert : function() {
var id = $('table.widefat tr.inline-editor').attr('id');
if ( id ) {
$('table.widefat .inline-edit-save .waiting').hide();
$('#'+id).remove();
id = id.substr( id.lastIndexOf('-') + 1 );
$(this.what+id).show();
}
return false;
},
getId : function(o) {
var id = o.tagName == 'TR' ? o.id : $(o).parents('tr').attr('id'), parts = id.split('-');
return parts[parts.length - 1];
}
};
$(document).ready(function(){inlineEditTax.init();});
})(jQuery);
| JavaScript |
jQuery(document).ready( function($) {
var newCat, noSyncChecks = false, syncChecks, catAddAfter;
$('#link_name').focus();
// postboxes
postboxes.add_postbox_toggles('link');
// category tabs
$('#category-tabs a').click(function(){
var t = $(this).attr('href');
$(this).parent().addClass('tabs').siblings('li').removeClass('tabs');
$('.tabs-panel').hide();
$(t).show();
if ( '#categories-all' == t )
deleteUserSetting('cats');
else
setUserSetting('cats','pop');
return false;
});
if ( getUserSetting('cats') )
$('#category-tabs a[href="#categories-pop"]').click();
// Ajax Cat
newCat = $('#newcat').one( 'focus', function() { $(this).val( '' ).removeClass( 'form-input-tip' ) } );
$('#category-add-submit').click( function() { newCat.focus(); } );
syncChecks = function() {
if ( noSyncChecks )
return;
noSyncChecks = true;
var th = $(this), c = th.is(':checked'), id = th.val().toString();
$('#in-link-category-' + id + ', #in-popular-category-' + id).prop( 'checked', c );
noSyncChecks = false;
};
catAddAfter = function( r, s ) {
$(s.what + ' response_data', r).each( function() {
var t = $($(this).text());
t.find( 'label' ).each( function() {
var th = $(this), val = th.find('input').val(), id = th.find('input')[0].id, name = $.trim( th.text() ), o;
$('#' + id).change( syncChecks );
o = $( '<option value="' + parseInt( val, 10 ) + '"></option>' ).text( name );
} );
} );
};
$('#categorychecklist').wpList( {
alt: '',
what: 'link-category',
response: 'category-ajax-response',
addAfter: catAddAfter
} );
$('a[href="#categories-all"]').click(function(){deleteUserSetting('cats');});
$('a[href="#categories-pop"]').click(function(){setUserSetting('cats','pop');});
if ( 'pop' == getUserSetting('cats') )
$('a[href="#categories-pop"]').click();
$('#category-add-toggle').click( function() {
$(this).parents('div:first').toggleClass( 'wp-hidden-children' );
$('#category-tabs a[href="#categories-all"]').click();
$('#newcategory').focus();
return false;
} );
$('.categorychecklist :checkbox').change( syncChecks ).filter( ':checked' ).change();
});
| JavaScript |
jQuery(document).ready( function($) {
var stamp = $('#timestamp').html();
$('.edit-timestamp').click(function () {
if ($('#timestampdiv').is(":hidden")) {
$('#timestampdiv').slideDown("normal");
$('.edit-timestamp').hide();
}
return false;
});
$('.cancel-timestamp').click(function() {
$('#timestampdiv').slideUp("normal");
$('#mm').val($('#hidden_mm').val());
$('#jj').val($('#hidden_jj').val());
$('#aa').val($('#hidden_aa').val());
$('#hh').val($('#hidden_hh').val());
$('#mn').val($('#hidden_mn').val());
$('#timestamp').html(stamp);
$('.edit-timestamp').show();
return false;
});
$('.save-timestamp').click(function () { // crazyhorse - multiple ok cancels
var aa = $('#aa').val(), mm = $('#mm').val(), jj = $('#jj').val(), hh = $('#hh').val(), mn = $('#mn').val(),
newD = new Date( aa, mm - 1, jj, hh, mn );
if ( newD.getFullYear() != aa || (1 + newD.getMonth()) != mm || newD.getDate() != jj || newD.getMinutes() != mn ) {
$('.timestamp-wrap', '#timestampdiv').addClass('form-invalid');
return false;
} else {
$('.timestamp-wrap', '#timestampdiv').removeClass('form-invalid');
}
$('#timestampdiv').slideUp("normal");
$('.edit-timestamp').show();
$('#timestamp').html(
commentL10n.submittedOn + ' <b>' +
$( '#mm option[value="' + mm + '"]' ).text() + ' ' +
jj + ', ' +
aa + ' @ ' +
hh + ':' +
mn + '</b> '
);
return false;
});
});
| JavaScript |
jQuery(document).ready( function($) {
$('#link_rel').prop('readonly', true);
$('#linkxfndiv input').bind('click keyup', function() {
var isMe = $('#me').is(':checked'), inputs = '';
$('input.valinp').each( function() {
if (isMe) {
$(this).prop('disabled', true).parent().addClass('disabled');
} else {
$(this).removeAttr('disabled').parent().removeClass('disabled');
if ( $(this).is(':checked') && $(this).val() != '')
inputs += $(this).val() + ' ';
}
});
$('#link_rel').val( (isMe) ? 'me' : inputs.substr(0,inputs.length - 1) );
});
});
| JavaScript |
var farbtastic, pickColor;
(function($) {
var defaultColor = '';
pickColor = function(color) {
farbtastic.setColor(color);
$('#background-color').val(color);
$('#custom-background-image').css('background-color', color);
// If we have a default color, and they match, then we need to hide the 'Default' link.
// Otherwise, we hide the 'Clear' link when it is empty.
if ( ( defaultColor && color === defaultColor ) || ( ! defaultColor && ( '' === color || '#' === color ) ) )
$('#clearcolor').hide();
else
$('#clearcolor').show();
}
$(document).ready(function() {
defaultColor = $('#defaultcolor').val();
$('#pickcolor').click(function() {
$('#colorPickerDiv').show();
return false;
});
$('#clearcolor a').click( function(e) {
pickColor( defaultColor );
e.preventDefault();
});
$('#background-color').keyup(function() {
var _hex = $('#background-color').val(), hex = _hex;
if ( hex.charAt(0) != '#' )
hex = '#' + hex;
hex = hex.replace(/[^#a-fA-F0-9]+/, '');
if ( hex != _hex )
$('#background-color').val(hex);
if ( hex.length == 4 || hex.length == 7 )
pickColor( hex );
});
$('input[name="background-position-x"]').change(function() {
$('#custom-background-image').css('background-position', $(this).val() + ' top');
});
$('input[name="background-repeat"]').change(function() {
$('#custom-background-image').css('background-repeat', $(this).val());
});
farbtastic = $.farbtastic('#colorPickerDiv', function(color) {
pickColor(color);
});
pickColor($('#background-color').val());
$(document).mousedown(function(){
$('#colorPickerDiv').each(function(){
var display = $(this).css('display');
if ( display == 'block' )
$(this).fadeOut(2);
});
});
});
})(jQuery); | JavaScript |
(function($) {
var id = 'undefined' !== typeof current_site_id ? '&site_id=' + current_site_id : '';
$(document).ready( function() {
$( '.wp-suggest-user' ).autocomplete({
source: ajaxurl + '?action=autocomplete-user&autocomplete_type=add' + id,
delay: 500,
minLength: 2,
position: ( 'undefined' !== typeof isRtl && isRtl ) ? { my: 'right top', at: 'right bottom', offset: '0, -1' } : { offset: '0, -1' },
open: function() { $(this).addClass('open'); },
close: function() { $(this).removeClass('open'); }
});
});
})(jQuery); | JavaScript |
var showNotice, adminMenu, columns, validateForm, screenMeta;
(function($){
// Removed in 3.3.
// (perhaps) needed for back-compat
adminMenu = {
init : function() {},
fold : function() {},
restoreMenuState : function() {},
toggle : function() {},
favorites : function() {}
};
// show/hide/save table columns
columns = {
init : function() {
var that = this;
$('.hide-column-tog', '#adv-settings').click( function() {
var $t = $(this), column = $t.val();
if ( $t.prop('checked') )
that.checked(column);
else
that.unchecked(column);
columns.saveManageColumnsState();
});
},
saveManageColumnsState : function() {
var hidden = this.hidden();
$.post(ajaxurl, {
action: 'hidden-columns',
hidden: hidden,
screenoptionnonce: $('#screenoptionnonce').val(),
page: pagenow
});
},
checked : function(column) {
$('.column-' + column).show();
this.colSpanChange(+1);
},
unchecked : function(column) {
$('.column-' + column).hide();
this.colSpanChange(-1);
},
hidden : function() {
return $('.manage-column').filter(':hidden').map(function() { return this.id; }).get().join(',');
},
useCheckboxesForHidden : function() {
this.hidden = function(){
return $('.hide-column-tog').not(':checked').map(function() {
var id = this.id;
return id.substring( id, id.length - 5 );
}).get().join(',');
};
},
colSpanChange : function(diff) {
var $t = $('table').find('.colspanchange'), n;
if ( !$t.length )
return;
n = parseInt( $t.attr('colspan'), 10 ) + diff;
$t.attr('colspan', n.toString());
}
}
$(document).ready(function(){columns.init();});
validateForm = function( form ) {
return !$( form ).find('.form-required').filter( function() { return $('input:visible', this).val() == ''; } ).addClass( 'form-invalid' ).find('input:visible').change( function() { $(this).closest('.form-invalid').removeClass( 'form-invalid' ); } ).size();
}
// stub for doing better warnings
showNotice = {
warn : function() {
var msg = commonL10n.warnDelete || '';
if ( confirm(msg) ) {
return true;
}
return false;
},
note : function(text) {
alert(text);
}
};
screenMeta = {
element: null, // #screen-meta
toggles: null, // .screen-meta-toggle
page: null, // #wpcontent
init: function() {
this.element = $('#screen-meta');
this.toggles = $('.screen-meta-toggle a');
this.page = $('#wpcontent');
this.toggles.click( this.toggleEvent );
},
toggleEvent: function( e ) {
var panel = $( this.href.replace(/.+#/, '#') );
e.preventDefault();
if ( !panel.length )
return;
if ( panel.is(':visible') )
screenMeta.close( panel, $(this) );
else
screenMeta.open( panel, $(this) );
},
open: function( panel, link ) {
$('.screen-meta-toggle').not( link.parent() ).css('visibility', 'hidden');
panel.parent().show();
panel.slideDown( 'fast', function() {
link.addClass('screen-meta-active');
});
},
close: function( panel, link ) {
panel.slideUp( 'fast', function() {
link.removeClass('screen-meta-active');
$('.screen-meta-toggle').css('visibility', '');
panel.parent().hide();
});
}
};
/**
* Help tabs.
*/
$('.contextual-help-tabs').delegate('a', 'click focus', function(e) {
var link = $(this),
panel;
e.preventDefault();
// Don't do anything if the click is for the tab already showing.
if ( link.is('.active a') )
return false;
// Links
$('.contextual-help-tabs .active').removeClass('active');
link.parent('li').addClass('active');
panel = $( link.attr('href') );
// Panels
$('.help-tab-content').not( panel ).removeClass('active').hide();
panel.addClass('active').show();
});
$(document).ready( function() {
var lastClicked = false, checks, first, last, checked, menu = $('#adminmenu'),
pageInput = $('input.current-page'), currentPage = pageInput.val(), refresh;
// admin menu
refresh = function(i, el){ // force the browser to refresh the tabbing index
var node = $(el), tab = node.attr('tabindex');
if ( tab )
node.attr('tabindex', '0').attr('tabindex', tab);
};
$('#collapse-menu', menu).click(function(){
var body = $(document.body);
// reset any compensation for submenus near the bottom of the screen
$('#adminmenu div.wp-submenu').css('margin-top', '');
if ( body.hasClass('folded') ) {
body.removeClass('folded');
setUserSetting('mfold', 'o');
} else {
body.addClass('folded');
setUserSetting('mfold', 'f');
}
return false;
});
$('li.wp-has-submenu', menu).hoverIntent({
over: function(e){
var b, h, o, f, m = $(this).find('.wp-submenu'), menutop, wintop, maxtop;
if ( m.is(':visible') )
return;
menutop = $(this).offset().top;
wintop = $(window).scrollTop();
maxtop = menutop - wintop - 30; // max = make the top of the sub almost touch admin bar
b = menutop + m.height() + 1; // Bottom offset of the menu
h = $('#wpwrap').height(); // Height of the entire page
o = 60 + b - h;
f = $(window).height() + wintop - 15; // The fold
if ( f < (b - o) )
o = b - f;
if ( o > maxtop )
o = maxtop;
if ( o > 1 )
m.css('margin-top', '-'+o+'px');
else
m.css('margin-top', '');
menu.find('.wp-submenu').removeClass('sub-open');
m.addClass('sub-open');
},
out: function(){
$(this).find('.wp-submenu').removeClass('sub-open').css('margin-top', '');
},
timeout: 200,
sensitivity: 7,
interval: 90
});
// Tab to select, Enter to open sub, Esc to close sub and focus the top menu
$('li.wp-has-submenu > a.wp-not-current-submenu', menu).bind('keydown.adminmenu', function(e){
if ( e.which != 13 )
return;
var target = $(e.target);
e.stopPropagation();
e.preventDefault();
menu.find('.wp-submenu').removeClass('sub-open');
target.siblings('.wp-submenu').toggleClass('sub-open').find('a[role="menuitem"]').each(refresh);
}).each(refresh);
$('a[role="menuitem"]', menu).bind('keydown.adminmenu', function(e){
if ( e.which != 27 )
return;
var target = $(e.target);
e.stopPropagation();
e.preventDefault();
target.add( target.siblings() ).closest('.sub-open').removeClass('sub-open').siblings('a.wp-not-current-submenu').focus();
});
// Move .updated and .error alert boxes. Don't move boxes designed to be inline.
$('div.wrap h2:first').nextAll('div.updated, div.error').addClass('below-h2');
$('div.updated, div.error').not('.below-h2, .inline').insertAfter( $('div.wrap h2:first') );
// Init screen meta
screenMeta.init();
// check all checkboxes
$('tbody').children().children('.check-column').find(':checkbox').click( function(e) {
if ( 'undefined' == e.shiftKey ) { return true; }
if ( e.shiftKey ) {
if ( !lastClicked ) { return true; }
checks = $( lastClicked ).closest( 'form' ).find( ':checkbox' );
first = checks.index( lastClicked );
last = checks.index( this );
checked = $(this).prop('checked');
if ( 0 < first && 0 < last && first != last ) {
checks.slice( first, last ).prop( 'checked', function(){
if ( $(this).closest('tr').is(':visible') )
return checked;
return false;
});
}
}
lastClicked = this;
return true;
});
$('thead, tfoot').find('.check-column :checkbox').click( function(e) {
var c = $(this).prop('checked'),
kbtoggle = 'undefined' == typeof toggleWithKeyboard ? false : toggleWithKeyboard,
toggle = e.shiftKey || kbtoggle;
$(this).closest( 'table' ).children( 'tbody' ).filter(':visible')
.children().children('.check-column').find(':checkbox')
.prop('checked', function() {
if ( $(this).closest('tr').is(':hidden') )
return false;
if ( toggle )
return $(this).prop( 'checked' );
else if (c)
return true;
return false;
});
$(this).closest('table').children('thead, tfoot').filter(':visible')
.children().children('.check-column').find(':checkbox')
.prop('checked', function() {
if ( toggle )
return false;
else if (c)
return true;
return false;
});
});
$('#default-password-nag-no').click( function() {
setUserSetting('default_password_nag', 'hide');
$('div.default-password-nag').hide();
return false;
});
// tab in textareas
$('#newcontent').bind('keydown.wpevent_InsertTab', function(e) {
if ( e.keyCode != 9 )
return true;
var el = e.target, selStart = el.selectionStart, selEnd = el.selectionEnd, val = el.value, scroll, sel;
try {
this.lastKey = 9; // not a standard DOM property, lastKey is to help stop Opera tab event. See blur handler below.
} catch(err) {}
if ( document.selection ) {
el.focus();
sel = document.selection.createRange();
sel.text = '\t';
} else if ( selStart >= 0 ) {
scroll = this.scrollTop;
el.value = val.substring(0, selStart).concat('\t', val.substring(selEnd) );
el.selectionStart = el.selectionEnd = selStart + 1;
this.scrollTop = scroll;
}
if ( e.stopPropagation )
e.stopPropagation();
if ( e.preventDefault )
e.preventDefault();
});
$('#newcontent').bind('blur.wpevent_InsertTab', function(e) {
if ( this.lastKey && 9 == this.lastKey )
this.focus();
});
if ( pageInput.length ) {
pageInput.closest('form').submit( function(e){
// Reset paging var for new filters/searches but not for bulk actions. See #17685.
if ( $('select[name="action"]').val() == -1 && $('select[name="action2"]').val() == -1 && pageInput.val() == currentPage )
pageInput.val('1');
});
}
});
// internal use
$(document).bind( 'wp_CloseOnEscape', function( e, data ) {
if ( typeof(data.cb) != 'function' )
return;
if ( typeof(data.condition) != 'function' || data.condition() )
data.cb();
return true;
});
})(jQuery);
| JavaScript |
/**
* Theme Browsing
*
* Controls visibility of theme details on manage and install themes pages.
*/
jQuery( function($) {
$('#availablethemes').on( 'click', '.theme-detail', function (event) {
var theme = $(this).closest('.available-theme'),
details = theme.find('.themedetaildiv');
if ( ! details.length ) {
details = theme.find('.install-theme-info .theme-details');
details = details.clone().addClass('themedetaildiv').appendTo( theme ).hide();
}
details.toggle();
event.preventDefault();
});
});
/**
* Theme Install
*
* Displays theme previews on theme install pages.
*/
jQuery( function($) {
if( ! window.postMessage )
return;
var preview = $('#theme-installer'),
info = preview.find('.install-theme-info'),
panel = preview.find('.wp-full-overlay-main'),
body = $( document.body );
preview.on( 'click', '.close-full-overlay', function( event ) {
preview.fadeOut( 200, function() {
panel.empty();
body.removeClass('theme-installer-active full-overlay-active');
});
event.preventDefault();
});
preview.on( 'click', '.collapse-sidebar', function( event ) {
preview.toggleClass( 'collapsed' ).toggleClass( 'expanded' );
event.preventDefault();
});
$('#availablethemes').on( 'click', '.install-theme-preview', function( event ) {
var src;
info.html( $(this).closest('.installable-theme').find('.install-theme-info').html() );
src = info.find( '.theme-preview-url' ).val();
panel.html( '<iframe src="' + src + '" />');
preview.fadeIn( 200, function() {
body.addClass('theme-installer-active full-overlay-active');
});
event.preventDefault();
});
});
var ThemeViewer;
(function($){
ThemeViewer = function( args ) {
function init() {
$( '#filter-click, #mini-filter-click' ).unbind( 'click' ).click( function() {
$( '#filter-click' ).toggleClass( 'current' );
$( '#filter-box' ).slideToggle();
$( '#current-theme' ).slideToggle( 300 );
return false;
});
$( '#filter-box :checkbox' ).unbind( 'click' ).click( function() {
var count = $( '#filter-box :checked' ).length,
text = $( '#filter-click' ).text();
if ( text.indexOf( '(' ) != -1 )
text = text.substr( 0, text.indexOf( '(' ) );
if ( count == 0 )
$( '#filter-click' ).text( text );
else
$( '#filter-click' ).text( text + ' (' + count + ')' );
});
/* $('#filter-box :submit').unbind( 'click' ).click(function() {
var features = [];
$('#filter-box :checked').each(function() {
features.push($(this).val());
});
listTable.update_rows({'features': features}, true, function() {
$( '#filter-click' ).toggleClass( 'current' );
$( '#filter-box' ).slideToggle();
$( '#current-theme' ).slideToggle( 300 );
});
return false;
}); */
}
// These are the functions we expose
var api = {
init: init
};
return api;
}
})(jQuery);
jQuery( document ).ready( function($) {
theme_viewer = new ThemeViewer();
theme_viewer.init();
});
/**
* Class that provides infinite scroll for Themes admin screens
*
* @since 3.4
*
* @uses ajaxurl
* @uses list_args
* @uses theme_list_args
* @uses $('#_ajax_fetch_list_nonce').val()
* */
var ThemeScroller;
(function($){
ThemeScroller = {
querying: false,
scrollPollingDelay: 500,
failedRetryDelay: 4000,
outListBottomThreshold: 300,
/**
* Initializer
*
* @since 3.4
* @access private
*/
init: function() {
var self = this;
// Get out early if we don't have the required arguments.
if ( typeof ajaxurl === 'undefined' ||
typeof list_args === 'undefined' ||
typeof theme_list_args === 'undefined' ) {
$('.pagination-links').show();
return;
}
// Handle inputs
this.nonce = $('#_ajax_fetch_list_nonce').val();
this.nextPage = ( theme_list_args.paged + 1 );
// Cache jQuery selectors
this.$outList = $('#availablethemes');
this.$spinner = $('div.tablenav.bottom').children( 'img.ajax-loading' );
this.$window = $(window);
this.$document = $(document);
/**
* If there are more pages to query, then start polling to track
* when user hits the bottom of the current page
*/
if ( theme_list_args.total_pages >= this.nextPage )
this.pollInterval =
setInterval( function() {
return self.poll();
}, this.scrollPollingDelay );
},
/**
* Checks to see if user has scrolled to bottom of page.
* If so, requests another page of content from self.ajax().
*
* @since 3.4
* @access private
*/
poll: function() {
var bottom = this.$document.scrollTop() + this.$window.innerHeight();
if ( this.querying ||
( bottom < this.$outList.height() - this.outListBottomThreshold ) )
return;
this.ajax();
},
/**
* Applies results passed from this.ajax() to $outList
*
* @since 3.4
* @access private
*
* @param results Array with results from this.ajax() query.
*/
process: function( results ) {
if ( results === undefined ) {
clearInterval( this.pollInterval );
return;
}
if ( this.nextPage > theme_list_args.total_pages )
clearInterval( this.pollInterval );
if ( this.nextPage <= ( theme_list_args.total_pages + 1 ) )
this.$outList.append( results.rows );
},
/**
* Queries next page of themes
*
* @since 3.4
* @access private
*/
ajax: function() {
var self = this;
this.querying = true;
var query = {
action: 'fetch-list',
paged: this.nextPage,
s: theme_list_args.search,
tab: theme_list_args.tab,
type: theme_list_args.type,
_ajax_fetch_list_nonce: this.nonce,
'features[]': theme_list_args.features,
'list_args': list_args
};
this.$spinner.css( 'visibility', 'visible' );
$.getJSON( ajaxurl, query )
.done( function( response ) {
self.nextPage++;
self.process( response );
self.$spinner.css( 'visibility', 'hidden' );
self.querying = false;
})
.fail( function() {
self.$spinner.css( 'visibility', 'hidden' );
self.querying = false;
setTimeout( function() { self.ajax(); }, self.failedRetryDelay );
});
}
}
$(document).ready( function($) {
ThemeScroller.init();
});
})(jQuery);
| JavaScript |
jQuery(document).ready(function($) {
$('.delete-tag').live('click', function(e){
var t = $(this), tr = t.parents('tr'), r = true, data;
if ( 'undefined' != showNotice )
r = showNotice.warn();
if ( r ) {
data = t.attr('href').replace(/[^?]*\?/, '').replace(/action=delete/, 'action=delete-tag');
$.post(ajaxurl, data, function(r){
if ( '1' == r ) {
$('#ajax-response').empty();
tr.fadeOut('normal', function(){ tr.remove(); });
// Remove the term from the parent box and tag cloud
$('select#parent option[value="' + data.match(/tag_ID=(\d+)/)[1] + '"]').remove();
$('a.tag-link-' + data.match(/tag_ID=(\d+)/)[1]).remove();
} else if ( '-1' == r ) {
$('#ajax-response').empty().append('<div class="error"><p>' + tagsl10n.noPerm + '</p></div>');
tr.children().css('backgroundColor', '');
} else {
$('#ajax-response').empty().append('<div class="error"><p>' + tagsl10n.broken + '</p></div>');
tr.children().css('backgroundColor', '');
}
});
tr.children().css('backgroundColor', '#f33');
}
return false;
});
$('#submit').click(function(){
var form = $(this).parents('form');
if ( !validateForm( form ) )
return false;
$.post(ajaxurl, $('#addtag').serialize(), function(r){
$('#ajax-response').empty();
var res = wpAjax.parseAjaxResponse(r, 'ajax-response');
if ( ! res || res.errors )
return;
var parent = form.find('select#parent').val();
if ( parent > 0 && $('#tag-' + parent ).length > 0 ) // If the parent exists on this page, insert it below. Else insert it at the top of the list.
$('.tags #tag-' + parent).after( res.responses[0].supplemental['noparents'] ); // As the parent exists, Insert the version with - - - prefixed
else
$('.tags').prepend( res.responses[0].supplemental['parents'] ); // As the parent is not visible, Insert the version with Parent - Child - ThisTerm
$('.tags .no-items').remove();
if ( form.find('select#parent') ) {
// Parents field exists, Add new term to the list.
var term = res.responses[1].supplemental;
// Create an indent for the Parent field
var indent = '';
for ( var i = 0; i < res.responses[1].position; i++ )
indent += ' ';
form.find('select#parent option:selected').after('<option value="' + term['term_id'] + '">' + indent + term['name'] + '</option>');
}
$('input[type="text"]:visible, textarea:visible', form).val('');
});
return false;
});
});
| JavaScript |
var switchEditors = {
switchto: function(el) {
var aid = el.id, l = aid.length, id = aid.substr(0, l - 5), mode = aid.substr(l - 4);
this.go(id, mode);
},
go: function(id, mode) { // mode can be 'html', 'tmce', or 'toggle'
id = id || 'content';
mode = mode || 'toggle';
var t = this, ed = tinyMCE.get(id), wrap_id, txtarea_el, dom = tinymce.DOM;
wrap_id = 'wp-'+id+'-wrap';
txtarea_el = dom.get(id);
if ( 'toggle' == mode ) {
if ( ed && !ed.isHidden() )
mode = 'html';
else
mode = 'tmce';
}
if ( 'tmce' == mode || 'tinymce' == mode ) {
if ( ed && ! ed.isHidden() )
return false;
if ( typeof(QTags) != 'undefined' )
QTags.closeAllTags(id);
if ( tinyMCEPreInit.mceInit[id] && tinyMCEPreInit.mceInit[id].wpautop )
txtarea_el.value = t.wpautop( txtarea_el.value );
if ( ed ) {
ed.show();
} else {
ed = new tinymce.Editor(id, tinyMCEPreInit.mceInit[id]);
ed.render();
}
dom.removeClass(wrap_id, 'html-active');
dom.addClass(wrap_id, 'tmce-active');
setUserSetting('editor', 'tinymce');
} else if ( 'html' == mode ) {
if ( ed && ed.isHidden() )
return false;
if ( ed ) {
txtarea_el.style.height = ed.getContentAreaContainer().offsetHeight + 20 + 'px';
ed.hide();
}
dom.removeClass(wrap_id, 'tmce-active');
dom.addClass(wrap_id, 'html-active');
setUserSetting('editor', 'html');
}
return false;
},
_wp_Nop : function(content) {
var blocklist1, blocklist2, preserve_linebreaks = false, preserve_br = false;
// Protect pre|script tags
if ( content.indexOf('<pre') != -1 || content.indexOf('<script') != -1 ) {
preserve_linebreaks = true;
content = content.replace(/<(pre|script)[^>]*>[\s\S]+?<\/\1>/g, function(a) {
a = a.replace(/<br ?\/?>(\r\n|\n)?/g, '<wp-temp-lb>');
return a.replace(/<\/?p( [^>]*)?>(\r\n|\n)?/g, '<wp-temp-lb>');
});
}
// keep <br> tags inside captions and remove line breaks
if ( content.indexOf('[caption') != -1 ) {
preserve_br = true;
content = content.replace(/\[caption[\s\S]+?\[\/caption\]/g, function(a) {
return a.replace(/<br([^>]*)>/g, '<wp-temp-br$1>').replace(/[\r\n\t]+/, '');
});
}
// Pretty it up for the source editor
blocklist1 = 'blockquote|ul|ol|li|table|thead|tbody|tfoot|tr|th|td|div|h[1-6]|p|fieldset';
content = content.replace(new RegExp('\\s*</('+blocklist1+')>\\s*', 'g'), '</$1>\n');
content = content.replace(new RegExp('\\s*<((?:'+blocklist1+')(?: [^>]*)?)>', 'g'), '\n<$1>');
// Mark </p> if it has any attributes.
content = content.replace(/(<p [^>]+>.*?)<\/p>/g, '$1</p#>');
// Sepatate <div> containing <p>
content = content.replace(/<div( [^>]*)?>\s*<p>/gi, '<div$1>\n\n');
// Remove <p> and <br />
content = content.replace(/\s*<p>/gi, '');
content = content.replace(/\s*<\/p>\s*/gi, '\n\n');
content = content.replace(/\n[\s\u00a0]+\n/g, '\n\n');
content = content.replace(/\s*<br ?\/?>\s*/gi, '\n');
// Fix some block element newline issues
content = content.replace(/\s*<div/g, '\n<div');
content = content.replace(/<\/div>\s*/g, '</div>\n');
content = content.replace(/\s*\[caption([^\[]+)\[\/caption\]\s*/gi, '\n\n[caption$1[/caption]\n\n');
content = content.replace(/caption\]\n\n+\[caption/g, 'caption]\n\n[caption');
blocklist2 = 'blockquote|ul|ol|li|table|thead|tbody|tfoot|tr|th|td|h[1-6]|pre|fieldset';
content = content.replace(new RegExp('\\s*<((?:'+blocklist2+')(?: [^>]*)?)\\s*>', 'g'), '\n<$1>');
content = content.replace(new RegExp('\\s*</('+blocklist2+')>\\s*', 'g'), '</$1>\n');
content = content.replace(/<li([^>]*)>/g, '\t<li$1>');
if ( content.indexOf('<hr') != -1 ) {
content = content.replace(/\s*<hr( [^>]*)?>\s*/g, '\n\n<hr$1>\n\n');
}
if ( content.indexOf('<object') != -1 ) {
content = content.replace(/<object[\s\S]+?<\/object>/g, function(a){
return a.replace(/[\r\n]+/g, '');
});
}
// Unmark special paragraph closing tags
content = content.replace(/<\/p#>/g, '</p>\n');
content = content.replace(/\s*(<p [^>]+>[\s\S]*?<\/p>)/g, '\n$1');
// Trim whitespace
content = content.replace(/^\s+/, '');
content = content.replace(/[\s\u00a0]+$/, '');
// put back the line breaks in pre|script
if ( preserve_linebreaks )
content = content.replace(/<wp-temp-lb>/g, '\n');
// and the <br> tags in captions
if ( preserve_br )
content = content.replace(/<wp-temp-br([^>]*)>/g, '<br$1>');
return content;
},
_wp_Autop : function(pee) {
var preserve_linebreaks = false, preserve_br = false,
blocklist = 'table|thead|tfoot|tbody|tr|td|th|caption|col|colgroup|div|dl|dd|dt|ul|ol|li|pre|select|form|blockquote|address|math|p|h[1-6]|fieldset|legend|hr|noscript|menu|samp|header|footer|article|section|hgroup|nav|aside|details|summary';
if ( pee.indexOf('<object') != -1 ) {
pee = pee.replace(/<object[\s\S]+?<\/object>/g, function(a){
return a.replace(/[\r\n]+/g, '');
});
}
pee = pee.replace(/<[^<>]+>/g, function(a){
return a.replace(/[\r\n]+/g, ' ');
});
// Protect pre|script tags
if ( pee.indexOf('<pre') != -1 || pee.indexOf('<script') != -1 ) {
preserve_linebreaks = true;
pee = pee.replace(/<(pre|script)[^>]*>[\s\S]+?<\/\1>/g, function(a) {
return a.replace(/(\r\n|\n)/g, '<wp-temp-lb>');
});
}
// keep <br> tags inside captions and convert line breaks
if ( pee.indexOf('[caption') != -1 ) {
preserve_br = true;
pee = pee.replace(/\[caption[\s\S]+?\[\/caption\]/g, function(a) {
// keep existing <br>
a = a.replace(/<br([^>]*)>/g, '<wp-temp-br$1>');
// no line breaks inside HTML tags
a = a.replace(/<[a-zA-Z0-9]+( [^<>]+)?>/g, function(b){
return b.replace(/[\r\n\t]+/, ' ');
});
// convert remaining line breaks to <br>
return a.replace(/\s*\n\s*/g, '<wp-temp-br />');
});
}
pee = pee + '\n\n';
pee = pee.replace(/<br \/>\s*<br \/>/gi, '\n\n');
pee = pee.replace(new RegExp('(<(?:'+blocklist+')(?: [^>]*)?>)', 'gi'), '\n$1');
pee = pee.replace(new RegExp('(</(?:'+blocklist+')>)', 'gi'), '$1\n\n');
pee = pee.replace(/<hr( [^>]*)?>/gi, '<hr$1>\n\n'); // hr is self closing block element
pee = pee.replace(/\r\n|\r/g, '\n');
pee = pee.replace(/\n\s*\n+/g, '\n\n');
pee = pee.replace(/([\s\S]+?)\n\n/g, '<p>$1</p>\n');
pee = pee.replace(/<p>\s*?<\/p>/gi, '');
pee = pee.replace(new RegExp('<p>\\s*(</?(?:'+blocklist+')(?: [^>]*)?>)\\s*</p>', 'gi'), "$1");
pee = pee.replace(/<p>(<li.+?)<\/p>/gi, '$1');
pee = pee.replace(/<p>\s*<blockquote([^>]*)>/gi, '<blockquote$1><p>');
pee = pee.replace(/<\/blockquote>\s*<\/p>/gi, '</p></blockquote>');
pee = pee.replace(new RegExp('<p>\\s*(</?(?:'+blocklist+')(?: [^>]*)?>)', 'gi'), "$1");
pee = pee.replace(new RegExp('(</?(?:'+blocklist+')(?: [^>]*)?>)\\s*</p>', 'gi'), "$1");
pee = pee.replace(/\s*\n/gi, '<br />\n');
pee = pee.replace(new RegExp('(</?(?:'+blocklist+')[^>]*>)\\s*<br />', 'gi'), "$1");
pee = pee.replace(/<br \/>(\s*<\/?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)>)/gi, '$1');
pee = pee.replace(/(?:<p>|<br ?\/?>)*\s*\[caption([^\[]+)\[\/caption\]\s*(?:<\/p>|<br ?\/?>)*/gi, '[caption$1[/caption]');
pee = pee.replace(/(<(?:div|th|td|form|fieldset|dd)[^>]*>)(.*?)<\/p>/g, function(a, b, c) {
if ( c.match(/<p( [^>]*)?>/) )
return a;
return b + '<p>' + c + '</p>';
});
// put back the line breaks in pre|script
if ( preserve_linebreaks )
pee = pee.replace(/<wp-temp-lb>/g, '\n');
if ( preserve_br )
pee = pee.replace(/<wp-temp-br([^>]*)>/g, '<br$1>');
return pee;
},
pre_wpautop : function(content) {
var t = this, o = { o: t, data: content, unfiltered: content },
q = typeof(jQuery) != 'undefined';
if ( q )
jQuery('body').trigger('beforePreWpautop', [o]);
o.data = t._wp_Nop(o.data);
if ( q )
jQuery('body').trigger('afterPreWpautop', [o]);
return o.data;
},
wpautop : function(pee) {
var t = this, o = { o: t, data: pee, unfiltered: pee },
q = typeof(jQuery) != 'undefined';
if ( q )
jQuery('body').trigger('beforeWpautop', [o]);
o.data = t._wp_Autop(o.data);
if ( q )
jQuery('body').trigger('afterWpautop', [o]);
return o.data;
}
}
| JavaScript |
jQuery(document).ready(function($) {
var gallerySortable, gallerySortableInit, w, desc = false;
gallerySortableInit = function() {
gallerySortable = $('#media-items').sortable( {
items: 'div.media-item',
placeholder: 'sorthelper',
axis: 'y',
distance: 2,
handle: 'div.filename',
stop: function(e, ui) {
// When an update has occurred, adjust the order for each item
var all = $('#media-items').sortable('toArray'), len = all.length;
$.each(all, function(i, id) {
var order = desc ? (len - i) : (1 + i);
$('#' + id + ' .menu_order input').val(order);
});
}
} );
}
sortIt = function() {
var all = $('.menu_order_input'), len = all.length;
all.each(function(i){
var order = desc ? (len - i) : (1 + i);
$(this).val(order);
});
}
clearAll = function(c) {
c = c || 0;
$('.menu_order_input').each(function(){
if ( this.value == '0' || c ) this.value = '';
});
}
$('#asc').click(function(){desc = false; sortIt(); return false;});
$('#desc').click(function(){desc = true; sortIt(); return false;});
$('#clear').click(function(){clearAll(1); return false;});
$('#showall').click(function(){
$('#sort-buttons span a').toggle();
$('a.describe-toggle-on').hide();
$('a.describe-toggle-off, table.slidetoggle').show();
$('img.pinkynail').toggle(false);
return false;
});
$('#hideall').click(function(){
$('#sort-buttons span a').toggle();
$('a.describe-toggle-on').show();
$('a.describe-toggle-off, table.slidetoggle').hide();
$('img.pinkynail').toggle(true);
return false;
});
// initialize sortable
gallerySortableInit();
clearAll();
if ( $('#media-items>*').length > 1 ) {
w = wpgallery.getWin();
$('#save-all, #gallery-settings').show();
if ( typeof w.tinyMCE != 'undefined' && w.tinyMCE.activeEditor && ! w.tinyMCE.activeEditor.isHidden() ) {
wpgallery.mcemode = true;
wpgallery.init();
} else {
$('#insert-gallery').show();
}
}
});
jQuery(window).unload( function () { tinymce = tinyMCE = wpgallery = null; } ); // Cleanup
/* gallery settings */
var tinymce = null, tinyMCE, wpgallery;
wpgallery = {
mcemode : false,
editor : {},
dom : {},
is_update : false,
el : {},
I : function(e) {
return document.getElementById(e);
},
init: function() {
var t = this, li, q, i, it, w = t.getWin();
if ( ! t.mcemode ) return;
li = ('' + document.location.search).replace(/^\?/, '').split('&');
q = {};
for (i=0; i<li.length; i++) {
it = li[i].split('=');
q[unescape(it[0])] = unescape(it[1]);
}
if (q.mce_rdomain)
document.domain = q.mce_rdomain;
// Find window & API
tinymce = w.tinymce;
tinyMCE = w.tinyMCE;
t.editor = tinymce.EditorManager.activeEditor;
t.setup();
},
getWin : function() {
return window.dialogArguments || opener || parent || top;
},
setup : function() {
var t = this, a, ed = t.editor, g, columns, link, order, orderby;
if ( ! t.mcemode ) return;
t.el = ed.selection.getNode();
if ( t.el.nodeName != 'IMG' || ! ed.dom.hasClass(t.el, 'wpGallery') ) {
if ( (g = ed.dom.select('img.wpGallery')) && g[0] ) {
t.el = g[0];
} else {
if ( getUserSetting('galfile') == '1' ) t.I('linkto-file').checked = "checked";
if ( getUserSetting('galdesc') == '1' ) t.I('order-desc').checked = "checked";
if ( getUserSetting('galcols') ) t.I('columns').value = getUserSetting('galcols');
if ( getUserSetting('galord') ) t.I('orderby').value = getUserSetting('galord');
jQuery('#insert-gallery').show();
return;
}
}
a = ed.dom.getAttrib(t.el, 'title');
a = ed.dom.decode(a);
if ( a ) {
jQuery('#update-gallery').show();
t.is_update = true;
columns = a.match(/columns=['"]([0-9]+)['"]/);
link = a.match(/link=['"]([^'"]+)['"]/i);
order = a.match(/order=['"]([^'"]+)['"]/i);
orderby = a.match(/orderby=['"]([^'"]+)['"]/i);
if ( link && link[1] ) t.I('linkto-file').checked = "checked";
if ( order && order[1] ) t.I('order-desc').checked = "checked";
if ( columns && columns[1] ) t.I('columns').value = ''+columns[1];
if ( orderby && orderby[1] ) t.I('orderby').value = orderby[1];
} else {
jQuery('#insert-gallery').show();
}
},
update : function() {
var t = this, ed = t.editor, all = '', s;
if ( ! t.mcemode || ! t.is_update ) {
s = '[gallery'+t.getSettings()+']';
t.getWin().send_to_editor(s);
return;
}
if (t.el.nodeName != 'IMG') return;
all = ed.dom.decode(ed.dom.getAttrib(t.el, 'title'));
all = all.replace(/\s*(order|link|columns|orderby)=['"]([^'"]+)['"]/gi, '');
all += t.getSettings();
ed.dom.setAttrib(t.el, 'title', all);
t.getWin().tb_remove();
},
getSettings : function() {
var I = this.I, s = '';
if ( I('linkto-file').checked ) {
s += ' link="file"';
setUserSetting('galfile', '1');
}
if ( I('order-desc').checked ) {
s += ' order="DESC"';
setUserSetting('galdesc', '1');
}
if ( I('columns').value != 3 ) {
s += ' columns="'+I('columns').value+'"';
setUserSetting('galcols', I('columns').value);
}
if ( I('orderby').value != 'menu_order' ) {
s += ' orderby="'+I('orderby').value+'"';
setUserSetting('galord', I('orderby').value);
}
return s;
}
};
| JavaScript |
jQuery(document).ready(function($) {
var options = false, addAfter, delBefore, delAfter;
if ( document.forms['addcat'].category_parent )
options = document.forms['addcat'].category_parent.options;
addAfter = function( r, settings ) {
var name, id;
name = $("<span>" + $('name', r).text() + "</span>").text();
id = $('cat', r).attr('id');
options[options.length] = new Option(name, id);
}
delAfter = function( r, settings ) {
var id = $('cat', r).attr('id'), o;
for ( o = 0; o < options.length; o++ )
if ( id == options[o].value )
options[o] = null;
}
delBefore = function(s) {
if ( 'undefined' != showNotice )
return showNotice.warn() ? s : false;
return s;
}
if ( options )
$('#the-list').wpList( { addAfter: addAfter, delBefore: delBefore, delAfter: delAfter } );
else
$('#the-list').wpList({ delBefore: delBefore });
$('.delete a[class^="delete"]').live('click', function(){return false;});
});
| JavaScript |
/*!
* Farbtastic: jQuery color picker plug-in v1.3u
*
* Licensed under the GPL license:
* http://www.gnu.org/licenses/gpl.html
*/
(function($) {
$.fn.farbtastic = function (options) {
$.farbtastic(this, options);
return this;
};
$.farbtastic = function (container, callback) {
var container = $(container).get(0);
return container.farbtastic || (container.farbtastic = new $._farbtastic(container, callback));
};
$._farbtastic = function (container, callback) {
// Store farbtastic object
var fb = this;
// Insert markup
$(container).html('<div class="farbtastic"><div class="color"></div><div class="wheel"></div><div class="overlay"></div><div class="h-marker marker"></div><div class="sl-marker marker"></div></div>');
var e = $('.farbtastic', container);
fb.wheel = $('.wheel', container).get(0);
// Dimensions
fb.radius = 84;
fb.square = 100;
fb.width = 194;
// Fix background PNGs in IE6
if (navigator.appVersion.match(/MSIE [0-6]\./)) {
$('*', e).each(function () {
if (this.currentStyle.backgroundImage != 'none') {
var image = this.currentStyle.backgroundImage;
image = this.currentStyle.backgroundImage.substring(5, image.length - 2);
$(this).css({
'backgroundImage': 'none',
'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='" + image + "')"
});
}
});
}
/**
* Link to the given element(s) or callback.
*/
fb.linkTo = function (callback) {
// Unbind previous nodes
if (typeof fb.callback == 'object') {
$(fb.callback).unbind('keyup', fb.updateValue);
}
// Reset color
fb.color = null;
// Bind callback or elements
if (typeof callback == 'function') {
fb.callback = callback;
}
else if (typeof callback == 'object' || typeof callback == 'string') {
fb.callback = $(callback);
fb.callback.bind('keyup', fb.updateValue);
if (fb.callback.get(0).value) {
fb.setColor(fb.callback.get(0).value);
}
}
return this;
};
fb.updateValue = function (event) {
if (this.value && this.value != fb.color) {
fb.setColor(this.value);
}
};
/**
* Change color with HTML syntax #123456
*/
fb.setColor = function (color) {
var unpack = fb.unpack(color);
if (fb.color != color && unpack) {
fb.color = color;
fb.rgb = unpack;
fb.hsl = fb.RGBToHSL(fb.rgb);
fb.updateDisplay();
}
return this;
};
/**
* Change color with HSL triplet [0..1, 0..1, 0..1]
*/
fb.setHSL = function (hsl) {
fb.hsl = hsl;
fb.rgb = fb.HSLToRGB(hsl);
fb.color = fb.pack(fb.rgb);
fb.updateDisplay();
return this;
};
/////////////////////////////////////////////////////
/**
* Retrieve the coordinates of the given event relative to the center
* of the widget.
*/
fb.widgetCoords = function (event) {
var offset = $(fb.wheel).offset();
return { x: (event.pageX - offset.left) - fb.width / 2, y: (event.pageY - offset.top) - fb.width / 2 };
};
/**
* Mousedown handler
*/
fb.mousedown = function (event) {
// Capture mouse
if (!document.dragging) {
$(document).bind('mousemove', fb.mousemove).bind('mouseup', fb.mouseup);
document.dragging = true;
}
// Check which area is being dragged
var pos = fb.widgetCoords(event);
fb.circleDrag = Math.max(Math.abs(pos.x), Math.abs(pos.y)) * 2 > fb.square;
// Process
fb.mousemove(event);
return false;
};
/**
* Mousemove handler
*/
fb.mousemove = function (event) {
// Get coordinates relative to color picker center
var pos = fb.widgetCoords(event);
// Set new HSL parameters
if (fb.circleDrag) {
var hue = Math.atan2(pos.x, -pos.y) / 6.28;
if (hue < 0) hue += 1;
fb.setHSL([hue, fb.hsl[1], fb.hsl[2]]);
}
else {
var sat = Math.max(0, Math.min(1, -(pos.x / fb.square) + .5));
var lum = Math.max(0, Math.min(1, -(pos.y / fb.square) + .5));
fb.setHSL([fb.hsl[0], sat, lum]);
}
return false;
};
/**
* Mouseup handler
*/
fb.mouseup = function () {
// Uncapture mouse
$(document).unbind('mousemove', fb.mousemove);
$(document).unbind('mouseup', fb.mouseup);
document.dragging = false;
};
/**
* Update the markers and styles
*/
fb.updateDisplay = function () {
// Markers
var angle = fb.hsl[0] * 6.28;
$('.h-marker', e).css({
left: Math.round(Math.sin(angle) * fb.radius + fb.width / 2) + 'px',
top: Math.round(-Math.cos(angle) * fb.radius + fb.width / 2) + 'px'
});
$('.sl-marker', e).css({
left: Math.round(fb.square * (.5 - fb.hsl[1]) + fb.width / 2) + 'px',
top: Math.round(fb.square * (.5 - fb.hsl[2]) + fb.width / 2) + 'px'
});
// Saturation/Luminance gradient
$('.color', e).css('backgroundColor', fb.pack(fb.HSLToRGB([fb.hsl[0], 1, 0.5])));
// Linked elements or callback
if (typeof fb.callback == 'object') {
// Set background/foreground color
$(fb.callback).css({
backgroundColor: fb.color,
color: fb.hsl[2] > 0.5 ? '#000' : '#fff'
});
// Change linked value
$(fb.callback).each(function() {
if (this.value && this.value != fb.color) {
this.value = fb.color;
}
});
}
else if (typeof fb.callback == 'function') {
fb.callback.call(fb, fb.color);
}
};
/* Various color utility functions */
fb.pack = function (rgb) {
var r = Math.round(rgb[0] * 255);
var g = Math.round(rgb[1] * 255);
var b = Math.round(rgb[2] * 255);
return '#' + (r < 16 ? '0' : '') + r.toString(16) +
(g < 16 ? '0' : '') + g.toString(16) +
(b < 16 ? '0' : '') + b.toString(16);
};
fb.unpack = function (color) {
if (color.length == 7) {
return [parseInt('0x' + color.substring(1, 3)) / 255,
parseInt('0x' + color.substring(3, 5)) / 255,
parseInt('0x' + color.substring(5, 7)) / 255];
}
else if (color.length == 4) {
return [parseInt('0x' + color.substring(1, 2)) / 15,
parseInt('0x' + color.substring(2, 3)) / 15,
parseInt('0x' + color.substring(3, 4)) / 15];
}
};
fb.HSLToRGB = function (hsl) {
var m1, m2, r, g, b;
var h = hsl[0], s = hsl[1], l = hsl[2];
m2 = (l <= 0.5) ? l * (s + 1) : l + s - l*s;
m1 = l * 2 - m2;
return [this.hueToRGB(m1, m2, h+0.33333),
this.hueToRGB(m1, m2, h),
this.hueToRGB(m1, m2, h-0.33333)];
};
fb.hueToRGB = function (m1, m2, h) {
h = (h < 0) ? h + 1 : ((h > 1) ? h - 1 : h);
if (h * 6 < 1) return m1 + (m2 - m1) * h * 6;
if (h * 2 < 1) return m2;
if (h * 3 < 2) return m1 + (m2 - m1) * (0.66666 - h) * 6;
return m1;
};
fb.RGBToHSL = function (rgb) {
var min, max, delta, h, s, l;
var r = rgb[0], g = rgb[1], b = rgb[2];
min = Math.min(r, Math.min(g, b));
max = Math.max(r, Math.max(g, b));
delta = max - min;
l = (min + max) / 2;
s = 0;
if (l > 0 && l < 1) {
s = delta / (l < 0.5 ? (2 * l) : (2 - 2 * l));
}
h = 0;
if (delta > 0) {
if (max == r && max != g) h += (g - b) / delta;
if (max == g && max != b) h += (2 + (b - r) / delta);
if (max == b && max != r) h += (4 + (r - g) / delta);
h /= 6;
}
return [h, s, l];
};
// Install mousedown handler (the others are set on the document on-demand)
$('*', e).mousedown(fb.mousedown);
// Init color
fb.setColor('#000000');
// Set linked elements/callback
if (callback) {
fb.linkTo(callback);
}
};
})(jQuery); | JavaScript |
var tagBox, commentsBox, editPermalink, makeSlugeditClickable, WPSetThumbnailHTML, WPSetThumbnailID, WPRemoveThumbnail, wptitlehint;
// return an array with any duplicate, whitespace or values removed
function array_unique_noempty(a) {
var out = [];
jQuery.each( a, function(key, val) {
val = jQuery.trim(val);
if ( val && jQuery.inArray(val, out) == -1 )
out.push(val);
} );
return out;
}
(function($){
tagBox = {
clean : function(tags) {
var comma = postL10n.comma;
if ( ',' !== comma )
tags = tags.replace(new RegExp(comma, 'g'), ',');
tags = tags.replace(/\s*,\s*/g, ',').replace(/,+/g, ',').replace(/[,\s]+$/, '').replace(/^[,\s]+/, '');
if ( ',' !== comma )
tags = tags.replace(/,/g, comma);
return tags;
},
parseTags : function(el) {
var id = el.id, num = id.split('-check-num-')[1], taxbox = $(el).closest('.tagsdiv'),
thetags = taxbox.find('.the-tags'), comma = postL10n.comma,
current_tags = thetags.val().split(comma), new_tags = [];
delete current_tags[num];
$.each( current_tags, function(key, val) {
val = $.trim(val);
if ( val ) {
new_tags.push(val);
}
});
thetags.val( this.clean( new_tags.join(comma) ) );
this.quickClicks(taxbox);
return false;
},
quickClicks : function(el) {
var thetags = $('.the-tags', el),
tagchecklist = $('.tagchecklist', el),
id = $(el).attr('id'),
current_tags, disabled;
if ( !thetags.length )
return;
disabled = thetags.prop('disabled');
current_tags = thetags.val().split(postL10n.comma);
tagchecklist.empty();
$.each( current_tags, function( key, val ) {
var span, xbutton;
val = $.trim( val );
if ( ! val )
return;
// Create a new span, and ensure the text is properly escaped.
span = $('<span />').text( val );
// If tags editing isn't disabled, create the X button.
if ( ! disabled ) {
xbutton = $( '<a id="' + id + '-check-num-' + key + '" class="ntdelbutton">X</a>' );
xbutton.click( function(){ tagBox.parseTags(this); });
span.prepend(' ').prepend( xbutton );
}
// Append the span to the tag list.
tagchecklist.append( span );
});
},
flushTags : function(el, a, f) {
a = a || false;
var tags = $('.the-tags', el),
newtag = $('input.newtag', el),
comma = postL10n.comma,
newtags, text;
text = a ? $(a).text() : newtag.val();
tagsval = tags.val();
newtags = tagsval ? tagsval + comma + text : text;
newtags = this.clean( newtags );
newtags = array_unique_noempty( newtags.split(comma) ).join(comma);
tags.val(newtags);
this.quickClicks(el);
if ( !a )
newtag.val('');
if ( 'undefined' == typeof(f) )
newtag.focus();
return false;
},
get : function(id) {
var tax = id.substr(id.indexOf('-')+1);
$.post(ajaxurl, {'action':'get-tagcloud', 'tax':tax}, function(r, stat) {
if ( 0 == r || 'success' != stat )
r = wpAjax.broken;
r = $('<p id="tagcloud-'+tax+'" class="the-tagcloud">'+r+'</p>');
$('a', r).click(function(){
tagBox.flushTags( $(this).closest('.inside').children('.tagsdiv'), this);
return false;
});
$('#'+id).after(r);
});
},
init : function() {
var t = this, ajaxtag = $('div.ajaxtag');
$('.tagsdiv').each( function() {
tagBox.quickClicks(this);
});
$('input.tagadd', ajaxtag).click(function(){
t.flushTags( $(this).closest('.tagsdiv') );
});
$('div.taghint', ajaxtag).click(function(){
$(this).css('visibility', 'hidden').parent().siblings('.newtag').focus();
});
$('input.newtag', ajaxtag).blur(function() {
if ( this.value == '' )
$(this).parent().siblings('.taghint').css('visibility', '');
}).focus(function(){
$(this).parent().siblings('.taghint').css('visibility', 'hidden');
}).keyup(function(e){
if ( 13 == e.which ) {
tagBox.flushTags( $(this).closest('.tagsdiv') );
return false;
}
}).keypress(function(e){
if ( 13 == e.which ) {
e.preventDefault();
return false;
}
}).each(function(){
var tax = $(this).closest('div.tagsdiv').attr('id');
$(this).suggest( ajaxurl + '?action=ajax-tag-search&tax=' + tax, { delay: 500, minchars: 2, multiple: true, multipleSep: postL10n.comma + ' ' } );
});
// save tags on post save/publish
$('#post').submit(function(){
$('div.tagsdiv').each( function() {
tagBox.flushTags(this, false, 1);
});
});
// tag cloud
$('a.tagcloud-link').click(function(){
tagBox.get( $(this).attr('id') );
$(this).unbind().click(function(){
$(this).siblings('.the-tagcloud').toggle();
return false;
});
return false;
});
}
};
commentsBox = {
st : 0,
get : function(total, num) {
var st = this.st, data;
if ( ! num )
num = 20;
this.st += num;
this.total = total;
$('#commentsdiv img.waiting').show();
data = {
'action' : 'get-comments',
'mode' : 'single',
'_ajax_nonce' : $('#add_comment_nonce').val(),
'p' : $('#post_ID').val(),
'start' : st,
'number' : num
};
$.post(ajaxurl, data,
function(r) {
r = wpAjax.parseAjaxResponse(r);
$('#commentsdiv .widefat').show();
$('#commentsdiv img.waiting').hide();
if ( 'object' == typeof r && r.responses[0] ) {
$('#the-comment-list').append( r.responses[0].data );
theList = theExtraList = null;
$("a[className*=':']").unbind();
if ( commentsBox.st > commentsBox.total )
$('#show-comments').hide();
else
$('#show-comments').show().children('a').html(postL10n.showcomm);
return;
} else if ( 1 == r ) {
$('#show-comments').html(postL10n.endcomm);
return;
}
$('#the-comment-list').append('<tr><td colspan="2">'+wpAjax.broken+'</td></tr>');
}
);
return false;
}
};
WPSetThumbnailHTML = function(html){
$('.inside', '#postimagediv').html(html);
};
WPSetThumbnailID = function(id){
var field = $('input[value="_thumbnail_id"]', '#list-table');
if ( field.size() > 0 ) {
$('#meta\\[' + field.attr('id').match(/[0-9]+/) + '\\]\\[value\\]').text(id);
}
};
WPRemoveThumbnail = function(nonce){
$.post(ajaxurl, {
action:"set-post-thumbnail", post_id: $('#post_ID').val(), thumbnail_id: -1, _ajax_nonce: nonce, cookie: encodeURIComponent(document.cookie)
}, function(str){
if ( str == '0' ) {
alert( setPostThumbnailL10n.error );
} else {
WPSetThumbnailHTML(str);
}
}
);
};
})(jQuery);
jQuery(document).ready( function($) {
var stamp, visibility, sticky = '', last = 0, co = $('#content');
postboxes.add_postbox_toggles(pagenow);
// multi-taxonomies
if ( $('#tagsdiv-post_tag').length ) {
tagBox.init();
} else {
$('#side-sortables, #normal-sortables, #advanced-sortables').children('div.postbox').each(function(){
if ( this.id.indexOf('tagsdiv-') === 0 ) {
tagBox.init();
return false;
}
});
}
// categories
$('.categorydiv').each( function(){
var this_id = $(this).attr('id'), noSyncChecks = false, syncChecks, catAddAfter, taxonomyParts, taxonomy, settingName;
taxonomyParts = this_id.split('-');
taxonomyParts.shift();
taxonomy = taxonomyParts.join('-');
settingName = taxonomy + '_tab';
if ( taxonomy == 'category' )
settingName = 'cats';
// TODO: move to jQuery 1.3+, support for multiple hierarchical taxonomies, see wp-lists.dev.js
$('a', '#' + taxonomy + '-tabs').click( function(){
var t = $(this).attr('href');
$(this).parent().addClass('tabs').siblings('li').removeClass('tabs');
$('#' + taxonomy + '-tabs').siblings('.tabs-panel').hide();
$(t).show();
if ( '#' + taxonomy + '-all' == t )
deleteUserSetting(settingName);
else
setUserSetting(settingName, 'pop');
return false;
});
if ( getUserSetting(settingName) )
$('a[href="#' + taxonomy + '-pop"]', '#' + taxonomy + '-tabs').click();
// Ajax Cat
$('#new' + taxonomy).one( 'focus', function() { $(this).val( '' ).removeClass( 'form-input-tip' ) } );
$('#' + taxonomy + '-add-submit').click( function(){ $('#new' + taxonomy).focus(); });
syncChecks = function() {
if ( noSyncChecks )
return;
noSyncChecks = true;
var th = jQuery(this), c = th.is(':checked'), id = th.val().toString();
$('#in-' + taxonomy + '-' + id + ', #in-' + taxonomy + '-category-' + id).prop( 'checked', c );
noSyncChecks = false;
};
catAddBefore = function( s ) {
if ( !$('#new'+taxonomy).val() )
return false;
s.data += '&' + $( ':checked', '#'+taxonomy+'checklist' ).serialize();
$( '#' + taxonomy + '-add-submit' ).prop( 'disabled', true );
return s;
};
catAddAfter = function( r, s ) {
var sup, drop = $('#new'+taxonomy+'_parent');
$( '#' + taxonomy + '-add-submit' ).prop( 'disabled', false );
if ( 'undefined' != s.parsed.responses[0] && (sup = s.parsed.responses[0].supplemental.newcat_parent) ) {
drop.before(sup);
drop.remove();
}
};
$('#' + taxonomy + 'checklist').wpList({
alt: '',
response: taxonomy + '-ajax-response',
addBefore: catAddBefore,
addAfter: catAddAfter
});
$('#' + taxonomy + '-add-toggle').click( function() {
$('#' + taxonomy + '-adder').toggleClass( 'wp-hidden-children' );
$('a[href="#' + taxonomy + '-all"]', '#' + taxonomy + '-tabs').click();
$('#new'+taxonomy).focus();
return false;
});
$('#' + taxonomy + 'checklist li.popular-category :checkbox, #' + taxonomy + 'checklist-pop :checkbox').live( 'click', function(){
var t = $(this), c = t.is(':checked'), id = t.val();
if ( id && t.parents('#taxonomy-'+taxonomy).length )
$('#in-' + taxonomy + '-' + id + ', #in-popular-' + taxonomy + '-' + id).prop( 'checked', c );
});
}); // end cats
// Custom Fields
if ( $('#postcustom').length ) {
$('#the-list').wpList( { addAfter: function( xml, s ) {
$('table#list-table').show();
}, addBefore: function( s ) {
s.data += '&post_id=' + $('#post_ID').val();
return s;
}
});
}
// submitdiv
if ( $('#submitdiv').length ) {
stamp = $('#timestamp').html();
visibility = $('#post-visibility-display').html();
function updateVisibility() {
var pvSelect = $('#post-visibility-select');
if ( $('input:radio:checked', pvSelect).val() != 'public' ) {
$('#sticky').prop('checked', false);
$('#sticky-span').hide();
} else {
$('#sticky-span').show();
}
if ( $('input:radio:checked', pvSelect).val() != 'password' ) {
$('#password-span').hide();
} else {
$('#password-span').show();
}
}
function updateText() {
var attemptedDate, originalDate, currentDate, publishOn, postStatus = $('#post_status'),
optPublish = $('option[value="publish"]', postStatus), aa = $('#aa').val(),
mm = $('#mm').val(), jj = $('#jj').val(), hh = $('#hh').val(), mn = $('#mn').val();
attemptedDate = new Date( aa, mm - 1, jj, hh, mn );
originalDate = new Date( $('#hidden_aa').val(), $('#hidden_mm').val() -1, $('#hidden_jj').val(), $('#hidden_hh').val(), $('#hidden_mn').val() );
currentDate = new Date( $('#cur_aa').val(), $('#cur_mm').val() -1, $('#cur_jj').val(), $('#cur_hh').val(), $('#cur_mn').val() );
if ( attemptedDate.getFullYear() != aa || (1 + attemptedDate.getMonth()) != mm || attemptedDate.getDate() != jj || attemptedDate.getMinutes() != mn ) {
$('.timestamp-wrap', '#timestampdiv').addClass('form-invalid');
return false;
} else {
$('.timestamp-wrap', '#timestampdiv').removeClass('form-invalid');
}
if ( attemptedDate > currentDate && $('#original_post_status').val() != 'future' ) {
publishOn = postL10n.publishOnFuture;
$('#publish').val( postL10n.schedule );
} else if ( attemptedDate <= currentDate && $('#original_post_status').val() != 'publish' ) {
publishOn = postL10n.publishOn;
$('#publish').val( postL10n.publish );
} else {
publishOn = postL10n.publishOnPast;
$('#publish').val( postL10n.update );
}
if ( originalDate.toUTCString() == attemptedDate.toUTCString() ) { //hack
$('#timestamp').html(stamp);
} else {
$('#timestamp').html(
publishOn + ' <b>' +
$('option[value="' + $('#mm').val() + '"]', '#mm').text() + ' ' +
jj + ', ' +
aa + ' @ ' +
hh + ':' +
mn + '</b> '
);
}
if ( $('input:radio:checked', '#post-visibility-select').val() == 'private' ) {
$('#publish').val( postL10n.update );
if ( optPublish.length == 0 ) {
postStatus.append('<option value="publish">' + postL10n.privatelyPublished + '</option>');
} else {
optPublish.html( postL10n.privatelyPublished );
}
$('option[value="publish"]', postStatus).prop('selected', true);
$('.edit-post-status', '#misc-publishing-actions').hide();
} else {
if ( $('#original_post_status').val() == 'future' || $('#original_post_status').val() == 'draft' ) {
if ( optPublish.length ) {
optPublish.remove();
postStatus.val($('#hidden_post_status').val());
}
} else {
optPublish.html( postL10n.published );
}
if ( postStatus.is(':hidden') )
$('.edit-post-status', '#misc-publishing-actions').show();
}
$('#post-status-display').html($('option:selected', postStatus).text());
if ( $('option:selected', postStatus).val() == 'private' || $('option:selected', postStatus).val() == 'publish' ) {
$('#save-post').hide();
} else {
$('#save-post').show();
if ( $('option:selected', postStatus).val() == 'pending' ) {
$('#save-post').show().val( postL10n.savePending );
} else {
$('#save-post').show().val( postL10n.saveDraft );
}
}
return true;
}
$('.edit-visibility', '#visibility').click(function () {
if ($('#post-visibility-select').is(":hidden")) {
updateVisibility();
$('#post-visibility-select').slideDown('fast');
$(this).hide();
}
return false;
});
$('.cancel-post-visibility', '#post-visibility-select').click(function () {
$('#post-visibility-select').slideUp('fast');
$('#visibility-radio-' + $('#hidden-post-visibility').val()).prop('checked', true);
$('#post_password').val($('#hidden_post_password').val());
$('#sticky').prop('checked', $('#hidden-post-sticky').prop('checked'));
$('#post-visibility-display').html(visibility);
$('.edit-visibility', '#visibility').show();
updateText();
return false;
});
$('.save-post-visibility', '#post-visibility-select').click(function () { // crazyhorse - multiple ok cancels
var pvSelect = $('#post-visibility-select');
pvSelect.slideUp('fast');
$('.edit-visibility', '#visibility').show();
updateText();
if ( $('input:radio:checked', pvSelect).val() != 'public' ) {
$('#sticky').prop('checked', false);
} // WEAPON LOCKED
if ( true == $('#sticky').prop('checked') ) {
sticky = 'Sticky';
} else {
sticky = '';
}
$('#post-visibility-display').html( postL10n[$('input:radio:checked', pvSelect).val() + sticky] );
return false;
});
$('input:radio', '#post-visibility-select').change(function() {
updateVisibility();
});
$('#timestampdiv').siblings('a.edit-timestamp').click(function() {
if ($('#timestampdiv').is(":hidden")) {
$('#timestampdiv').slideDown('fast');
$(this).hide();
}
return false;
});
$('.cancel-timestamp', '#timestampdiv').click(function() {
$('#timestampdiv').slideUp('fast');
$('#mm').val($('#hidden_mm').val());
$('#jj').val($('#hidden_jj').val());
$('#aa').val($('#hidden_aa').val());
$('#hh').val($('#hidden_hh').val());
$('#mn').val($('#hidden_mn').val());
$('#timestampdiv').siblings('a.edit-timestamp').show();
updateText();
return false;
});
$('.save-timestamp', '#timestampdiv').click(function () { // crazyhorse - multiple ok cancels
if ( updateText() ) {
$('#timestampdiv').slideUp('fast');
$('#timestampdiv').siblings('a.edit-timestamp').show();
}
return false;
});
$('#post-status-select').siblings('a.edit-post-status').click(function() {
if ($('#post-status-select').is(":hidden")) {
$('#post-status-select').slideDown('fast');
$(this).hide();
}
return false;
});
$('.save-post-status', '#post-status-select').click(function() {
$('#post-status-select').slideUp('fast');
$('#post-status-select').siblings('a.edit-post-status').show();
updateText();
return false;
});
$('.cancel-post-status', '#post-status-select').click(function() {
$('#post-status-select').slideUp('fast');
$('#post_status').val($('#hidden_post_status').val());
$('#post-status-select').siblings('a.edit-post-status').show();
updateText();
return false;
});
} // end submitdiv
// permalink
if ( $('#edit-slug-box').length ) {
editPermalink = function(post_id) {
var i, c = 0, e = $('#editable-post-name'), revert_e = e.html(), real_slug = $('#post_name'), revert_slug = real_slug.val(), b = $('#edit-slug-buttons'), revert_b = b.html(), full = $('#editable-post-name-full').html();
$('#view-post-btn').hide();
b.html('<a href="#" class="save button">'+postL10n.ok+'</a> <a class="cancel" href="#">'+postL10n.cancel+'</a>');
b.children('.save').click(function() {
var new_slug = e.children('input').val();
if ( new_slug == $('#editable-post-name-full').text() ) {
return $('.cancel', '#edit-slug-buttons').click();
}
$.post(ajaxurl, {
action: 'sample-permalink',
post_id: post_id,
new_slug: new_slug,
new_title: $('#title').val(),
samplepermalinknonce: $('#samplepermalinknonce').val()
}, function(data) {
$('#edit-slug-box').html(data);
b.html(revert_b);
real_slug.val(new_slug);
makeSlugeditClickable();
$('#view-post-btn').show();
});
return false;
});
$('.cancel', '#edit-slug-buttons').click(function() {
$('#view-post-btn').show();
e.html(revert_e);
b.html(revert_b);
real_slug.val(revert_slug);
return false;
});
for ( i = 0; i < full.length; ++i ) {
if ( '%' == full.charAt(i) )
c++;
}
slug_value = ( c > full.length / 4 ) ? '' : full;
e.html('<input type="text" id="new-post-slug" value="'+slug_value+'" />').children('input').keypress(function(e){
var key = e.keyCode || 0;
// on enter, just save the new slug, don't save the post
if ( 13 == key ) {
b.children('.save').click();
return false;
}
if ( 27 == key ) {
b.children('.cancel').click();
return false;
}
real_slug.val(this.value);
}).focus();
}
makeSlugeditClickable = function() {
$('#editable-post-name').click(function() {
$('#edit-slug-buttons').children('.edit-slug').click();
});
}
makeSlugeditClickable();
}
// word count
if ( typeof(wpWordCount) != 'undefined' ) {
$(document).triggerHandler('wpcountwords', [ co.val() ]);
co.keyup( function(e) {
var k = e.keyCode || e.charCode;
if ( k == last )
return true;
if ( 13 == k || 8 == last || 46 == last )
$(document).triggerHandler('wpcountwords', [ co.val() ]);
last = k;
return true;
});
}
wptitlehint = function(id) {
id = id || 'title';
var title = $('#' + id), titleprompt = $('#' + id + '-prompt-text');
if ( title.val() == '' )
titleprompt.css('visibility', '');
titleprompt.click(function(){
$(this).css('visibility', 'hidden');
title.focus();
});
title.blur(function(){
if ( this.value == '' )
titleprompt.css('visibility', '');
}).focus(function(){
titleprompt.css('visibility', 'hidden');
}).keydown(function(e){
titleprompt.css('visibility', 'hidden');
$(this).unbind(e);
});
}
wptitlehint();
});
| JavaScript |
// utility functions
var wpCookies = {
// The following functions are from Cookie.js class in TinyMCE, Moxiecode, used under LGPL.
each : function(obj, cb, scope) {
var n, l;
if ( !obj )
return 0;
scope = scope || obj;
if ( typeof(obj.length) != 'undefined' ) {
for ( n = 0, l = obj.length; n < l; n++ ) {
if ( cb.call(scope, obj[n], n, obj) === false )
return 0;
}
} else {
for ( n in obj ) {
if ( obj.hasOwnProperty(n) ) {
if ( cb.call(scope, obj[n], n, obj) === false ) {
return 0;
}
}
}
}
return 1;
},
/**
* Get a multi-values cookie.
* Returns a JS object with the name: 'value' pairs.
*/
getHash : function(name) {
var all = this.get(name), ret;
if ( all ) {
this.each( all.split('&'), function(pair) {
pair = pair.split('=');
ret = ret || {};
ret[pair[0]] = pair[1];
});
}
return ret;
},
/**
* Set a multi-values cookie.
*
* 'values_obj' is the JS object that is stored. It is encoded as URI in wpCookies.set().
*/
setHash : function(name, values_obj, expires, path, domain, secure) {
var str = '';
this.each(values_obj, function(val, key) {
str += (!str ? '' : '&') + key + '=' + val;
});
this.set(name, str, expires, path, domain, secure);
},
/**
* Get a cookie.
*/
get : function(name) {
var cookie = document.cookie, e, p = name + "=", b;
if ( !cookie )
return;
b = cookie.indexOf("; " + p);
if ( b == -1 ) {
b = cookie.indexOf(p);
if ( b != 0 )
return null;
} else {
b += 2;
}
e = cookie.indexOf(";", b);
if ( e == -1 )
e = cookie.length;
return decodeURIComponent( cookie.substring(b + p.length, e) );
},
/**
* Set a cookie.
*
* The 'expires' arg can be either a JS Date() object set to the expiration date (back-compat)
* or the number of seconds until expiration
*/
set : function(name, value, expires, path, domain, secure) {
var d = new Date();
if ( typeof(expires) == 'object' && expires.toGMTString ) {
expires = expires.toGMTString();
} else if ( parseInt(expires, 10) ) {
d.setTime( d.getTime() + ( parseInt(expires, 10) * 1000 ) ); // time must be in miliseconds
expires = d.toGMTString();
} else {
expires = '';
}
document.cookie = name + "=" + encodeURIComponent(value) +
((expires) ? "; expires=" + expires : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
},
/**
* Remove a cookie.
*
* This is done by setting it to an empty value and setting the expiration time in the past.
*/
remove : function(name, path) {
this.set(name, '', -1000, path);
}
};
// Returns the value as string. Second arg or empty string is returned when value is not set.
function getUserSetting( name, def ) {
var obj = getAllUserSettings();
if ( obj.hasOwnProperty(name) )
return obj[name];
if ( typeof def != 'undefined' )
return def;
return '';
}
// Both name and value must be only ASCII letters, numbers or underscore
// and the shorter, the better (cookies can store maximum 4KB). Not suitable to store text.
function setUserSetting( name, value, _del ) {
if ( 'object' !== typeof userSettings )
return false;
var cookie = 'wp-settings-' + userSettings.uid, all = wpCookies.getHash(cookie) || {}, path = userSettings.url,
n = name.toString().replace(/[^A-Za-z0-9_]/, ''), v = value.toString().replace(/[^A-Za-z0-9_]/, '');
if ( _del ) {
delete all[n];
} else {
all[n] = v;
}
wpCookies.setHash(cookie, all, 31536000, path);
wpCookies.set('wp-settings-time-'+userSettings.uid, userSettings.time, 31536000, path);
return name;
}
function deleteUserSetting( name ) {
return setUserSetting( name, '', 1 );
}
// Returns all settings as js object.
function getAllUserSettings() {
if ( 'object' !== typeof userSettings )
return {};
return wpCookies.getHash('wp-settings-' + userSettings.uid) || {};
}
| JavaScript |
(function($){
function check_pass_strength() {
var pass1 = $('#pass1').val(), user = $('#user_login').val(), pass2 = $('#pass2').val(), strength;
$('#pass-strength-result').removeClass('short bad good strong');
if ( ! pass1 ) {
$('#pass-strength-result').html( pwsL10n.empty );
return;
}
strength = passwordStrength(pass1, user, pass2);
switch ( strength ) {
case 2:
$('#pass-strength-result').addClass('bad').html( pwsL10n['bad'] );
break;
case 3:
$('#pass-strength-result').addClass('good').html( pwsL10n['good'] );
break;
case 4:
$('#pass-strength-result').addClass('strong').html( pwsL10n['strong'] );
break;
case 5:
$('#pass-strength-result').addClass('short').html( pwsL10n['mismatch'] );
break;
default:
$('#pass-strength-result').addClass('short').html( pwsL10n['short'] );
}
}
$(document).ready( function() {
var select = $('#display_name');
$('#pass1').val('').keyup( check_pass_strength );
$('#pass2').val('').keyup( check_pass_strength );
$('#pass-strength-result').show();
$('.color-palette').click( function() {
$(this).siblings('input[name="admin_color"]').prop('checked', true);
});
if ( select.length ) {
$('#first_name, #last_name, #nickname').bind( 'blur.user_profile', function() {
var dub = [],
inputs = {
display_nickname : $('#nickname').val() || '',
display_username : $('#user_login').val() || '',
display_firstname : $('#first_name').val() || '',
display_lastname : $('#last_name').val() || ''
};
if ( inputs.display_firstname && inputs.display_lastname ) {
inputs['display_firstlast'] = inputs.display_firstname + ' ' + inputs.display_lastname;
inputs['display_lastfirst'] = inputs.display_lastname + ' ' + inputs.display_firstname;
}
$.each( $('option', select), function( i, el ){
dub.push( el.value );
});
$.each(inputs, function( id, value ) {
if ( ! value )
return;
var val = value.replace(/<\/?[a-z][^>]*>/gi, '');
if ( inputs[id].length && $.inArray( val, dub ) == -1 ) {
dub.push(val);
$('<option />', {
'text': val
}).appendTo( select );
}
});
});
}
});
})(jQuery);
| JavaScript |
var wpWidgets;
(function($) {
wpWidgets = {
init : function() {
var rem, sidebars = $('div.widgets-sortables'), isRTL = !! ( 'undefined' != typeof isRtl && isRtl ),
margin = ( isRtl ? 'marginRight' : 'marginLeft' ), the_id;
$('#widgets-right').children('.widgets-holder-wrap').children('.sidebar-name').click(function(){
var c = $(this).siblings('.widgets-sortables'), p = $(this).parent();
if ( !p.hasClass('closed') ) {
c.sortable('disable');
p.addClass('closed');
} else {
p.removeClass('closed');
c.sortable('enable').sortable('refresh');
}
});
$('#widgets-left').children('.widgets-holder-wrap').children('.sidebar-name').click(function() {
$(this).parent().toggleClass('closed');
});
sidebars.each(function(){
if ( $(this).parent().hasClass('inactive') )
return true;
var h = 50, H = $(this).children('.widget').length;
h = h + parseInt(H * 48, 10);
$(this).css( 'minHeight', h + 'px' );
});
$('a.widget-action').live('click', function(){
var css = {}, widget = $(this).closest('div.widget'), inside = widget.children('.widget-inside'), w = parseInt( widget.find('input.widget-width').val(), 10 );
if ( inside.is(':hidden') ) {
if ( w > 250 && inside.closest('div.widgets-sortables').length ) {
css['width'] = w + 30 + 'px';
if ( inside.closest('div.widget-liquid-right').length )
css[margin] = 235 - w + 'px';
widget.css(css);
}
wpWidgets.fixLabels(widget);
inside.slideDown('fast');
} else {
inside.slideUp('fast', function() {
widget.css({'width':'', margin:''});
});
}
return false;
});
$('input.widget-control-save').live('click', function(){
wpWidgets.save( $(this).closest('div.widget'), 0, 1, 0 );
return false;
});
$('a.widget-control-remove').live('click', function(){
wpWidgets.save( $(this).closest('div.widget'), 1, 1, 0 );
return false;
});
$('a.widget-control-close').live('click', function(){
wpWidgets.close( $(this).closest('div.widget') );
return false;
});
sidebars.children('.widget').each(function() {
wpWidgets.appendTitle(this);
if ( $('p.widget-error', this).length )
$('a.widget-action', this).click();
});
$('#widget-list').children('.widget').draggable({
connectToSortable: 'div.widgets-sortables',
handle: '> .widget-top > .widget-title',
distance: 2,
helper: 'clone',
zIndex: 5,
containment: 'document',
start: function(e,ui) {
ui.helper.find('div.widget-description').hide();
the_id = this.id;
},
stop: function(e,ui) {
if ( rem )
$(rem).hide();
rem = '';
}
});
sidebars.sortable({
placeholder: 'widget-placeholder',
items: '> .widget',
handle: '> .widget-top > .widget-title',
cursor: 'move',
distance: 2,
containment: 'document',
start: function(e,ui) {
ui.item.children('.widget-inside').hide();
ui.item.css({margin:'', 'width':''});
},
stop: function(e,ui) {
if ( ui.item.hasClass('ui-draggable') && ui.item.data('draggable') )
ui.item.draggable('destroy');
if ( ui.item.hasClass('deleting') ) {
wpWidgets.save( ui.item, 1, 0, 1 ); // delete widget
ui.item.remove();
return;
}
var add = ui.item.find('input.add_new').val(),
n = ui.item.find('input.multi_number').val(),
id = the_id,
sb = $(this).attr('id');
ui.item.css({margin:'', 'width':''});
the_id = '';
if ( add ) {
if ( 'multi' == add ) {
ui.item.html( ui.item.html().replace(/<[^<>]+>/g, function(m){ return m.replace(/__i__|%i%/g, n); }) );
ui.item.attr( 'id', id.replace('__i__', n) );
n++;
$('div#' + id).find('input.multi_number').val(n);
} else if ( 'single' == add ) {
ui.item.attr( 'id', 'new-' + id );
rem = 'div#' + id;
}
wpWidgets.save( ui.item, 0, 0, 1 );
ui.item.find('input.add_new').val('');
ui.item.find('a.widget-action').click();
return;
}
wpWidgets.saveOrder(sb);
},
receive: function(e, ui) {
var sender = $(ui.sender);
if ( !$(this).is(':visible') || this.id.indexOf('orphaned_widgets') != -1 )
sender.sortable('cancel');
if ( sender.attr('id').indexOf('orphaned_widgets') != -1 && !sender.children('.widget').length ) {
sender.parents('.orphan-sidebar').slideUp(400, function(){ $(this).remove(); });
}
}
}).sortable('option', 'connectWith', 'div.widgets-sortables').parent().filter('.closed').children('.widgets-sortables').sortable('disable');
$('#available-widgets').droppable({
tolerance: 'pointer',
accept: function(o){
return $(o).parent().attr('id') != 'widget-list';
},
drop: function(e,ui) {
ui.draggable.addClass('deleting');
$('#removing-widget').hide().children('span').html('');
},
over: function(e,ui) {
ui.draggable.addClass('deleting');
$('div.widget-placeholder').hide();
if ( ui.draggable.hasClass('ui-sortable-helper') )
$('#removing-widget').show().children('span')
.html( ui.draggable.find('div.widget-title').children('h4').html() );
},
out: function(e,ui) {
ui.draggable.removeClass('deleting');
$('div.widget-placeholder').show();
$('#removing-widget').hide().children('span').html('');
}
});
},
saveOrder : function(sb) {
if ( sb )
$('#' + sb).closest('div.widgets-holder-wrap').find('img.ajax-feedback').css('visibility', 'visible');
var a = {
action: 'widgets-order',
savewidgets: $('#_wpnonce_widgets').val(),
sidebars: []
};
$('div.widgets-sortables').each( function() {
if ( $(this).sortable )
a['sidebars[' + $(this).attr('id') + ']'] = $(this).sortable('toArray').join(',');
});
$.post( ajaxurl, a, function() {
$('img.ajax-feedback').css('visibility', 'hidden');
});
this.resize();
},
save : function(widget, del, animate, order) {
var sb = widget.closest('div.widgets-sortables').attr('id'), data = widget.find('form').serialize(), a;
widget = $(widget);
$('.ajax-feedback', widget).css('visibility', 'visible');
a = {
action: 'save-widget',
savewidgets: $('#_wpnonce_widgets').val(),
sidebar: sb
};
if ( del )
a['delete_widget'] = 1;
data += '&' + $.param(a);
$.post( ajaxurl, data, function(r){
var id;
if ( del ) {
if ( !$('input.widget_number', widget).val() ) {
id = $('input.widget-id', widget).val();
$('#available-widgets').find('input.widget-id').each(function(){
if ( $(this).val() == id )
$(this).closest('div.widget').show();
});
}
if ( animate ) {
order = 0;
widget.slideUp('fast', function(){
$(this).remove();
wpWidgets.saveOrder();
});
} else {
widget.remove();
wpWidgets.resize();
}
} else {
$('.ajax-feedback').css('visibility', 'hidden');
if ( r && r.length > 2 ) {
$('div.widget-content', widget).html(r);
wpWidgets.appendTitle(widget);
wpWidgets.fixLabels(widget);
}
}
if ( order )
wpWidgets.saveOrder();
});
},
appendTitle : function(widget) {
var title = $('input[id*="-title"]', widget).val() || '';
if ( title )
title = ': ' + title.replace(/<[^<>]+>/g, '').replace(/</g, '<').replace(/>/g, '>');
$(widget).children('.widget-top').children('.widget-title').children()
.children('.in-widget-title').html(title);
},
resize : function() {
$('div.widgets-sortables').each(function(){
if ( $(this).parent().hasClass('inactive') )
return true;
var h = 50, H = $(this).children('.widget').length;
h = h + parseInt(H * 48, 10);
$(this).css( 'minHeight', h + 'px' );
});
},
fixLabels : function(widget) {
widget.children('.widget-inside').find('label').each(function(){
var f = $(this).attr('for');
if ( f && f == $('input', this).attr('id') )
$(this).removeAttr('for');
});
},
close : function(widget) {
widget.children('.widget-inside').slideUp('fast', function(){
widget.css({'width':'', margin:''});
});
}
};
$(document).ready(function($){ wpWidgets.init(); });
})(jQuery);
| JavaScript |
/* Plugin Browser Thickbox related JS*/
var tb_position;
jQuery(document).ready(function($) {
tb_position = function() {
var tbWindow = $('#TB_window'), width = $(window).width(), H = $(window).height(), W = ( 720 < width ) ? 720 : width, adminbar_height = 0;
if ( $('body.admin-bar').length )
adminbar_height = 28;
if ( tbWindow.size() ) {
tbWindow.width( W - 50 ).height( H - 45 - adminbar_height );
$('#TB_iframeContent').width( W - 50 ).height( H - 75 - adminbar_height );
tbWindow.css({'margin-left': '-' + parseInt((( W - 50 ) / 2),10) + 'px'});
if ( typeof document.body.style.maxWidth != 'undefined' )
tbWindow.css({'top': 20 + adminbar_height + 'px','margin-top':'0'});
};
return $('a.thickbox').each( function() {
var href = $(this).attr('href');
if ( ! href )
return;
href = href.replace(/&width=[0-9]+/g, '');
href = href.replace(/&height=[0-9]+/g, '');
$(this).attr( 'href', href + '&width=' + ( W - 80 ) + '&height=' + ( H - 85 - adminbar_height ) );
});
};
$(window).resize(function(){ tb_position(); });
$('#dashboard_plugins a.thickbox, .plugins a.thickbox').click( function() {
tb_click.call(this);
$('#TB_title').css({'background-color':'#222','color':'#cfcfcf'});
$('#TB_ajaxWindowTitle').html('<strong>' + plugininstallL10n.plugin_information + '</strong> ' + $(this).attr('title') );
return false;
});
/* Plugin install related JS*/
$('#plugin-information #sidemenu a').click( function() {
var tab = $(this).attr('name');
//Flip the tab
$('#plugin-information-header a.current').removeClass('current');
$(this).addClass('current');
//Flip the content.
$('#section-holder div.section').hide(); //Hide 'em all
$('#section-' + tab).show();
return false;
});
$('a.install-now').click( function() {
return confirm( plugininstallL10n.ays );
});
});
| JavaScript |
(function( exports, $ ){
var api = wp.customize;
/*
* @param options
* - previewer - The Previewer instance to sync with.
* - transport - The transport to use for previewing. Supports 'refresh' and 'postMessage'.
*/
api.Setting = api.Value.extend({
initialize: function( id, value, options ) {
var element;
api.Value.prototype.initialize.call( this, value, options );
this.id = id;
this.transport = this.transport || 'refresh';
this.bind( this.preview );
},
preview: function() {
switch ( this.transport ) {
case 'refresh':
return this.previewer.refresh();
case 'postMessage':
return this.previewer.send( 'setting', [ this.id, this() ] );
}
}
});
api.Control = api.Class.extend({
initialize: function( id, options ) {
var control = this,
nodes, radios, settings;
this.params = {};
$.extend( this, options || {} );
this.id = id;
this.selector = '#customize-control-' + id.replace( ']', '' ).replace( '[', '-' );
this.container = $( this.selector );
settings = $.map( this.params.settings, function( value ) {
return value;
});
api.apply( api, settings.concat( function() {
var key;
control.settings = {};
for ( key in control.params.settings ) {
control.settings[ key ] = api( control.params.settings[ key ] );
}
control.setting = control.settings['default'] || null;
control.ready();
}) );
control.elements = [];
nodes = this.container.find('[data-customize-setting-link]');
radios = {};
nodes.each( function() {
var node = $(this),
name;
if ( node.is(':radio') ) {
name = node.prop('name');
if ( radios[ name ] )
return;
radios[ name ] = true;
node = nodes.filter( '[name="' + name + '"]' );
}
api( node.data('customizeSettingLink'), function( setting ) {
var element = new api.Element( node );
control.elements.push( element );
element.sync( setting );
element.set( setting() );
});
});
},
ready: function() {},
dropdownInit: function() {
var control = this,
statuses = this.container.find('.dropdown-status'),
params = this.params,
update = function( to ) {
if ( typeof to === 'string' && params.statuses && params.statuses[ to ] )
statuses.html( params.statuses[ to ] ).show();
else
statuses.hide();
};
// Support the .dropdown class to open/close complex elements
this.container.on( 'click', '.dropdown', function( event ) {
event.preventDefault();
control.container.toggleClass('open');
});
this.setting.bind( update );
update( this.setting() );
}
});
api.ColorControl = api.Control.extend({
ready: function() {
var control = this,
rhex, spot, input, text, update;
rhex = /^#([A-Fa-f0-9]{3}){0,2}$/;
spot = this.container.find('.dropdown-content');
input = new api.Element( this.container.find('.color-picker-hex') );
update = function( color ) {
spot.css( 'background', color );
control.farbtastic.setColor( color );
};
this.farbtastic = $.farbtastic( this.container.find('.farbtastic-placeholder'), control.setting.set );
// Only pass through values that are valid hexes/empty.
input.sync( this.setting ).validate = function( to ) {
return rhex.test( to ) ? to : null;
};
this.setting.bind( update );
update( this.setting() );
this.dropdownInit();
}
});
api.UploadControl = api.Control.extend({
ready: function() {
var control = this;
this.params.removed = this.params.removed || '';
this.success = $.proxy( this.success, this );
this.uploader = $.extend({
container: this.container,
browser: this.container.find('.upload'),
dropzone: this.container.find('.upload-dropzone'),
success: this.success
}, this.uploader || {} );
if ( this.uploader.supported ) {
if ( control.params.context )
control.uploader.param( 'post_data[context]', this.params.context );
control.uploader.param( 'post_data[theme]', api.settings.theme.stylesheet );
}
this.uploader = new wp.Uploader( this.uploader );
this.remover = this.container.find('.remove');
this.remover.click( function( event ) {
control.setting.set( control.params.removed );
event.preventDefault();
});
this.removerVisibility = $.proxy( this.removerVisibility, this );
this.setting.bind( this.removerVisibility );
this.removerVisibility( this.setting.get() );
},
success: function( attachment ) {
this.setting.set( attachment.url );
},
removerVisibility: function( to ) {
this.remover.toggle( to != this.params.removed );
}
});
api.ImageControl = api.UploadControl.extend({
ready: function() {
var control = this,
panels;
this.uploader = {
init: function( up ) {
var fallback, button;
if ( this.supports.dragdrop )
return;
// Maintain references while wrapping the fallback button.
fallback = control.container.find( '.upload-fallback' );
button = fallback.children().detach();
this.browser.detach().empty().append( button );
fallback.append( this.browser ).show();
}
};
api.UploadControl.prototype.ready.call( this );
this.thumbnail = this.container.find('.preview-thumbnail img');
this.thumbnailSrc = $.proxy( this.thumbnailSrc, this );
this.setting.bind( this.thumbnailSrc );
this.library = this.container.find('.library');
// Generate tab objects
this.tabs = {};
panels = this.library.find('.library-content');
this.library.children('ul').children('li').each( function() {
var link = $(this),
id = link.data('customizeTab'),
panel = panels.filter('[data-customize-tab="' + id + '"]');
control.tabs[ id ] = {
both: link.add( panel ),
link: link,
panel: panel
};
});
// Select a tab
this.selected = this.tabs[ panels.first().data('customizeTab') ];
this.selected.both.addClass('library-selected');
// Bind tab switch events
this.library.children('ul').on( 'click', 'li', function( event ) {
var id = $(this).data('customizeTab'),
tab = control.tabs[ id ];
event.preventDefault();
if ( tab.link.hasClass('library-selected') )
return;
control.selected.both.removeClass('library-selected');
control.selected = tab;
control.selected.both.addClass('library-selected');
});
// Bind events to switch image urls.
this.library.on( 'click', 'a', function( event ) {
var value = $(this).data('customizeImageValue');
if ( value ) {
control.setting.set( value );
event.preventDefault();
}
});
if ( this.tabs.uploaded ) {
this.tabs.uploaded.target = this.library.find('.uploaded-target');
if ( ! this.tabs.uploaded.panel.find('.thumbnail').length )
this.tabs.uploaded.both.addClass('hidden');
}
this.dropdownInit();
},
success: function( attachment ) {
api.UploadControl.prototype.success.call( this, attachment );
// Add the uploaded image to the uploaded tab.
if ( this.tabs.uploaded && this.tabs.uploaded.target.length ) {
this.tabs.uploaded.both.removeClass('hidden');
attachment.element = $( '<a href="#" class="thumbnail"></a>' )
.data( 'customizeImageValue', attachment.url )
.append( '<img src="' + attachment.url+ '" />' )
.appendTo( this.tabs.uploaded.target );
}
},
thumbnailSrc: function( to ) {
if ( /^(https?:)?\/\//.test( to ) )
this.thumbnail.prop( 'src', to ).show();
else
this.thumbnail.hide();
}
});
// Change objects contained within the main customize object to Settings.
api.defaultConstructor = api.Setting;
// Create the collection of Control objects.
api.control = new api.Values({ defaultConstructor: api.Control });
api.PreviewFrame = api.Messenger.extend({
sensitivity: 2000,
initialize: function( params, options ) {
var deferred = $.Deferred(),
self = this;
// This is the promise object.
deferred.promise( this );
this.container = params.container;
this.signature = params.signature;
$.extend( params, { channel: api.PreviewFrame.uuid() });
api.Messenger.prototype.initialize.call( this, params, options );
this.add( 'previewUrl', params.previewUrl );
this.query = $.extend( params.query || {}, { customize_messenger_channel: this.channel() });
this.run( deferred );
},
run: function( deferred ) {
var self = this,
loaded = false,
ready = false;
if ( this._ready )
this.unbind( 'ready', this._ready );
this._ready = function() {
ready = true;
if ( loaded )
deferred.resolveWith( self );
};
this.bind( 'ready', this._ready );
this.request = $.ajax( this.previewUrl(), {
type: 'POST',
data: this.query,
xhrFields: {
withCredentials: true
}
} );
this.request.fail( function() {
deferred.rejectWith( self, [ 'request failure' ] );
});
this.request.done( function( response ) {
var location = self.request.getResponseHeader('Location'),
signature = self.signature,
index;
// Check if the location response header differs from the current URL.
// If so, the request was redirected; try loading the requested page.
if ( location && location != self.previewUrl() ) {
deferred.rejectWith( self, [ 'redirect', location ] );
return;
}
// Check if the user is not logged in.
if ( '0' === response ) {
self.login( deferred );
return;
}
// Check for cheaters.
if ( '-1' === response ) {
deferred.rejectWith( self, [ 'cheatin' ] );
return;
}
// Check for a signature in the request.
index = response.lastIndexOf( signature );
if ( -1 === index || index < response.lastIndexOf('</html>') ) {
deferred.rejectWith( self, [ 'unsigned' ] );
return;
}
// Strip the signature from the request.
response = response.slice( 0, index ) + response.slice( index + signature.length );
// Create the iframe and inject the html content.
self.iframe = $('<iframe />').appendTo( self.container );
// Bind load event after the iframe has been added to the page;
// otherwise it will fire when injected into the DOM.
self.iframe.one( 'load', function() {
loaded = true;
if ( ready ) {
deferred.resolveWith( self );
} else {
setTimeout( function() {
deferred.rejectWith( self, [ 'ready timeout' ] );
}, self.sensitivity );
}
});
self.targetWindow( self.iframe[0].contentWindow );
self.targetWindow().document.open();
self.targetWindow().document.write( response );
self.targetWindow().document.close();
});
},
login: function( deferred ) {
var self = this,
reject;
reject = function() {
deferred.rejectWith( self, [ 'logged out' ] );
};
if ( this.triedLogin )
return reject();
// Check if we have an admin cookie.
$.get( api.settings.url.ajax, {
action: 'logged-in'
}).fail( reject ).done( function( response ) {
var iframe;
if ( '1' !== response )
reject();
iframe = $('<iframe src="' + self.previewUrl() + '" />').hide();
iframe.appendTo( self.container );
iframe.load( function() {
self.triedLogin = true;
iframe.remove();
self.run( deferred );
});
});
},
destroy: function() {
api.Messenger.prototype.destroy.call( this );
this.request.abort();
if ( this.iframe )
this.iframe.remove();
delete this.request;
delete this.iframe;
delete this.targetWindow;
}
});
(function(){
var uuid = 0;
api.PreviewFrame.uuid = function() {
return 'preview-' + uuid++;
};
}());
api.Previewer = api.Messenger.extend({
refreshBuffer: 250,
/**
* Requires params:
* - container - a selector or jQuery element
* - previewUrl - the URL of preview frame
*/
initialize: function( params, options ) {
var self = this,
rscheme = /^https?/,
url;
$.extend( this, options || {} );
/*
* Wrap this.refresh to prevent it from hammering the servers:
*
* If refresh is called once and no other refresh requests are
* loading, trigger the request immediately.
*
* If refresh is called while another refresh request is loading,
* debounce the refresh requests:
* 1. Stop the loading request (as it is instantly outdated).
* 2. Trigger the new request once refresh hasn't been called for
* self.refreshBuffer milliseconds.
*/
this.refresh = (function( self ) {
var refresh = self.refresh,
callback = function() {
timeout = null;
refresh.call( self );
},
timeout;
return function() {
if ( typeof timeout !== 'number' ) {
if ( self.loading ) {
self.abort();
} else {
return callback();
}
}
clearTimeout( timeout );
timeout = setTimeout( callback, self.refreshBuffer );
};
})( this );
this.container = api.ensure( params.container );
this.allowedUrls = params.allowedUrls;
this.signature = params.signature;
params.url = window.location.href;
api.Messenger.prototype.initialize.call( this, params );
this.add( 'scheme', this.origin() ).link( this.origin ).setter( function( to ) {
var match = to.match( rscheme );
return match ? match[0] : '';
});
// Limit the URL to internal, front-end links.
//
// If the frontend and the admin are served from the same domain, load the
// preview over ssl if the customizer is being loaded over ssl. This avoids
// insecure content warnings. This is not attempted if the admin and frontend
// are on different domains to avoid the case where the frontend doesn't have
// ssl certs.
this.add( 'previewUrl', params.previewUrl ).setter( function( to ) {
var result;
// Check for URLs that include "/wp-admin/" or end in "/wp-admin".
// Strip hashes and query strings before testing.
if ( /\/wp-admin(\/|$)/.test( to.replace(/[#?].*$/, '') ) )
return null;
// Attempt to match the URL to the control frame's scheme
// and check if it's allowed. If not, try the original URL.
$.each([ to.replace( rscheme, self.scheme() ), to ], function( i, url ) {
$.each( self.allowedUrls, function( i, allowed ) {
if ( 0 === url.indexOf( allowed ) ) {
result = url;
return false;
}
});
if ( result )
return false;
});
// If we found a matching result, return it. If not, bail.
return result ? result : null;
});
// Refresh the preview when the URL is changed (but not yet).
this.previewUrl.bind( this.refresh );
this.scroll = 0;
this.bind( 'scroll', function( distance ) {
this.scroll = distance;
});
// Update the URL when the iframe sends a URL message.
this.bind( 'url', this.previewUrl );
},
query: function() {},
abort: function() {
if ( this.loading ) {
this.loading.destroy();
delete this.loading;
}
},
refresh: function() {
var self = this;
this.abort();
this.loading = new api.PreviewFrame({
url: this.url(),
previewUrl: this.previewUrl(),
query: this.query() || {},
container: this.container,
signature: this.signature
});
this.loading.done( function() {
// 'this' is the loading frame
this.bind( 'synced', function() {
if ( self.preview )
self.preview.destroy();
self.preview = this;
delete self.loading;
self.targetWindow( this.targetWindow() );
self.channel( this.channel() );
self.send( 'active' );
});
this.send( 'sync', {
scroll: self.scroll,
settings: api.get()
});
});
this.loading.fail( function( reason, location ) {
if ( 'redirect' === reason && location )
self.previewUrl( location );
if ( 'logged out' === reason ) {
if ( self.preview ) {
self.preview.destroy();
delete self.preview;
}
self.login().done( self.refresh );
}
if ( 'cheatin' === reason )
self.cheatin();
});
},
login: function() {
var previewer = this,
deferred, messenger, iframe;
if ( this._login )
return this._login;
deferred = $.Deferred();
this._login = deferred.promise();
messenger = new api.Messenger({
channel: 'login',
url: api.settings.url.login
});
iframe = $('<iframe src="' + api.settings.url.login + '" />').appendTo( this.container );
messenger.targetWindow( iframe[0].contentWindow );
messenger.bind( 'login', function() {
iframe.remove();
messenger.destroy();
delete previewer._login;
deferred.resolve();
});
return this._login;
},
cheatin: function() {
$( document.body ).empty().addClass('cheatin').append( '<p>' + api.l10n.cheatin + '</p>' );
}
});
/* =====================================================================
* Ready.
* ===================================================================== */
api.controlConstructor = {
color: api.ColorControl,
upload: api.UploadControl,
image: api.ImageControl
};
$( function() {
api.settings = window._wpCustomizeSettings;
api.l10n = window._wpCustomizeControlsL10n;
// Check if we can run the customizer.
if ( ! api.settings )
return;
// Redirect to the fallback preview if any incompatibilities are found.
if ( ! $.support.postMessage || ( ! $.support.cors && api.settings.isCrossDomain ) )
return window.location = api.settings.url.fallback;
var body = $( document.body ),
overlay = body.children('.wp-full-overlay'),
query, previewer, parent;
// Prevent the form from saving when enter is pressed.
$('#customize-controls').on( 'keydown', function( e ) {
if ( $( e.target ).is('textarea') )
return;
if ( 13 === e.which ) // Enter
e.preventDefault();
});
// Initialize Previewer
previewer = new api.Previewer({
container: '#customize-preview',
form: '#customize-controls',
previewUrl: api.settings.url.preview,
allowedUrls: api.settings.url.allowed,
signature: 'WP_CUSTOMIZER_SIGNATURE'
}, {
nonce: api.settings.nonce,
query: function() {
return {
wp_customize: 'on',
theme: api.settings.theme.stylesheet,
customized: JSON.stringify( api.get() ),
nonce: this.nonce.preview
};
},
save: function() {
var self = this,
query = $.extend( this.query(), {
action: 'customize_save',
nonce: this.nonce.save
}),
request = $.post( api.settings.url.ajax, query );
api.trigger( 'save', request );
body.addClass('saving');
request.always( function() {
body.removeClass('saving');
});
request.done( function( response ) {
// Check if the user is logged out.
if ( '0' === response ) {
self.preview.iframe.hide();
self.login().done( function() {
self.save();
self.preview.iframe.show();
});
return;
}
// Check for cheaters.
if ( '-1' === response ) {
self.cheatin();
return;
}
api.trigger( 'saved' );
});
}
});
// Refresh the nonces if the preview sends updated nonces over.
previewer.bind( 'nonce', function( nonce ) {
$.extend( this.nonce, nonce );
});
$.each( api.settings.settings, function( id, data ) {
api.create( id, id, data.value, {
transport: data.transport,
previewer: previewer
} );
});
$.each( api.settings.controls, function( id, data ) {
var constructor = api.controlConstructor[ data.type ] || api.Control,
control;
control = api.control.add( id, new constructor( id, {
params: data,
previewer: previewer
} ) );
});
// Check if preview url is valid and load the preview frame.
if ( previewer.previewUrl() )
previewer.refresh();
else
previewer.previewUrl( api.settings.url.home );
// Save and activated states
(function() {
var state = new api.Values(),
saved = state.create('saved'),
activated = state.create('activated');
state.bind( 'change', function() {
var save = $('#save'),
back = $('.back');
if ( ! activated() ) {
save.val( api.l10n.activate ).prop( 'disabled', false );
back.text( api.l10n.cancel );
} else if ( saved() ) {
save.val( api.l10n.saved ).prop( 'disabled', true );
back.text( api.l10n.close );
} else {
save.val( api.l10n.save ).prop( 'disabled', false );
back.text( api.l10n.cancel );
}
});
// Set default states.
saved( true );
activated( api.settings.theme.active );
api.bind( 'change', function() {
state('saved').set( false );
});
api.bind( 'saved', function() {
state('saved').set( true );
state('activated').set( true );
});
activated.bind( function( to ) {
if ( to )
api.trigger( 'activated' );
});
// Expose states to the API.
api.state = state;
}());
// Temporary accordion code.
$('.customize-section-title').click( function( event ) {
var clicked = $( this ).parents( '.customize-section' );
if ( clicked.hasClass('cannot-expand') )
return;
$( '.customize-section' ).not( clicked ).removeClass( 'open' );
clicked.toggleClass( 'open' );
event.preventDefault();
});
// Button bindings.
$('#save').click( function( event ) {
previewer.save();
event.preventDefault();
});
$('.collapse-sidebar').click( function( event ) {
overlay.toggleClass( 'collapsed' ).toggleClass( 'expanded' );
event.preventDefault();
});
// Create a potential postMessage connection with the parent frame.
parent = new api.Messenger({
url: api.settings.url.parent,
channel: 'loader'
});
// If we receive a 'back' event, we're inside an iframe.
// Send any clicks to the 'Return' link to the parent page.
parent.bind( 'back', function() {
$('.back').on( 'click.back', function( event ) {
event.preventDefault();
parent.send( 'close' );
});
});
// Pass events through to the parent.
api.bind( 'saved', function() {
parent.send( 'saved' );
});
// When activated, let the loader handle redirecting the page.
// If no loader exists, redirect the page ourselves (if a url exists).
api.bind( 'activated', function() {
if ( parent.targetWindow() )
parent.send( 'activated', api.settings.url.activated );
else if ( api.settings.url.activated )
window.location = api.settings.url.activated;
});
// Initialize the connection with the parent frame.
parent.send( 'ready' );
// Control visibility for default controls
$.each({
'background_image': {
controls: [ 'background_repeat', 'background_position_x', 'background_attachment' ],
callback: function( to ) { return !! to }
},
'show_on_front': {
controls: [ 'page_on_front', 'page_for_posts' ],
callback: function( to ) { return 'page' === to }
},
'header_textcolor': {
controls: [ 'header_textcolor' ],
callback: function( to ) { return 'blank' !== to }
}
}, function( settingId, o ) {
api( settingId, function( setting ) {
$.each( o.controls, function( i, controlId ) {
api.control( controlId, function( control ) {
var visibility = function( to ) {
control.container.toggle( o.callback( to ) );
};
visibility( setting.get() );
setting.bind( visibility );
});
});
});
});
// Juggle the two controls that use header_textcolor
api.control( 'display_header_text', function( control ) {
var last = '';
control.elements[0].unsync( api( 'header_textcolor' ) );
control.element = new api.Element( control.container.find('input') );
control.element.set( 'blank' !== control.setting() );
control.element.bind( function( to ) {
if ( ! to )
last = api( 'header_textcolor' ).get();
control.setting.set( to ? last : 'blank' );
});
control.setting.bind( function( to ) {
control.element.set( 'blank' !== to );
});
});
// Handle header image data
api.control( 'header_image', function( control ) {
control.setting.bind( function( to ) {
if ( to === control.params.removed )
control.settings.data.set( false );
});
control.library.on( 'click', 'a', function( event ) {
control.settings.data.set( $(this).data('customizeHeaderImageData') );
});
control.uploader.success = function( attachment ) {
var data;
api.ImageControl.prototype.success.call( control, attachment );
data = {
attachment_id: attachment.id,
url: attachment.url,
thumbnail_url: attachment.url,
height: attachment.meta.height,
width: attachment.meta.width
};
attachment.element.data( 'customizeHeaderImageData', data );
control.settings.data.set( data );
}
});
api.trigger( 'ready' );
});
})( wp, jQuery ); | JavaScript |
// Password strength meter
function passwordStrength(password1, username, password2) {
var shortPass = 1, badPass = 2, goodPass = 3, strongPass = 4, mismatch = 5, symbolSize = 0, natLog, score;
// password 1 != password 2
if ( (password1 != password2) && password2.length > 0)
return mismatch
//password < 4
if ( password1.length < 4 )
return shortPass
//password1 == username
if ( password1.toLowerCase() == username.toLowerCase() )
return badPass;
if ( password1.match(/[0-9]/) )
symbolSize +=10;
if ( password1.match(/[a-z]/) )
symbolSize +=26;
if ( password1.match(/[A-Z]/) )
symbolSize +=26;
if ( password1.match(/[^a-zA-Z0-9]/) )
symbolSize +=31;
natLog = Math.log( Math.pow(symbolSize, password1.length) );
score = natLog / Math.LN2;
if (score < 40 )
return badPass
if (score < 56 )
return goodPass
return strongPass;
}
| JavaScript |
var imageEdit;
(function($) {
imageEdit = {
iasapi : {},
hold : {},
postid : '',
intval : function(f) {
return f | 0;
},
setDisabled : function(el, s) {
if ( s ) {
el.removeClass('disabled');
$('input', el).removeAttr('disabled');
} else {
el.addClass('disabled');
$('input', el).prop('disabled', true);
}
},
init : function(postid, nonce) {
var t = this, old = $('#image-editor-' + t.postid),
x = t.intval( $('#imgedit-x-' + postid).val() ),
y = t.intval( $('#imgedit-y-' + postid).val() );
if ( t.postid != postid && old.length )
t.close(t.postid);
t.hold['w'] = t.hold['ow'] = x;
t.hold['h'] = t.hold['oh'] = y;
t.hold['xy_ratio'] = x / y;
t.hold['sizer'] = parseFloat( $('#imgedit-sizer-' + postid).val() );
t.postid = postid;
$('#imgedit-response-' + postid).empty();
$('input[type="text"]', '#imgedit-panel-' + postid).keypress(function(e) {
var k = e.keyCode;
if ( 36 < k && k < 41 )
$(this).blur()
if ( 13 == k ) {
e.preventDefault();
e.stopPropagation();
return false;
}
});
},
toggleEditor : function(postid, toggle) {
var wait = $('#imgedit-wait-' + postid);
if ( toggle )
wait.height( $('#imgedit-panel-' + postid).height() ).fadeIn('fast');
else
wait.fadeOut('fast');
},
toggleHelp : function(el) {
$(el).siblings('.imgedit-help').slideToggle('fast');
return false;
},
getTarget : function(postid) {
return $('input[name="imgedit-target-' + postid + '"]:checked', '#imgedit-save-target-' + postid).val() || 'full';
},
scaleChanged : function(postid, x) {
var w = $('#imgedit-scale-width-' + postid), h = $('#imgedit-scale-height-' + postid),
warn = $('#imgedit-scale-warn-' + postid), w1 = '', h1 = '';
if ( x ) {
h1 = (w.val() != '') ? this.intval( w.val() / this.hold['xy_ratio'] ) : '';
h.val( h1 );
} else {
w1 = (h.val() != '') ? this.intval( h.val() * this.hold['xy_ratio'] ) : '';
w.val( w1 );
}
if ( ( h1 && h1 > this.hold['oh'] ) || ( w1 && w1 > this.hold['ow'] ) )
warn.css('visibility', 'visible');
else
warn.css('visibility', 'hidden');
},
getSelRatio : function(postid) {
var x = this.hold['w'], y = this.hold['h'],
X = this.intval( $('#imgedit-crop-width-' + postid).val() ),
Y = this.intval( $('#imgedit-crop-height-' + postid).val() );
if ( X && Y )
return X + ':' + Y;
if ( x && y )
return x + ':' + y;
return '1:1';
},
filterHistory : function(postid, setSize) {
// apply undo state to history
var history = $('#imgedit-history-' + postid).val(), pop, n, o, i, op = [];
if ( history != '' ) {
history = JSON.parse(history);
pop = this.intval( $('#imgedit-undone-' + postid).val() );
if ( pop > 0 ) {
while ( pop > 0 ) {
history.pop();
pop--;
}
}
if ( setSize ) {
if ( !history.length ) {
this.hold['w'] = this.hold['ow'];
this.hold['h'] = this.hold['oh'];
return '';
}
// restore
o = history[history.length - 1];
o = o.c || o.r || o.f || false;
if ( o ) {
this.hold['w'] = o.fw;
this.hold['h'] = o.fh;
}
}
// filter the values
for ( n in history ) {
i = history[n];
if ( i.hasOwnProperty('c') ) {
op[n] = { 'c': { 'x': i.c.x, 'y': i.c.y, 'w': i.c.w, 'h': i.c.h } };
} else if ( i.hasOwnProperty('r') ) {
op[n] = { 'r': i.r.r };
} else if ( i.hasOwnProperty('f') ) {
op[n] = { 'f': i.f.f };
}
}
return JSON.stringify(op);
}
return '';
},
refreshEditor : function(postid, nonce, callback) {
var t = this, data, img;
t.toggleEditor(postid, 1);
data = {
'action': 'imgedit-preview',
'_ajax_nonce': nonce,
'postid': postid,
'history': t.filterHistory(postid, 1),
'rand': t.intval(Math.random() * 1000000)
};
img = $('<img id="image-preview-' + postid + '" />');
img.load( function() {
var max1, max2, parent = $('#imgedit-crop-' + postid), t = imageEdit;
parent.empty().append(img);
// w, h are the new full size dims
max1 = Math.max( t.hold.w, t.hold.h );
max2 = Math.max( $(img).width(), $(img).height() );
t.hold['sizer'] = max1 > max2 ? max2 / max1 : 1;
t.initCrop(postid, img, parent);
t.setCropSelection(postid, 0);
if ( (typeof callback != "unknown") && callback != null )
callback();
if ( $('#imgedit-history-' + postid).val() && $('#imgedit-undone-' + postid).val() == 0 )
$('input.imgedit-submit-btn', '#imgedit-panel-' + postid).removeAttr('disabled');
else
$('input.imgedit-submit-btn', '#imgedit-panel-' + postid).prop('disabled', true);
t.toggleEditor(postid, 0);
}).error(function(){
$('#imgedit-crop-' + postid).empty().append('<div class="error"><p>' + imageEditL10n.error + '</p></div>');
t.toggleEditor(postid, 0);
}).attr('src', ajaxurl + '?' + $.param(data));
},
action : function(postid, nonce, action) {
var t = this, data, w, h, fw, fh;
if ( t.notsaved(postid) )
return false;
data = {
'action': 'image-editor',
'_ajax_nonce': nonce,
'postid': postid
};
if ( 'scale' == action ) {
w = $('#imgedit-scale-width-' + postid),
h = $('#imgedit-scale-height-' + postid),
fw = t.intval(w.val()),
fh = t.intval(h.val());
if ( fw < 1 ) {
w.focus();
return false;
} else if ( fh < 1 ) {
h.focus();
return false;
}
if ( fw == t.hold.ow || fh == t.hold.oh )
return false;
data['do'] = 'scale';
data['fwidth'] = fw;
data['fheight'] = fh;
} else if ( 'restore' == action ) {
data['do'] = 'restore';
} else {
return false;
}
t.toggleEditor(postid, 1);
$.post(ajaxurl, data, function(r) {
$('#image-editor-' + postid).empty().append(r);
t.toggleEditor(postid, 0);
});
},
save : function(postid, nonce) {
var data, target = this.getTarget(postid), history = this.filterHistory(postid, 0);
if ( '' == history )
return false;
this.toggleEditor(postid, 1);
data = {
'action': 'image-editor',
'_ajax_nonce': nonce,
'postid': postid,
'history': history,
'target': target,
'do': 'save'
};
$.post(ajaxurl, data, function(r) {
var ret = JSON.parse(r);
if ( ret.error ) {
$('#imgedit-response-' + postid).html('<div class="error"><p>' + ret.error + '</p><div>');
imageEdit.close(postid);
return;
}
if ( ret.fw && ret.fh )
$('#media-dims-' + postid).html( ret.fw + ' × ' + ret.fh );
if ( ret.thumbnail )
$('.thumbnail', '#thumbnail-head-' + postid).attr('src', ''+ret.thumbnail);
if ( ret.msg )
$('#imgedit-response-' + postid).html('<div class="updated"><p>' + ret.msg + '</p></div>');
imageEdit.close(postid);
});
},
open : function(postid, nonce) {
var data, elem = $('#image-editor-' + postid), head = $('#media-head-' + postid),
btn = $('#imgedit-open-btn-' + postid), spin = btn.siblings('img');
btn.prop('disabled', true);
spin.css('visibility', 'visible');
data = {
'action': 'image-editor',
'_ajax_nonce': nonce,
'postid': postid,
'do': 'open'
};
elem.load(ajaxurl, data, function() {
elem.fadeIn('fast');
head.fadeOut('fast', function(){
btn.removeAttr('disabled');
spin.css('visibility', 'hidden');
});
});
},
imgLoaded : function(postid) {
var img = $('#image-preview-' + postid), parent = $('#imgedit-crop-' + postid);
this.initCrop(postid, img, parent);
this.setCropSelection(postid, 0);
this.toggleEditor(postid, 0);
},
initCrop : function(postid, image, parent) {
var t = this, selW = $('#imgedit-sel-width-' + postid),
selH = $('#imgedit-sel-height-' + postid);
t.iasapi = $(image).imgAreaSelect({
parent: parent,
instance: true,
handles: true,
keys: true,
minWidth: 3,
minHeight: 3,
onInit: function(img, c) {
parent.children().mousedown(function(e){
var ratio = false, sel, defRatio;
if ( e.shiftKey ) {
sel = t.iasapi.getSelection();
defRatio = t.getSelRatio(postid);
ratio = ( sel && sel.width && sel.height ) ? sel.width + ':' + sel.height : defRatio;
}
t.iasapi.setOptions({
aspectRatio: ratio
});
});
},
onSelectStart: function(img, c) {
imageEdit.setDisabled($('#imgedit-crop-sel-' + postid), 1);
},
onSelectEnd: function(img, c) {
imageEdit.setCropSelection(postid, c);
},
onSelectChange: function(img, c) {
var sizer = imageEdit.hold.sizer;
selW.val( imageEdit.round(c.width / sizer) );
selH.val( imageEdit.round(c.height / sizer) );
}
});
},
setCropSelection : function(postid, c) {
var sel, min = $('#imgedit-minthumb-' + postid).val() || '128:128',
sizer = this.hold['sizer'];
min = min.split(':');
c = c || 0;
if ( !c || ( c.width < 3 && c.height < 3 ) ) {
this.setDisabled($('.imgedit-crop', '#imgedit-panel-' + postid), 0);
this.setDisabled($('#imgedit-crop-sel-' + postid), 0);
$('#imgedit-sel-width-' + postid).val('');
$('#imgedit-sel-height-' + postid).val('');
$('#imgedit-selection-' + postid).val('');
return false;
}
if ( c.width < (min[0] * sizer) && c.height < (min[1] * sizer) ) {
this.setDisabled($('.imgedit-crop', '#imgedit-panel-' + postid), 0);
$('#imgedit-selection-' + postid).val('');
return false;
}
sel = { 'x': c.x1, 'y': c.y1, 'w': c.width, 'h': c.height };
this.setDisabled($('.imgedit-crop', '#imgedit-panel-' + postid), 1);
$('#imgedit-selection-' + postid).val( JSON.stringify(sel) );
},
close : function(postid, warn) {
warn = warn || false;
if ( warn && this.notsaved(postid) )
return false;
this.iasapi = {};
this.hold = {};
$('#image-editor-' + postid).fadeOut('fast', function() {
$('#media-head-' + postid).fadeIn('fast');
$(this).empty();
});
},
notsaved : function(postid) {
var h = $('#imgedit-history-' + postid).val(),
history = (h != '') ? JSON.parse(h) : new Array(),
pop = this.intval( $('#imgedit-undone-' + postid).val() );
if ( pop < history.length ) {
if ( confirm( $('#imgedit-leaving-' + postid).html() ) )
return false;
return true;
}
return false;
},
addStep : function(op, postid, nonce) {
var t = this, elem = $('#imgedit-history-' + postid),
history = (elem.val() != '') ? JSON.parse(elem.val()) : new Array(),
undone = $('#imgedit-undone-' + postid),
pop = t.intval(undone.val());
while ( pop > 0 ) {
history.pop();
pop--;
}
undone.val(0); // reset
history.push(op);
elem.val( JSON.stringify(history) );
t.refreshEditor(postid, nonce, function() {
t.setDisabled($('#image-undo-' + postid), true);
t.setDisabled($('#image-redo-' + postid), false);
});
},
rotate : function(angle, postid, nonce, t) {
if ( $(t).hasClass('disabled') )
return false;
this.addStep({ 'r': { 'r': angle, 'fw': this.hold['h'], 'fh': this.hold['w'] }}, postid, nonce);
},
flip : function (axis, postid, nonce, t) {
if ( $(t).hasClass('disabled') )
return false;
this.addStep({ 'f': { 'f': axis, 'fw': this.hold['w'], 'fh': this.hold['h'] }}, postid, nonce);
},
crop : function (postid, nonce, t) {
var sel = $('#imgedit-selection-' + postid).val(),
w = this.intval( $('#imgedit-sel-width-' + postid).val() ),
h = this.intval( $('#imgedit-sel-height-' + postid).val() );
if ( $(t).hasClass('disabled') || sel == '' )
return false;
sel = JSON.parse(sel);
if ( sel.w > 0 && sel.h > 0 && w > 0 && h > 0 ) {
sel['fw'] = w;
sel['fh'] = h;
this.addStep({ 'c': sel }, postid, nonce);
}
},
undo : function (postid, nonce) {
var t = this, button = $('#image-undo-' + postid), elem = $('#imgedit-undone-' + postid),
pop = t.intval( elem.val() ) + 1;
if ( button.hasClass('disabled') )
return;
elem.val(pop);
t.refreshEditor(postid, nonce, function() {
var elem = $('#imgedit-history-' + postid),
history = (elem.val() != '') ? JSON.parse(elem.val()) : new Array();
t.setDisabled($('#image-redo-' + postid), true);
t.setDisabled(button, pop < history.length);
});
},
redo : function(postid, nonce) {
var t = this, button = $('#image-redo-' + postid), elem = $('#imgedit-undone-' + postid),
pop = t.intval( elem.val() ) - 1;
if ( button.hasClass('disabled') )
return;
elem.val(pop);
t.refreshEditor(postid, nonce, function() {
t.setDisabled($('#image-undo-' + postid), true);
t.setDisabled(button, pop > 0);
});
},
setNumSelection : function(postid) {
var sel, elX = $('#imgedit-sel-width-' + postid), elY = $('#imgedit-sel-height-' + postid),
x = this.intval( elX.val() ), y = this.intval( elY.val() ),
img = $('#image-preview-' + postid), imgh = img.height(), imgw = img.width(),
sizer = this.hold['sizer'], x1, y1, x2, y2, ias = this.iasapi;
if ( x < 1 ) {
elX.val('');
return false;
}
if ( y < 1 ) {
elY.val('');
return false;
}
if ( x && y && ( sel = ias.getSelection() ) ) {
x2 = sel.x1 + Math.round( x * sizer );
y2 = sel.y1 + Math.round( y * sizer );
x1 = sel.x1;
y1 = sel.y1;
if ( x2 > imgw ) {
x1 = 0;
x2 = imgw;
elX.val( Math.round( x2 / sizer ) );
}
if ( y2 > imgh ) {
y1 = 0;
y2 = imgh;
elY.val( Math.round( y2 / sizer ) );
}
ias.setSelection( x1, y1, x2, y2 );
ias.update();
this.setCropSelection(postid, ias.getSelection());
}
},
round : function(num) {
var s;
num = Math.round(num);
if ( this.hold.sizer > 0.6 )
return num;
s = num.toString().slice(-1);
if ( '1' == s )
return num - 1;
else if ( '9' == s )
return num + 1;
return num;
},
setRatioSelection : function(postid, n, el) {
var sel, r, x = this.intval( $('#imgedit-crop-width-' + postid).val() ),
y = this.intval( $('#imgedit-crop-height-' + postid).val() ),
h = $('#image-preview-' + postid).height();
if ( !this.intval( $(el).val() ) ) {
$(el).val('');
return;
}
if ( x && y ) {
this.iasapi.setOptions({
aspectRatio: x + ':' + y
});
if ( sel = this.iasapi.getSelection(true) ) {
r = Math.ceil( sel.y1 + ((sel.x2 - sel.x1) / (x / y)) );
if ( r > h ) {
r = h;
if ( n )
$('#imgedit-crop-height-' + postid).val('');
else
$('#imgedit-crop-width-' + postid).val('');
}
this.iasapi.setSelection( sel.x1, sel.y1, sel.x2, r );
this.iasapi.update();
}
}
}
}
})(jQuery);
| JavaScript |
var findPosts;
(function($){
findPosts = {
open : function(af_name, af_val) {
var st = document.documentElement.scrollTop || $(document).scrollTop();
if ( af_name && af_val ) {
$('#affected').attr('name', af_name).val(af_val);
}
$('#find-posts').show().draggable({
handle: '#find-posts-head'
}).css({'top':st + 50 + 'px','left':'50%','marginLeft':'-250px'});
$('#find-posts-input').focus().keyup(function(e){
if (e.which == 27) { findPosts.close(); } // close on Escape
});
return false;
},
close : function() {
$('#find-posts-response').html('');
$('#find-posts').draggable('destroy').hide();
},
send : function() {
var post = {
ps: $('#find-posts-input').val(),
action: 'find_posts',
_ajax_nonce: $('#_ajax_nonce').val(),
post_type: $('input[name="find-posts-what"]:checked').val()
};
$.ajax({
type : 'POST',
url : ajaxurl,
data : post,
success : function(x) { findPosts.show(x); },
error : function(r) { findPosts.error(r); }
});
},
show : function(x) {
if ( typeof(x) == 'string' ) {
this.error({'responseText': x});
return;
}
var r = wpAjax.parseAjaxResponse(x);
if ( r.errors ) {
this.error({'responseText': wpAjax.broken});
}
r = r.responses[0];
$('#find-posts-response').html(r.data);
},
error : function(r) {
var er = r.statusText;
if ( r.responseText ) {
er = r.responseText.replace( /<.[^<>]*?>/g, '' );
}
if ( er ) {
$('#find-posts-response').html(er);
}
}
};
$(document).ready(function() {
$('#find-posts-submit').click(function(e) {
if ( '' == $('#find-posts-response').html() )
e.preventDefault();
});
$( '#find-posts .find-box-search :input' ).keypress( function( event ) {
if ( 13 == event.which ) {
findPosts.send();
return false;
}
} );
$( '#find-posts-search' ).click( findPosts.send );
$( '#find-posts-close' ).click( findPosts.close );
$('#doaction, #doaction2').click(function(e){
$('select[name^="action"]').each(function(){
if ( $(this).val() == 'attach' ) {
e.preventDefault();
findPosts.open();
}
});
});
});
})(jQuery);
| JavaScript |
/**
* WordPress Administration Navigation Menu
* Interface JS functions
*
* @version 2.0.0
*
* @package WordPress
* @subpackage Administration
*/
var wpNavMenu;
(function($) {
var api = wpNavMenu = {
options : {
menuItemDepthPerLevel : 30, // Do not use directly. Use depthToPx and pxToDepth instead.
globalMaxDepth : 11
},
menuList : undefined, // Set in init.
targetList : undefined, // Set in init.
menusChanged : false,
isRTL: !! ( 'undefined' != typeof isRtl && isRtl ),
negateIfRTL: ( 'undefined' != typeof isRtl && isRtl ) ? -1 : 1,
// Functions that run on init.
init : function() {
api.menuList = $('#menu-to-edit');
api.targetList = api.menuList;
this.jQueryExtensions();
this.attachMenuEditListeners();
this.setupInputWithDefaultTitle();
this.attachQuickSearchListeners();
this.attachThemeLocationsListeners();
this.attachTabsPanelListeners();
this.attachUnsavedChangesListener();
if( api.menuList.length ) // If no menu, we're in the + tab.
this.initSortables();
this.initToggles();
this.initTabManager();
},
jQueryExtensions : function() {
// jQuery extensions
$.fn.extend({
menuItemDepth : function() {
var margin = api.isRTL ? this.eq(0).css('margin-right') : this.eq(0).css('margin-left');
return api.pxToDepth( margin && -1 != margin.indexOf('px') ? margin.slice(0, -2) : 0 );
},
updateDepthClass : function(current, prev) {
return this.each(function(){
var t = $(this);
prev = prev || t.menuItemDepth();
$(this).removeClass('menu-item-depth-'+ prev )
.addClass('menu-item-depth-'+ current );
});
},
shiftDepthClass : function(change) {
return this.each(function(){
var t = $(this),
depth = t.menuItemDepth();
$(this).removeClass('menu-item-depth-'+ depth )
.addClass('menu-item-depth-'+ (depth + change) );
});
},
childMenuItems : function() {
var result = $();
this.each(function(){
var t = $(this), depth = t.menuItemDepth(), next = t.next();
while( next.length && next.menuItemDepth() > depth ) {
result = result.add( next );
next = next.next();
}
});
return result;
},
updateParentMenuItemDBId : function() {
return this.each(function(){
var item = $(this),
input = item.find('.menu-item-data-parent-id'),
depth = item.menuItemDepth(),
parent = item.prev();
if( depth == 0 ) { // Item is on the top level, has no parent
input.val(0);
} else { // Find the parent item, and retrieve its object id.
while( ! parent[0] || ! parent[0].className || -1 == parent[0].className.indexOf('menu-item') || ( parent.menuItemDepth() != depth - 1 ) )
parent = parent.prev();
input.val( parent.find('.menu-item-data-db-id').val() );
}
});
},
hideAdvancedMenuItemFields : function() {
return this.each(function(){
var that = $(this);
$('.hide-column-tog').not(':checked').each(function(){
that.find('.field-' + $(this).val() ).addClass('hidden-field');
});
});
},
/**
* Adds selected menu items to the menu.
*
* @param jQuery metabox The metabox jQuery object.
*/
addSelectedToMenu : function(processMethod) {
if ( 0 == $('#menu-to-edit').length ) {
return false;
}
return this.each(function() {
var t = $(this), menuItems = {},
checkboxes = t.find('.tabs-panel-active .categorychecklist li input:checked'),
re = new RegExp('menu-item\\[(\[^\\]\]*)');
processMethod = processMethod || api.addMenuItemToBottom;
// If no items are checked, bail.
if ( !checkboxes.length )
return false;
// Show the ajax spinner
t.find('img.waiting').show();
// Retrieve menu item data
$(checkboxes).each(function(){
var t = $(this),
listItemDBIDMatch = re.exec( t.attr('name') ),
listItemDBID = 'undefined' == typeof listItemDBIDMatch[1] ? 0 : parseInt(listItemDBIDMatch[1], 10);
if ( this.className && -1 != this.className.indexOf('add-to-top') )
processMethod = api.addMenuItemToTop;
menuItems[listItemDBID] = t.closest('li').getItemData( 'add-menu-item', listItemDBID );
});
// Add the items
api.addItemToMenu(menuItems, processMethod, function(){
// Deselect the items and hide the ajax spinner
checkboxes.removeAttr('checked');
t.find('img.waiting').hide();
});
});
},
getItemData : function( itemType, id ) {
itemType = itemType || 'menu-item';
var itemData = {}, i,
fields = [
'menu-item-db-id',
'menu-item-object-id',
'menu-item-object',
'menu-item-parent-id',
'menu-item-position',
'menu-item-type',
'menu-item-title',
'menu-item-url',
'menu-item-description',
'menu-item-attr-title',
'menu-item-target',
'menu-item-classes',
'menu-item-xfn'
];
if( !id && itemType == 'menu-item' ) {
id = this.find('.menu-item-data-db-id').val();
}
if( !id ) return itemData;
this.find('input').each(function() {
var field;
i = fields.length;
while ( i-- ) {
if( itemType == 'menu-item' )
field = fields[i] + '[' + id + ']';
else if( itemType == 'add-menu-item' )
field = 'menu-item[' + id + '][' + fields[i] + ']';
if (
this.name &&
field == this.name
) {
itemData[fields[i]] = this.value;
}
}
});
return itemData;
},
setItemData : function( itemData, itemType, id ) { // Can take a type, such as 'menu-item', or an id.
itemType = itemType || 'menu-item';
if( !id && itemType == 'menu-item' ) {
id = $('.menu-item-data-db-id', this).val();
}
if( !id ) return this;
this.find('input').each(function() {
var t = $(this), field;
$.each( itemData, function( attr, val ) {
if( itemType == 'menu-item' )
field = attr + '[' + id + ']';
else if( itemType == 'add-menu-item' )
field = 'menu-item[' + id + '][' + attr + ']';
if ( field == t.attr('name') ) {
t.val( val );
}
});
});
return this;
}
});
},
initToggles : function() {
// init postboxes
postboxes.add_postbox_toggles('nav-menus');
// adjust columns functions for menus UI
columns.useCheckboxesForHidden();
columns.checked = function(field) {
$('.field-' + field).removeClass('hidden-field');
}
columns.unchecked = function(field) {
$('.field-' + field).addClass('hidden-field');
}
// hide fields
api.menuList.hideAdvancedMenuItemFields();
},
initSortables : function() {
var currentDepth = 0, originalDepth, minDepth, maxDepth,
prev, next, prevBottom, nextThreshold, helperHeight, transport,
menuEdge = api.menuList.offset().left,
body = $('body'), maxChildDepth,
menuMaxDepth = initialMenuMaxDepth();
// Use the right edge if RTL.
menuEdge += api.isRTL ? api.menuList.width() : 0;
api.menuList.sortable({
handle: '.menu-item-handle',
placeholder: 'sortable-placeholder',
start: function(e, ui) {
var height, width, parent, children, tempHolder;
// handle placement for rtl orientation
if ( api.isRTL )
ui.item[0].style.right = 'auto';
transport = ui.item.children('.menu-item-transport');
// Set depths. currentDepth must be set before children are located.
originalDepth = ui.item.menuItemDepth();
updateCurrentDepth(ui, originalDepth);
// Attach child elements to parent
// Skip the placeholder
parent = ( ui.item.next()[0] == ui.placeholder[0] ) ? ui.item.next() : ui.item;
children = parent.childMenuItems();
transport.append( children );
// Update the height of the placeholder to match the moving item.
height = transport.outerHeight();
// If there are children, account for distance between top of children and parent
height += ( height > 0 ) ? (ui.placeholder.css('margin-top').slice(0, -2) * 1) : 0;
height += ui.helper.outerHeight();
helperHeight = height;
height -= 2; // Subtract 2 for borders
ui.placeholder.height(height);
// Update the width of the placeholder to match the moving item.
maxChildDepth = originalDepth;
children.each(function(){
var depth = $(this).menuItemDepth();
maxChildDepth = (depth > maxChildDepth) ? depth : maxChildDepth;
});
width = ui.helper.find('.menu-item-handle').outerWidth(); // Get original width
width += api.depthToPx(maxChildDepth - originalDepth); // Account for children
width -= 2; // Subtract 2 for borders
ui.placeholder.width(width);
// Update the list of menu items.
tempHolder = ui.placeholder.next();
tempHolder.css( 'margin-top', helperHeight + 'px' ); // Set the margin to absorb the placeholder
ui.placeholder.detach(); // detach or jQuery UI will think the placeholder is a menu item
$(this).sortable( "refresh" ); // The children aren't sortable. We should let jQ UI know.
ui.item.after( ui.placeholder ); // reattach the placeholder.
tempHolder.css('margin-top', 0); // reset the margin
// Now that the element is complete, we can update...
updateSharedVars(ui);
},
stop: function(e, ui) {
var children, depthChange = currentDepth - originalDepth;
// Return child elements to the list
children = transport.children().insertAfter(ui.item);
// Update depth classes
if( depthChange != 0 ) {
ui.item.updateDepthClass( currentDepth );
children.shiftDepthClass( depthChange );
updateMenuMaxDepth( depthChange );
}
// Register a change
api.registerChange();
// Update the item data.
ui.item.updateParentMenuItemDBId();
// address sortable's incorrectly-calculated top in opera
ui.item[0].style.top = 0;
// handle drop placement for rtl orientation
if ( api.isRTL ) {
ui.item[0].style.left = 'auto';
ui.item[0].style.right = 0;
}
// The width of the tab bar might have changed. Just in case.
api.refreshMenuTabs( true );
},
change: function(e, ui) {
// Make sure the placeholder is inside the menu.
// Otherwise fix it, or we're in trouble.
if( ! ui.placeholder.parent().hasClass('menu') )
(prev.length) ? prev.after( ui.placeholder ) : api.menuList.prepend( ui.placeholder );
updateSharedVars(ui);
},
sort: function(e, ui) {
var offset = ui.helper.offset(),
edge = api.isRTL ? offset.left + ui.helper.width() : offset.left,
depth = api.negateIfRTL * api.pxToDepth( edge - menuEdge );
// Check and correct if depth is not within range.
// Also, if the dragged element is dragged upwards over
// an item, shift the placeholder to a child position.
if ( depth > maxDepth || offset.top < prevBottom ) depth = maxDepth;
else if ( depth < minDepth ) depth = minDepth;
if( depth != currentDepth )
updateCurrentDepth(ui, depth);
// If we overlap the next element, manually shift downwards
if( nextThreshold && offset.top + helperHeight > nextThreshold ) {
next.after( ui.placeholder );
updateSharedVars( ui );
$(this).sortable( "refreshPositions" );
}
}
});
function updateSharedVars(ui) {
var depth;
prev = ui.placeholder.prev();
next = ui.placeholder.next();
// Make sure we don't select the moving item.
if( prev[0] == ui.item[0] ) prev = prev.prev();
if( next[0] == ui.item[0] ) next = next.next();
prevBottom = (prev.length) ? prev.offset().top + prev.height() : 0;
nextThreshold = (next.length) ? next.offset().top + next.height() / 3 : 0;
minDepth = (next.length) ? next.menuItemDepth() : 0;
if( prev.length )
maxDepth = ( (depth = prev.menuItemDepth() + 1) > api.options.globalMaxDepth ) ? api.options.globalMaxDepth : depth;
else
maxDepth = 0;
}
function updateCurrentDepth(ui, depth) {
ui.placeholder.updateDepthClass( depth, currentDepth );
currentDepth = depth;
}
function initialMenuMaxDepth() {
if( ! body[0].className ) return 0;
var match = body[0].className.match(/menu-max-depth-(\d+)/);
return match && match[1] ? parseInt(match[1]) : 0;
}
function updateMenuMaxDepth( depthChange ) {
var depth, newDepth = menuMaxDepth;
if ( depthChange === 0 ) {
return;
} else if ( depthChange > 0 ) {
depth = maxChildDepth + depthChange;
if( depth > menuMaxDepth )
newDepth = depth;
} else if ( depthChange < 0 && maxChildDepth == menuMaxDepth ) {
while( ! $('.menu-item-depth-' + newDepth, api.menuList).length && newDepth > 0 )
newDepth--;
}
// Update the depth class.
body.removeClass( 'menu-max-depth-' + menuMaxDepth ).addClass( 'menu-max-depth-' + newDepth );
menuMaxDepth = newDepth;
}
},
attachMenuEditListeners : function() {
var that = this;
$('#update-nav-menu').bind('click', function(e) {
if ( e.target && e.target.className ) {
if ( -1 != e.target.className.indexOf('item-edit') ) {
return that.eventOnClickEditLink(e.target);
} else if ( -1 != e.target.className.indexOf('menu-save') ) {
return that.eventOnClickMenuSave(e.target);
} else if ( -1 != e.target.className.indexOf('menu-delete') ) {
return that.eventOnClickMenuDelete(e.target);
} else if ( -1 != e.target.className.indexOf('item-delete') ) {
return that.eventOnClickMenuItemDelete(e.target);
} else if ( -1 != e.target.className.indexOf('item-cancel') ) {
return that.eventOnClickCancelLink(e.target);
}
}
});
$('#add-custom-links input[type="text"]').keypress(function(e){
if ( e.keyCode === 13 ) {
e.preventDefault();
$("#submit-customlinkdiv").click();
}
});
},
/**
* An interface for managing default values for input elements
* that is both JS and accessibility-friendly.
*
* Input elements that add the class 'input-with-default-title'
* will have their values set to the provided HTML title when empty.
*/
setupInputWithDefaultTitle : function() {
var name = 'input-with-default-title';
$('.' + name).each( function(){
var $t = $(this), title = $t.attr('title'), val = $t.val();
$t.data( name, title );
if( '' == val ) $t.val( title );
else if ( title == val ) return;
else $t.removeClass( name );
}).focus( function(){
var $t = $(this);
if( $t.val() == $t.data(name) )
$t.val('').removeClass( name );
}).blur( function(){
var $t = $(this);
if( '' == $t.val() )
$t.addClass( name ).val( $t.data(name) );
});
},
attachThemeLocationsListeners : function() {
var loc = $('#nav-menu-theme-locations'), params = {};
params['action'] = 'menu-locations-save';
params['menu-settings-column-nonce'] = $('#menu-settings-column-nonce').val();
loc.find('input[type="submit"]').click(function() {
loc.find('select').each(function() {
params[this.name] = $(this).val();
});
loc.find('.waiting').show();
$.post( ajaxurl, params, function(r) {
loc.find('.waiting').hide();
});
return false;
});
},
attachQuickSearchListeners : function() {
var searchTimer;
$('.quick-search').keypress(function(e){
var t = $(this);
if( 13 == e.which ) {
api.updateQuickSearchResults( t );
return false;
}
if( searchTimer ) clearTimeout(searchTimer);
searchTimer = setTimeout(function(){
api.updateQuickSearchResults( t );
}, 400);
}).attr('autocomplete','off');
},
updateQuickSearchResults : function(input) {
var panel, params,
minSearchLength = 2,
q = input.val();
if( q.length < minSearchLength ) return;
panel = input.parents('.tabs-panel');
params = {
'action': 'menu-quick-search',
'response-format': 'markup',
'menu': $('#menu').val(),
'menu-settings-column-nonce': $('#menu-settings-column-nonce').val(),
'q': q,
'type': input.attr('name')
};
$('img.waiting', panel).show();
$.post( ajaxurl, params, function(menuMarkup) {
api.processQuickSearchQueryResponse(menuMarkup, params, panel);
});
},
addCustomLink : function( processMethod ) {
var url = $('#custom-menu-item-url').val(),
label = $('#custom-menu-item-name').val();
processMethod = processMethod || api.addMenuItemToBottom;
if ( '' == url || 'http://' == url )
return false;
// Show the ajax spinner
$('.customlinkdiv img.waiting').show();
this.addLinkToMenu( url, label, processMethod, function() {
// Remove the ajax spinner
$('.customlinkdiv img.waiting').hide();
// Set custom link form back to defaults
$('#custom-menu-item-name').val('').blur();
$('#custom-menu-item-url').val('http://');
});
},
addLinkToMenu : function(url, label, processMethod, callback) {
processMethod = processMethod || api.addMenuItemToBottom;
callback = callback || function(){};
api.addItemToMenu({
'-1': {
'menu-item-type': 'custom',
'menu-item-url': url,
'menu-item-title': label
}
}, processMethod, callback);
},
addItemToMenu : function(menuItem, processMethod, callback) {
var menu = $('#menu').val(),
nonce = $('#menu-settings-column-nonce').val();
processMethod = processMethod || function(){};
callback = callback || function(){};
params = {
'action': 'add-menu-item',
'menu': menu,
'menu-settings-column-nonce': nonce,
'menu-item': menuItem
};
$.post( ajaxurl, params, function(menuMarkup) {
var ins = $('#menu-instructions');
processMethod(menuMarkup, params);
if( ! ins.hasClass('menu-instructions-inactive') && ins.siblings().length )
ins.addClass('menu-instructions-inactive');
callback();
});
},
/**
* Process the add menu item request response into menu list item.
*
* @param string menuMarkup The text server response of menu item markup.
* @param object req The request arguments.
*/
addMenuItemToBottom : function( menuMarkup, req ) {
$(menuMarkup).hideAdvancedMenuItemFields().appendTo( api.targetList );
},
addMenuItemToTop : function( menuMarkup, req ) {
$(menuMarkup).hideAdvancedMenuItemFields().prependTo( api.targetList );
},
attachUnsavedChangesListener : function() {
$('#menu-management input, #menu-management select, #menu-management, #menu-management textarea').change(function(){
api.registerChange();
});
if ( 0 != $('#menu-to-edit').length ) {
window.onbeforeunload = function(){
if ( api.menusChanged )
return navMenuL10n.saveAlert;
};
} else {
// Make the post boxes read-only, as they can't be used yet
$('#menu-settings-column').find('input,select').prop('disabled', true).end().find('a').attr('href', '#').unbind('click');
}
},
registerChange : function() {
api.menusChanged = true;
},
attachTabsPanelListeners : function() {
$('#menu-settings-column').bind('click', function(e) {
var selectAreaMatch, panelId, wrapper, items,
target = $(e.target);
if ( target.hasClass('nav-tab-link') ) {
panelId = /#(.*)$/.exec(e.target.href);
if ( panelId && panelId[1] )
panelId = panelId[1]
else
return false;
wrapper = target.parents('.inside').first();
// upon changing tabs, we want to uncheck all checkboxes
$('input', wrapper).removeAttr('checked');
$('.tabs-panel-active', wrapper).removeClass('tabs-panel-active').addClass('tabs-panel-inactive');
$('#' + panelId, wrapper).removeClass('tabs-panel-inactive').addClass('tabs-panel-active');
$('.tabs', wrapper).removeClass('tabs');
target.parent().addClass('tabs');
// select the search bar
$('.quick-search', wrapper).focus();
return false;
} else if ( target.hasClass('select-all') ) {
selectAreaMatch = /#(.*)$/.exec(e.target.href);
if ( selectAreaMatch && selectAreaMatch[1] ) {
items = $('#' + selectAreaMatch[1] + ' .tabs-panel-active .menu-item-title input');
if( items.length === items.filter(':checked').length )
items.removeAttr('checked');
else
items.prop('checked', true);
return false;
}
} else if ( target.hasClass('submit-add-to-menu') ) {
api.registerChange();
if ( e.target.id && 'submit-customlinkdiv' == e.target.id )
api.addCustomLink( api.addMenuItemToBottom );
else if ( e.target.id && -1 != e.target.id.indexOf('submit-') )
$('#' + e.target.id.replace(/submit-/, '')).addSelectedToMenu( api.addMenuItemToBottom );
return false;
} else if ( target.hasClass('page-numbers') ) {
$.post( ajaxurl, e.target.href.replace(/.*\?/, '').replace(/action=([^&]*)/, '') + '&action=menu-get-metabox',
function( resp ) {
if ( -1 == resp.indexOf('replace-id') )
return;
var metaBoxData = $.parseJSON(resp),
toReplace = document.getElementById(metaBoxData['replace-id']),
placeholder = document.createElement('div'),
wrap = document.createElement('div');
if ( ! metaBoxData['markup'] || ! toReplace )
return;
wrap.innerHTML = metaBoxData['markup'] ? metaBoxData['markup'] : '';
toReplace.parentNode.insertBefore( placeholder, toReplace );
placeholder.parentNode.removeChild( toReplace );
placeholder.parentNode.insertBefore( wrap, placeholder );
placeholder.parentNode.removeChild( placeholder );
}
);
return false;
}
});
},
initTabManager : function() {
var fixed = $('.nav-tabs-wrapper'),
fluid = fixed.children('.nav-tabs'),
active = fluid.children('.nav-tab-active'),
tabs = fluid.children('.nav-tab'),
tabsWidth = 0,
fixedRight, fixedLeft,
arrowLeft, arrowRight, resizeTimer, css = {},
marginFluid = api.isRTL ? 'margin-right' : 'margin-left',
marginFixed = api.isRTL ? 'margin-left' : 'margin-right',
msPerPx = 2;
/**
* Refreshes the menu tabs.
* Will show and hide arrows where necessary.
* Scrolls to the active tab by default.
*
* @param savePosition {boolean} Optional. Prevents scrolling so
* that the current position is maintained. Default false.
**/
api.refreshMenuTabs = function( savePosition ) {
var fixedWidth = fixed.width(),
margin = 0, css = {};
fixedLeft = fixed.offset().left;
fixedRight = fixedLeft + fixedWidth;
if( !savePosition )
active.makeTabVisible();
// Prevent space from building up next to the last tab if there's more to show
if( tabs.last().isTabVisible() ) {
margin = fixed.width() - tabsWidth;
margin = margin > 0 ? 0 : margin;
css[marginFluid] = margin + 'px';
fluid.animate( css, 100, "linear" );
}
// Show the arrows only when necessary
if( fixedWidth > tabsWidth )
arrowLeft.add( arrowRight ).hide();
else
arrowLeft.add( arrowRight ).show();
}
$.fn.extend({
makeTabVisible : function() {
var t = this.eq(0), left, right, css = {}, shift = 0;
if( ! t.length ) return this;
left = t.offset().left;
right = left + t.outerWidth();
if( right > fixedRight )
shift = fixedRight - right;
else if ( left < fixedLeft )
shift = fixedLeft - left;
if( ! shift ) return this;
css[marginFluid] = "+=" + api.negateIfRTL * shift + 'px';
fluid.animate( css, Math.abs( shift ) * msPerPx, "linear" );
return this;
},
isTabVisible : function() {
var t = this.eq(0),
left = t.offset().left,
right = left + t.outerWidth();
return ( right <= fixedRight && left >= fixedLeft ) ? true : false;
}
});
// Find the width of all tabs
tabs.each(function(){
tabsWidth += $(this).outerWidth(true);
});
// Set up fixed margin for overflow, unset padding
css['padding'] = 0;
css[marginFixed] = (-1 * tabsWidth) + 'px';
fluid.css( css );
// Build tab navigation
arrowLeft = $('<div class="nav-tabs-arrow nav-tabs-arrow-left"><a>«</a></div>');
arrowRight = $('<div class="nav-tabs-arrow nav-tabs-arrow-right"><a>»</a></div>');
// Attach to the document
fixed.wrap('<div class="nav-tabs-nav"/>').parent().prepend( arrowLeft ).append( arrowRight );
// Set the menu tabs
api.refreshMenuTabs();
// Make sure the tabs reset on resize
$(window).resize(function() {
if( resizeTimer ) clearTimeout(resizeTimer);
resizeTimer = setTimeout( api.refreshMenuTabs, 200);
});
// Build arrow functions
$.each([{
arrow : arrowLeft,
next : "next",
last : "first",
operator : "+="
},{
arrow : arrowRight,
next : "prev",
last : "last",
operator : "-="
}], function(){
var that = this;
this.arrow.mousedown(function(){
var marginFluidVal = Math.abs( parseInt( fluid.css(marginFluid) ) ),
shift = marginFluidVal,
css = {};
if( "-=" == that.operator )
shift = Math.abs( tabsWidth - fixed.width() ) - marginFluidVal;
if( ! shift ) return;
css[marginFluid] = that.operator + shift + 'px';
fluid.animate( css, shift * msPerPx, "linear" );
}).mouseup(function(){
var tab, next;
fluid.stop(true);
tab = tabs[that.last]();
while( (next = tab[that.next]()) && next.length && ! next.isTabVisible() ) {
tab = next;
}
tab.makeTabVisible();
});
});
},
eventOnClickEditLink : function(clickedEl) {
var settings, item,
matchedSection = /#(.*)$/.exec(clickedEl.href);
if ( matchedSection && matchedSection[1] ) {
settings = $('#'+matchedSection[1]);
item = settings.parent();
if( 0 != item.length ) {
if( item.hasClass('menu-item-edit-inactive') ) {
if( ! settings.data('menu-item-data') ) {
settings.data( 'menu-item-data', settings.getItemData() );
}
settings.slideDown('fast');
item.removeClass('menu-item-edit-inactive')
.addClass('menu-item-edit-active');
} else {
settings.slideUp('fast');
item.removeClass('menu-item-edit-active')
.addClass('menu-item-edit-inactive');
}
return false;
}
}
},
eventOnClickCancelLink : function(clickedEl) {
var settings = $(clickedEl).closest('.menu-item-settings');
settings.setItemData( settings.data('menu-item-data') );
return false;
},
eventOnClickMenuSave : function(clickedEl) {
var locs = '',
menuName = $('#menu-name'),
menuNameVal = menuName.val();
// Cancel and warn if invalid menu name
if( !menuNameVal || menuNameVal == menuName.attr('title') || !menuNameVal.replace(/\s+/, '') ) {
menuName.parent().addClass('form-invalid');
return false;
}
// Copy menu theme locations
$('#nav-menu-theme-locations select').each(function() {
locs += '<input type="hidden" name="' + this.name + '" value="' + $(this).val() + '" />';
});
$('#update-nav-menu').append( locs );
// Update menu item position data
api.menuList.find('.menu-item-data-position').val( function(index) { return index + 1; } );
window.onbeforeunload = null;
return true;
},
eventOnClickMenuDelete : function(clickedEl) {
// Delete warning AYS
if ( confirm( navMenuL10n.warnDeleteMenu ) ) {
window.onbeforeunload = null;
return true;
}
return false;
},
eventOnClickMenuItemDelete : function(clickedEl) {
var itemID = parseInt(clickedEl.id.replace('delete-', ''), 10);
api.removeMenuItem( $('#menu-item-' + itemID) );
api.registerChange();
return false;
},
/**
* Process the quick search response into a search result
*
* @param string resp The server response to the query.
* @param object req The request arguments.
* @param jQuery panel The tabs panel we're searching in.
*/
processQuickSearchQueryResponse : function(resp, req, panel) {
var matched, newID,
takenIDs = {},
form = document.getElementById('nav-menu-meta'),
pattern = new RegExp('menu-item\\[(\[^\\]\]*)', 'g'),
$items = $('<div>').html(resp).find('li'),
$item;
if( ! $items.length ) {
$('.categorychecklist', panel).html( '<li><p>' + navMenuL10n.noResultsFound + '</p></li>' );
$('img.waiting', panel).hide();
return;
}
$items.each(function(){
$item = $(this);
// make a unique DB ID number
matched = pattern.exec($item.html());
if ( matched && matched[1] ) {
newID = matched[1];
while( form.elements['menu-item[' + newID + '][menu-item-type]'] || takenIDs[ newID ] ) {
newID--;
}
takenIDs[newID] = true;
if ( newID != matched[1] ) {
$item.html( $item.html().replace(new RegExp(
'menu-item\\[' + matched[1] + '\\]', 'g'),
'menu-item[' + newID + ']'
) );
}
}
});
$('.categorychecklist', panel).html( $items );
$('img.waiting', panel).hide();
},
removeMenuItem : function(el) {
var children = el.childMenuItems();
el.addClass('deleting').animate({
opacity : 0,
height: 0
}, 350, function() {
var ins = $('#menu-instructions');
el.remove();
children.shiftDepthClass(-1).updateParentMenuItemDBId();
if( ! ins.siblings().length )
ins.removeClass('menu-instructions-inactive');
});
},
depthToPx : function(depth) {
return depth * api.options.menuItemDepthPerLevel;
},
pxToDepth : function(px) {
return Math.floor(px / api.options.menuItemDepthPerLevel);
}
};
$(document).ready(function(){ wpNavMenu.init(); });
})(jQuery);
| JavaScript |
/**
* PubSub
*
* A lightweight publish/subscribe implementation.
* Private use only!
*/
var PubSub, fullscreen, wptitlehint;
PubSub = function() {
this.topics = {};
};
PubSub.prototype.subscribe = function( topic, callback ) {
if ( ! this.topics[ topic ] )
this.topics[ topic ] = [];
this.topics[ topic ].push( callback );
return callback;
};
PubSub.prototype.unsubscribe = function( topic, callback ) {
var i, l,
topics = this.topics[ topic ];
if ( ! topics )
return callback || [];
// Clear matching callbacks
if ( callback ) {
for ( i = 0, l = topics.length; i < l; i++ ) {
if ( callback == topics[i] )
topics.splice( i, 1 );
}
return callback;
// Clear all callbacks
} else {
this.topics[ topic ] = [];
return topics;
}
};
PubSub.prototype.publish = function( topic, args ) {
var i, l, broken,
topics = this.topics[ topic ];
if ( ! topics )
return;
args = args || [];
for ( i = 0, l = topics.length; i < l; i++ ) {
broken = ( topics[i].apply( null, args ) === false || broken );
}
return ! broken;
};
/**
* Distraction Free Writing
* (wp-fullscreen)
*
* Access the API globally using the fullscreen variable.
*/
(function($){
var api, ps, bounder, s;
// Initialize the fullscreen/api object
fullscreen = api = {};
// Create the PubSub (publish/subscribe) interface.
ps = api.pubsub = new PubSub();
timer = 0;
block = false;
s = api.settings = { // Settings
visible : false,
mode : 'tinymce',
editor_id : 'content',
title_id : '',
timer : 0,
toolbar_shown : false
}
/**
* Bounder
*
* Creates a function that publishes start/stop topics.
* Used to throttle events.
*/
bounder = api.bounder = function( start, stop, delay, e ) {
var y, top;
delay = delay || 1250;
if ( e ) {
y = e.pageY || e.clientY || e.offsetY;
top = $(document).scrollTop();
if ( !e.isDefaultPrevented ) // test if e ic jQuery normalized
y = 135 + y;
if ( y - top > 120 )
return;
}
if ( block )
return;
block = true;
setTimeout( function() {
block = false;
}, 400 );
if ( s.timer )
clearTimeout( s.timer );
else
ps.publish( start );
function timed() {
ps.publish( stop );
s.timer = 0;
}
s.timer = setTimeout( timed, delay );
};
/**
* on()
*
* Turns fullscreen on.
*
* @param string mode Optional. Switch to the given mode before opening.
*/
api.on = function() {
if ( s.visible )
return;
// Settings can be added or changed by defining "wp_fullscreen_settings" JS object.
if ( typeof(wp_fullscreen_settings) == 'object' )
$.extend( s, wp_fullscreen_settings );
s.editor_id = wpActiveEditor || 'content';
if ( $('input#title').length && s.editor_id == 'content' )
s.title_id = 'title';
else if ( $('input#' + s.editor_id + '-title').length ) // the title input field should have [editor_id]-title HTML ID to be auto detected
s.title_id = s.editor_id + '-title';
else
$('#wp-fullscreen-title, #wp-fullscreen-title-prompt-text').hide();
s.mode = $('#' + s.editor_id).is(':hidden') ? 'tinymce' : 'html';
s.qt_canvas = $('#' + s.editor_id).get(0);
if ( ! s.element )
api.ui.init();
s.is_mce_on = s.has_tinymce && typeof( tinyMCE.get(s.editor_id) ) != 'undefined';
api.ui.fade( 'show', 'showing', 'shown' );
};
/**
* off()
*
* Turns fullscreen off.
*/
api.off = function() {
if ( ! s.visible )
return;
api.ui.fade( 'hide', 'hiding', 'hidden' );
};
/**
* switchmode()
*
* @return string - The current mode.
*
* @param string to - The fullscreen mode to switch to.
* @event switchMode
* @eventparam string to - The new mode.
* @eventparam string from - The old mode.
*/
api.switchmode = function( to ) {
var from = s.mode;
if ( ! to || ! s.visible || ! s.has_tinymce )
return from;
// Don't switch if the mode is the same.
if ( from == to )
return from;
ps.publish( 'switchMode', [ from, to ] );
s.mode = to;
ps.publish( 'switchedMode', [ from, to ] );
return to;
};
/**
* General
*/
api.save = function() {
var hidden = $('#hiddenaction'), old = hidden.val(), spinner = $('#wp-fullscreen-save img'),
message = $('#wp-fullscreen-save span');
spinner.show();
api.savecontent();
hidden.val('wp-fullscreen-save-post');
$.post( ajaxurl, $('form#post').serialize(), function(r){
spinner.hide();
message.show();
setTimeout( function(){
message.fadeOut(1000);
}, 3000 );
if ( r.last_edited )
$('#wp-fullscreen-save input').attr( 'title', r.last_edited );
}, 'json');
hidden.val(old);
}
api.savecontent = function() {
var ed, content;
if ( s.title_id )
$('#' + s.title_id).val( $('#wp-fullscreen-title').val() );
if ( s.mode === 'tinymce' && (ed = tinyMCE.get('wp_mce_fullscreen')) ) {
content = ed.save();
} else {
content = $('#wp_mce_fullscreen').val();
}
$('#' + s.editor_id).val( content );
$(document).triggerHandler('wpcountwords', [ content ]);
}
set_title_hint = function( title ) {
if ( ! title.val().length )
title.siblings('label').css( 'visibility', '' );
else
title.siblings('label').css( 'visibility', 'hidden' );
}
api.dfw_width = function(n) {
var el = $('#wp-fullscreen-wrap'), w = el.width();
if ( !n ) { // reset to theme width
el.width( $('#wp-fullscreen-central-toolbar').width() );
deleteUserSetting('dfw_width');
return;
}
w = n + w;
if ( w < 200 || w > 1200 ) // sanity check
return;
el.width( w );
setUserSetting('dfw_width', w);
}
ps.subscribe( 'showToolbar', function() {
s.toolbars.removeClass('fade-1000').addClass('fade-300');
api.fade.In( s.toolbars, 300, function(){ ps.publish('toolbarShown'); }, true );
$('#wp-fullscreen-body').addClass('wp-fullscreen-focus');
s.toolbar_shown = true;
});
ps.subscribe( 'hideToolbar', function() {
s.toolbars.removeClass('fade-300').addClass('fade-1000');
api.fade.Out( s.toolbars, 1000, function(){ ps.publish('toolbarHidden'); }, true );
$('#wp-fullscreen-body').removeClass('wp-fullscreen-focus');
});
ps.subscribe( 'toolbarShown', function() {
s.toolbars.removeClass('fade-300');
});
ps.subscribe( 'toolbarHidden', function() {
s.toolbars.removeClass('fade-1000');
s.toolbar_shown = false;
});
ps.subscribe( 'show', function() { // This event occurs before the overlay blocks the UI.
var title;
if ( s.title_id ) {
title = $('#wp-fullscreen-title').val( $('#' + s.title_id).val() );
set_title_hint( title );
}
$('#wp-fullscreen-save input').attr( 'title', $('#last-edit').text() );
s.textarea_obj.value = s.qt_canvas.value;
if ( s.has_tinymce && s.mode === 'tinymce' )
tinyMCE.execCommand('wpFullScreenInit');
s.orig_y = $(window).scrollTop();
});
ps.subscribe( 'showing', function() { // This event occurs while the DFW overlay blocks the UI.
$( document.body ).addClass( 'fullscreen-active' );
api.refresh_buttons();
$( document ).bind( 'mousemove.fullscreen', function(e) { bounder( 'showToolbar', 'hideToolbar', 2000, e ); } );
bounder( 'showToolbar', 'hideToolbar', 2000 );
api.bind_resize();
setTimeout( api.resize_textarea, 200 );
// scroll to top so the user is not disoriented
scrollTo(0, 0);
// needed it for IE7 and compat mode
$('#wpadminbar').hide();
});
ps.subscribe( 'shown', function() { // This event occurs after the DFW overlay is shown
var interim_init;
s.visible = true;
// init the standard TinyMCE instance if missing
if ( s.has_tinymce && ! s.is_mce_on ) {
interim_init = function(mce, ed) {
var el = ed.getElement(), old_val = el.value, settings = tinyMCEPreInit.mceInit[s.editor_id];
if ( settings && settings.wpautop && typeof(switchEditors) != 'undefined' )
el.value = switchEditors.wpautop( el.value );
ed.onInit.add(function(ed) {
ed.hide();
ed.getElement().value = old_val;
tinymce.onAddEditor.remove(interim_init);
});
};
tinymce.onAddEditor.add(interim_init);
tinyMCE.init(tinyMCEPreInit.mceInit[s.editor_id]);
s.is_mce_on = true;
}
wpActiveEditor = 'wp_mce_fullscreen';
});
ps.subscribe( 'hide', function() { // This event occurs before the overlay blocks DFW.
var htmled_is_hidden = $('#' + s.editor_id).is(':hidden');
// Make sure the correct editor is displaying.
if ( s.has_tinymce && s.mode === 'tinymce' && !htmled_is_hidden ) {
switchEditors.go(s.editor_id, 'tmce');
} else if ( s.mode === 'html' && htmled_is_hidden ) {
switchEditors.go(s.editor_id, 'html');
}
// Save content must be after switchEditors or content will be overwritten. See #17229.
api.savecontent();
$( document ).unbind( '.fullscreen' );
$(s.textarea_obj).unbind('.grow');
if ( s.has_tinymce && s.mode === 'tinymce' )
tinyMCE.execCommand('wpFullScreenSave');
if ( s.title_id )
set_title_hint( $('#' + s.title_id) );
s.qt_canvas.value = s.textarea_obj.value;
});
ps.subscribe( 'hiding', function() { // This event occurs while the overlay blocks the DFW UI.
$( document.body ).removeClass( 'fullscreen-active' );
scrollTo(0, s.orig_y);
$('#wpadminbar').show();
});
ps.subscribe( 'hidden', function() { // This event occurs after DFW is removed.
s.visible = false;
$('#wp_mce_fullscreen, #wp-fullscreen-title').removeAttr('style');
if ( s.has_tinymce && s.is_mce_on )
tinyMCE.execCommand('wpFullScreenClose');
s.textarea_obj.value = '';
api.oldheight = 0;
wpActiveEditor = s.editor_id;
});
ps.subscribe( 'switchMode', function( from, to ) {
var ed;
if ( !s.has_tinymce || !s.is_mce_on )
return;
ed = tinyMCE.get('wp_mce_fullscreen');
if ( from === 'html' && to === 'tinymce' ) {
if ( tinyMCE.get(s.editor_id).getParam('wpautop') && typeof(switchEditors) != 'undefined' )
s.textarea_obj.value = switchEditors.wpautop( s.textarea_obj.value );
if ( 'undefined' == typeof(ed) )
tinyMCE.execCommand('wpFullScreenInit');
else
ed.show();
} else if ( from === 'tinymce' && to === 'html' ) {
if ( ed )
ed.hide();
}
});
ps.subscribe( 'switchedMode', function( from, to ) {
api.refresh_buttons(true);
if ( to === 'html' )
setTimeout( api.resize_textarea, 200 );
});
/**
* Buttons
*/
api.b = function() {
if ( s.has_tinymce && 'tinymce' === s.mode )
tinyMCE.execCommand('Bold');
}
api.i = function() {
if ( s.has_tinymce && 'tinymce' === s.mode )
tinyMCE.execCommand('Italic');
}
api.ul = function() {
if ( s.has_tinymce && 'tinymce' === s.mode )
tinyMCE.execCommand('InsertUnorderedList');
}
api.ol = function() {
if ( s.has_tinymce && 'tinymce' === s.mode )
tinyMCE.execCommand('InsertOrderedList');
}
api.link = function() {
if ( s.has_tinymce && 'tinymce' === s.mode )
tinyMCE.execCommand('WP_Link');
else
wpLink.open();
}
api.unlink = function() {
if ( s.has_tinymce && 'tinymce' === s.mode )
tinyMCE.execCommand('unlink');
}
api.atd = function() {
if ( s.has_tinymce && 'tinymce' === s.mode )
tinyMCE.execCommand('mceWritingImprovementTool');
}
api.help = function() {
if ( s.has_tinymce && 'tinymce' === s.mode )
tinyMCE.execCommand('WP_Help');
}
api.blockquote = function() {
if ( s.has_tinymce && 'tinymce' === s.mode )
tinyMCE.execCommand('mceBlockQuote');
}
api.medialib = function() {
if ( s.has_tinymce && 'tinymce' === s.mode ) {
tinyMCE.execCommand('WP_Medialib');
} else {
var href = $('#wp-' + s.editor_id + '-media-buttons a.thickbox').attr('href') || '';
if ( href )
tb_show('', href);
}
}
api.refresh_buttons = function( fade ) {
fade = fade || false;
if ( s.mode === 'html' ) {
$('#wp-fullscreen-mode-bar').removeClass('wp-tmce-mode').addClass('wp-html-mode');
if ( fade )
$('#wp-fullscreen-button-bar').fadeOut( 150, function(){
$(this).addClass('wp-html-mode').fadeIn( 150 );
});
else
$('#wp-fullscreen-button-bar').addClass('wp-html-mode');
} else if ( s.mode === 'tinymce' ) {
$('#wp-fullscreen-mode-bar').removeClass('wp-html-mode').addClass('wp-tmce-mode');
if ( fade )
$('#wp-fullscreen-button-bar').fadeOut( 150, function(){
$(this).removeClass('wp-html-mode').fadeIn( 150 );
});
else
$('#wp-fullscreen-button-bar').removeClass('wp-html-mode');
}
}
/**
* UI Elements
*
* Used for transitioning between states.
*/
api.ui = {
init: function() {
var topbar = $('#fullscreen-topbar'), txtarea = $('#wp_mce_fullscreen'), last = 0;
s.toolbars = topbar.add( $('#wp-fullscreen-status') );
s.element = $('#fullscreen-fader');
s.textarea_obj = txtarea[0];
s.has_tinymce = typeof(tinymce) != 'undefined';
if ( !s.has_tinymce )
$('#wp-fullscreen-mode-bar').hide();
if ( wptitlehint && $('#wp-fullscreen-title').length )
wptitlehint('wp-fullscreen-title');
$(document).keyup(function(e){
var c = e.keyCode || e.charCode, a, data;
if ( !fullscreen.settings.visible )
return true;
if ( navigator.platform && navigator.platform.indexOf('Mac') != -1 )
a = e.ctrlKey; // Ctrl key for Mac
else
a = e.altKey; // Alt key for Win & Linux
if ( 27 == c ) { // Esc
data = {
event: e,
what: 'dfw',
cb: fullscreen.off,
condition: function(){
if ( $('#TB_window').is(':visible') || $('.wp-dialog').is(':visible') )
return false;
return true;
}
};
if ( ! jQuery(document).triggerHandler( 'wp_CloseOnEscape', [data] ) )
fullscreen.off();
}
if ( a && (61 == c || 107 == c || 187 == c) ) // +
api.dfw_width(25);
if ( a && (45 == c || 109 == c || 189 == c) ) // -
api.dfw_width(-25);
if ( a && 48 == c ) // 0
api.dfw_width(0);
return false;
});
// word count in HTML mode
if ( typeof(wpWordCount) != 'undefined' ) {
txtarea.keyup( function(e) {
var k = e.keyCode || e.charCode;
if ( k == last )
return true;
if ( 13 == k || 8 == last || 46 == last )
$(document).triggerHandler('wpcountwords', [ txtarea.val() ]);
last = k;
return true;
});
}
topbar.mouseenter(function(e){
s.toolbars.addClass('fullscreen-make-sticky');
$( document ).unbind( '.fullscreen' );
clearTimeout( s.timer );
s.timer = 0;
}).mouseleave(function(e){
s.toolbars.removeClass('fullscreen-make-sticky');
if ( s.visible )
$( document ).bind( 'mousemove.fullscreen', function(e) { bounder( 'showToolbar', 'hideToolbar', 2000, e ); } );
});
},
fade: function( before, during, after ) {
if ( ! s.element )
api.ui.init();
// If any callback bound to before returns false, bail.
if ( before && ! ps.publish( before ) )
return;
api.fade.In( s.element, 600, function() {
if ( during )
ps.publish( during );
api.fade.Out( s.element, 600, function() {
if ( after )
ps.publish( after );
})
});
}
};
api.fade = {
transitionend: 'transitionend webkitTransitionEnd oTransitionEnd',
// Sensitivity to allow browsers to render the blank element before animating.
sensitivity: 100,
In: function( element, speed, callback, stop ) {
callback = callback || $.noop;
speed = speed || 400;
stop = stop || false;
if ( api.fade.transitions ) {
if ( element.is(':visible') ) {
element.addClass( 'fade-trigger' );
return element;
}
element.show();
element.first().one( this.transitionend, function() {
callback();
});
setTimeout( function() { element.addClass( 'fade-trigger' ); }, this.sensitivity );
} else {
if ( stop )
element.stop();
element.css( 'opacity', 1 );
element.first().fadeIn( speed, callback );
if ( element.length > 1 )
element.not(':first').fadeIn( speed );
}
return element;
},
Out: function( element, speed, callback, stop ) {
callback = callback || $.noop;
speed = speed || 400;
stop = stop || false;
if ( ! element.is(':visible') )
return element;
if ( api.fade.transitions ) {
element.first().one( api.fade.transitionend, function() {
if ( element.hasClass('fade-trigger') )
return;
element.hide();
callback();
});
setTimeout( function() { element.removeClass( 'fade-trigger' ); }, this.sensitivity );
} else {
if ( stop )
element.stop();
element.first().fadeOut( speed, callback );
if ( element.length > 1 )
element.not(':first').fadeOut( speed );
}
return element;
},
transitions: (function() { // Check if the browser supports CSS 3.0 transitions
var s = document.documentElement.style;
return ( typeof ( s.WebkitTransition ) == 'string' ||
typeof ( s.MozTransition ) == 'string' ||
typeof ( s.OTransition ) == 'string' ||
typeof ( s.transition ) == 'string' );
})()
};
/**
* Resize API
*
* Automatically updates textarea height.
*/
api.bind_resize = function() {
$(s.textarea_obj).bind('keypress.grow click.grow paste.grow', function(){
setTimeout( api.resize_textarea, 200 );
});
}
api.oldheight = 0;
api.resize_textarea = function() {
var txt = s.textarea_obj, newheight;
newheight = txt.scrollHeight > 300 ? txt.scrollHeight : 300;
if ( newheight != api.oldheight ) {
txt.style.height = newheight + 'px';
api.oldheight = newheight;
}
};
})(jQuery);
| JavaScript |
var theList, theExtraList, toggleWithKeyboard = false;
(function($) {
var getCount, updateCount, updatePending, dashboardTotals;
setCommentsList = function() {
var totalInput, perPageInput, pageInput, lastConfidentTime = 0, dimAfter, delBefore, updateTotalCount, delAfter, refillTheExtraList;
totalInput = $('input[name="_total"]', '#comments-form');
perPageInput = $('input[name="_per_page"]', '#comments-form');
pageInput = $('input[name="_page"]', '#comments-form');
dimAfter = function( r, settings ) {
var c = $('#' + settings.element), editRow, replyID, replyButton;
editRow = $('#replyrow');
replyID = $('#comment_ID', editRow).val();
replyButton = $('#replybtn', editRow);
if ( c.is('.unapproved') ) {
if ( settings.data.id == replyID )
replyButton.text(adminCommentsL10n.replyApprove);
c.find('div.comment_status').html('0');
} else {
if ( settings.data.id == replyID )
replyButton.text(adminCommentsL10n.reply);
c.find('div.comment_status').html('1');
}
var diff = $('#' + settings.element).is('.' + settings.dimClass) ? 1 : -1;
updatePending( diff );
};
// Send current total, page, per_page and url
delBefore = function( settings, list ) {
var cl = $(settings.target).attr('class'), id, el, n, h, a, author, action = false;
settings.data._total = totalInput.val() || 0;
settings.data._per_page = perPageInput.val() || 0;
settings.data._page = pageInput.val() || 0;
settings.data._url = document.location.href;
settings.data.comment_status = $('input[name="comment_status"]', '#comments-form').val();
if ( cl.indexOf(':trash=1') != -1 )
action = 'trash';
else if ( cl.indexOf(':spam=1') != -1 )
action = 'spam';
if ( action ) {
id = cl.replace(/.*?comment-([0-9]+).*/, '$1');
el = $('#comment-' + id);
note = $('#' + action + '-undo-holder').html();
el.find('.check-column :checkbox').prop('checked', false); // Uncheck the row so as not to be affected by Bulk Edits.
if ( el.siblings('#replyrow').length && commentReply.cid == id )
commentReply.close();
if ( el.is('tr') ) {
n = el.children(':visible').length;
author = $('.author strong', el).text();
h = $('<tr id="undo-' + id + '" class="undo un' + action + '" style="display:none;"><td colspan="' + n + '">' + note + '</td></tr>');
} else {
author = $('.comment-author', el).text();
h = $('<div id="undo-' + id + '" style="display:none;" class="undo un' + action + '">' + note + '</div>');
}
el.before(h);
$('strong', '#undo-' + id).text(author);
a = $('.undo a', '#undo-' + id);
a.attr('href', 'comment.php?action=un' + action + 'comment&c=' + id + '&_wpnonce=' + settings.data._ajax_nonce);
a.attr('class', 'delete:the-comment-list:comment-' + id + '::un' + action + '=1 vim-z vim-destructive');
$('.avatar', el).clone().prependTo('#undo-' + id + ' .' + action + '-undo-inside');
a.click(function(){
list.wpList.del(this);
$('#undo-' + id).css( {backgroundColor:'#ceb'} ).fadeOut(350, function(){
$(this).remove();
$('#comment-' + id).css('backgroundColor', '').fadeIn(300, function(){ $(this).show() });
});
return false;
});
}
return settings;
};
// Updates the current total (stored in the _total input)
updateTotalCount = function( total, time, setConfidentTime ) {
if ( time < lastConfidentTime )
return;
if ( setConfidentTime )
lastConfidentTime = time;
totalInput.val( total.toString() );
};
dashboardTotals = function(n) {
var dash = $('#dashboard_right_now'), total, appr, totalN, apprN;
n = n || 0;
if ( isNaN(n) || !dash.length )
return;
total = $('span.total-count', dash);
appr = $('span.approved-count', dash);
totalN = getCount(total);
totalN = totalN + n;
apprN = totalN - getCount( $('span.pending-count', dash) ) - getCount( $('span.spam-count', dash) );
updateCount(total, totalN);
updateCount(appr, apprN);
};
getCount = function(el) {
var n = parseInt( el.html().replace(/[^0-9]+/g, ''), 10 );
if ( isNaN(n) )
return 0;
return n;
};
updateCount = function(el, n) {
var n1 = '';
if ( isNaN(n) )
return;
n = n < 1 ? '0' : n.toString();
if ( n.length > 3 ) {
while ( n.length > 3 ) {
n1 = thousandsSeparator + n.substr(n.length - 3) + n1;
n = n.substr(0, n.length - 3);
}
n = n + n1;
}
el.html(n);
};
updatePending = function( diff ) {
$('span.pending-count').each(function() {
var a = $(this), n = getCount(a) + diff;
if ( n < 1 )
n = 0;
a.closest('.awaiting-mod')[ 0 == n ? 'addClass' : 'removeClass' ]('count-0');
updateCount( a, n );
});
dashboardTotals();
};
// In admin-ajax.php, we send back the unix time stamp instead of 1 on success
delAfter = function( r, settings ) {
var total, N, spam, trash, pending,
untrash = $(settings.target).parent().is('span.untrash'),
unspam = $(settings.target).parent().is('span.unspam'),
unapproved = $('#' + settings.element).is('.unapproved');
function getUpdate(s) {
if ( $(settings.target).parent().is('span.' + s) )
return 1;
else if ( $('#' + settings.element).is('.' + s) )
return -1;
return 0;
}
if ( untrash )
trash = -1;
else
trash = getUpdate('trash');
if ( unspam )
spam = -1;
else
spam = getUpdate('spam');
if ( $(settings.target).parent().is('span.unapprove') || ( ( untrash || unspam ) && unapproved ) ) {
// a comment was 'deleted' from another list (e.g. approved, spam, trash) and moved to pending,
// or a trash/spam of a pending comment was undone
pending = 1;
} else if ( unapproved ) {
// a pending comment was trashed/spammed/approved
pending = -1;
}
if ( pending )
updatePending(pending);
$('span.spam-count').each( function() {
var a = $(this), n = getCount(a) + spam;
updateCount(a, n);
});
$('span.trash-count').each( function() {
var a = $(this), n = getCount(a) + trash;
updateCount(a, n);
});
if ( $('#dashboard_right_now').length ) {
N = trash ? -1 * trash : 0;
dashboardTotals(N);
} else {
total = totalInput.val() ? parseInt( totalInput.val(), 10 ) : 0;
if ( $(settings.target).parent().is('span.undo') )
total++;
else
total--;
if ( total < 0 )
total = 0;
if ( ( 'object' == typeof r ) && lastConfidentTime < settings.parsed.responses[0].supplemental.time ) {
total_items_i18n = settings.parsed.responses[0].supplemental.total_items_i18n || '';
if ( total_items_i18n ) {
$('.displaying-num').text( total_items_i18n );
$('.total-pages').text( settings.parsed.responses[0].supplemental.total_pages_i18n );
$('.tablenav-pages').find('.next-page, .last-page').toggleClass('disabled', settings.parsed.responses[0].supplemental.total_pages == $('.current-page').val());
}
updateTotalCount( total, settings.parsed.responses[0].supplemental.time, true );
} else {
updateTotalCount( total, r, false );
}
}
if ( ! theExtraList || theExtraList.size() == 0 || theExtraList.children().size() == 0 || untrash || unspam ) {
return;
}
theList.get(0).wpList.add( theExtraList.children(':eq(0)').remove().clone() );
refillTheExtraList();
};
refillTheExtraList = function(ev) {
var args = $.query.get(), total_pages = $('.total-pages').text(), per_page = $('input[name="_per_page"]', '#comments-form').val();
if (! args.paged)
args.paged = 1;
if (args.paged > total_pages) {
return;
}
if (ev) {
theExtraList.empty();
args.number = Math.min(8, per_page); // see WP_Comments_List_Table::prepare_items() @ class-wp-comments-list-table.php
} else {
args.number = 1;
args.offset = Math.min(8, per_page) - 1; // fetch only the next item on the extra list
}
args.no_placeholder = true;
args.paged ++;
// $.query.get() needs some correction to be sent into an ajax request
if ( true === args.comment_type )
args.comment_type = '';
args = $.extend(args, {
'action': 'fetch-list',
'list_args': list_args,
'_ajax_fetch_list_nonce': $('#_ajax_fetch_list_nonce').val()
});
$.ajax({
url: ajaxurl,
global: false,
dataType: 'json',
data: args,
success: function(response) {
theExtraList.get(0).wpList.add( response.rows );
}
});
};
theExtraList = $('#the-extra-comment-list').wpList( { alt: '', delColor: 'none', addColor: 'none' } );
theList = $('#the-comment-list').wpList( { alt: '', delBefore: delBefore, dimAfter: dimAfter, delAfter: delAfter, addColor: 'none' } )
.bind('wpListDelEnd', function(e, s){
var id = s.element.replace(/[^0-9]+/g, '');
if ( s.target.className.indexOf(':trash=1') != -1 || s.target.className.indexOf(':spam=1') != -1 )
$('#undo-' + id).fadeIn(300, function(){ $(this).show() });
});
};
commentReply = {
cid : '',
act : '',
init : function() {
var row = $('#replyrow');
$('a.cancel', row).click(function() { return commentReply.revert(); });
$('a.save', row).click(function() { return commentReply.send(); });
$('input#author, input#author-email, input#author-url', row).keypress(function(e){
if ( e.which == 13 ) {
commentReply.send();
e.preventDefault();
return false;
}
});
// add events
$('#the-comment-list .column-comment > p').dblclick(function(){
commentReply.toggle($(this).parent());
});
$('#doaction, #doaction2, #post-query-submit').click(function(e){
if ( $('#the-comment-list #replyrow').length > 0 )
commentReply.close();
});
this.comments_listing = $('#comments-form > input[name="comment_status"]').val() || '';
/* $(listTable).bind('beforeChangePage', function(){
commentReply.close();
}); */
},
addEvents : function(r) {
r.each(function() {
$(this).find('.column-comment > p').dblclick(function(){
commentReply.toggle($(this).parent());
});
});
},
toggle : function(el) {
if ( $(el).css('display') != 'none' )
$(el).find('a.vim-q').click();
},
revert : function() {
if ( $('#the-comment-list #replyrow').length < 1 )
return false;
$('#replyrow').fadeOut('fast', function(){
commentReply.close();
});
return false;
},
close : function() {
var c, replyrow = $('#replyrow');
// replyrow is not showing?
if ( replyrow.parent().is('#com-reply') )
return;
if ( this.cid && this.act == 'edit-comment' ) {
c = $('#comment-' + this.cid);
c.fadeIn(300, function(){ c.show() }).css('backgroundColor', '');
}
// reset the Quicktags buttons
if ( typeof QTags != 'undefined' )
QTags.closeAllTags('replycontent');
$('#add-new-comment').css('display', '');
replyrow.hide();
$('#com-reply').append( replyrow );
$('#replycontent').css('height', '').val('');
$('#edithead input').val('');
$('.error', replyrow).html('').hide();
$('.waiting', replyrow).hide();
this.cid = '';
},
open : function(comment_id, post_id, action) {
var t = this, editRow, rowData, act, c = $('#comment-' + comment_id), h = c.height(), replyButton;
t.close();
t.cid = comment_id;
editRow = $('#replyrow');
rowData = $('#inline-'+comment_id);
action = action || 'replyto';
act = 'edit' == action ? 'edit' : 'replyto';
act = t.act = act + '-comment';
$('#action', editRow).val(act);
$('#comment_post_ID', editRow).val(post_id);
$('#comment_ID', editRow).val(comment_id);
if ( h > 120 )
$('#replycontent', editRow).css('height', (35+h) + 'px');
if ( action == 'edit' ) {
$('#author', editRow).val( $('div.author', rowData).text() );
$('#author-email', editRow).val( $('div.author-email', rowData).text() );
$('#author-url', editRow).val( $('div.author-url', rowData).text() );
$('#status', editRow).val( $('div.comment_status', rowData).text() );
$('#replycontent', editRow).val( $('textarea.comment', rowData).val() );
$('#edithead, #savebtn', editRow).show();
$('#replyhead, #replybtn, #addhead, #addbtn', editRow).hide();
c.after( editRow ).fadeOut('fast', function(){
$('#replyrow').fadeIn(300, function(){ $(this).show() });
});
} else if ( action == 'add' ) {
$('#addhead, #addbtn', editRow).show();
$('#replyhead, #replybtn, #edithead, #editbtn', editRow).hide();
$('#the-comment-list').prepend(editRow);
$('#replyrow').fadeIn(300);
} else {
replyButton = $('#replybtn', editRow);
$('#edithead, #savebtn, #addhead, #addbtn', editRow).hide();
$('#replyhead, #replybtn', editRow).show();
c.after(editRow);
if ( c.hasClass('unapproved') ) {
replyButton.text(adminCommentsL10n.replyApprove);
} else {
replyButton.text(adminCommentsL10n.reply);
}
$('#replyrow').fadeIn(300, function(){ $(this).show() });
}
setTimeout(function() {
var rtop, rbottom, scrollTop, vp, scrollBottom;
rtop = $('#replyrow').offset().top;
rbottom = rtop + $('#replyrow').height();
scrollTop = window.pageYOffset || document.documentElement.scrollTop;
vp = document.documentElement.clientHeight || self.innerHeight || 0;
scrollBottom = scrollTop + vp;
if ( scrollBottom - 20 < rbottom )
window.scroll(0, rbottom - vp + 35);
else if ( rtop - 20 < scrollTop )
window.scroll(0, rtop - 35);
$('#replycontent').focus().keyup(function(e){
if ( e.which == 27 )
commentReply.revert(); // close on Escape
});
}, 600);
return false;
},
send : function() {
var post = {};
$('#replysubmit .error').hide();
$('#replysubmit .waiting').show();
$('#replyrow input').not(':button').each(function() {
var t = $(this);
post[ t.attr('name') ] = t.val();
});
post.content = $('#replycontent').val();
post.id = post.comment_post_ID;
post.comments_listing = this.comments_listing;
post.p = $('[name="p"]').val();
if ( $('#comment-' + $('#comment_ID').val()).hasClass('unapproved') )
post.approve_parent = 1;
$.ajax({
type : 'POST',
url : ajaxurl,
data : post,
success : function(x) { commentReply.show(x); },
error : function(r) { commentReply.error(r); }
});
return false;
},
show : function(xml) {
var t = this, r, c, id, bg, pid;
if ( typeof(xml) == 'string' ) {
t.error({'responseText': xml});
return false;
}
r = wpAjax.parseAjaxResponse(xml);
if ( r.errors ) {
t.error({'responseText': wpAjax.broken});
return false;
}
t.revert();
r = r.responses[0];
c = r.data;
id = '#comment-' + r.id;
if ( 'edit-comment' == t.act )
$(id).remove();
if ( r.supplemental.parent_approved ) {
pid = $('#comment-' + r.supplemental.parent_approved);
updatePending( -1 );
if ( this.comments_listing == 'moderated' ) {
pid.animate( { 'backgroundColor':'#CCEEBB' }, 400, function(){
pid.fadeOut();
});
return;
}
}
$(c).hide()
$('#replyrow').after(c);
id = $(id);
t.addEvents(id);
bg = id.hasClass('unapproved') ? '#FFFFE0' : id.closest('.widefat, .postbox').css('backgroundColor');
id.animate( { 'backgroundColor':'#CCEEBB' }, 300 )
.animate( { 'backgroundColor': bg }, 300, function() {
if ( pid && pid.length ) {
pid.animate( { 'backgroundColor':'#CCEEBB' }, 300 )
.animate( { 'backgroundColor': bg }, 300 )
.removeClass('unapproved').addClass('approved')
.find('div.comment_status').html('1');
}
});
},
error : function(r) {
var er = r.statusText;
$('#replysubmit .waiting').hide();
if ( r.responseText )
er = r.responseText.replace( /<.[^<>]*?>/g, '' );
if ( er )
$('#replysubmit .error').html(er).show();
},
addcomment: function(post_id) {
var t = this;
$('#add-new-comment').fadeOut(200, function(){
t.open(0, post_id, 'add');
$('table.comments-box').css('display', '');
$('#no-comments').remove();
});
}
};
$(document).ready(function(){
var make_hotkeys_redirect, edit_comment, toggle_all, make_bulk;
setCommentsList();
commentReply.init();
$(document).delegate('span.delete a.delete', 'click', function(){return false;});
if ( typeof $.table_hotkeys != 'undefined' ) {
make_hotkeys_redirect = function(which) {
return function() {
var first_last, l;
first_last = 'next' == which? 'first' : 'last';
l = $('.tablenav-pages .'+which+'-page:not(.disabled)');
if (l.length)
window.location = l[0].href.replace(/\&hotkeys_highlight_(first|last)=1/g, '')+'&hotkeys_highlight_'+first_last+'=1';
}
};
edit_comment = function(event, current_row) {
window.location = $('span.edit a', current_row).attr('href');
};
toggle_all = function() {
toggleWithKeyboard = true;
$('input:checkbox', '#cb').click().prop('checked', false);
toggleWithKeyboard = false;
};
make_bulk = function(value) {
return function() {
var scope = $('select[name="action"]');
$('option[value="' + value + '"]', scope).prop('selected', true);
$('#doaction').click();
}
};
$.table_hotkeys(
$('table.widefat'),
['a', 'u', 's', 'd', 'r', 'q', 'z', ['e', edit_comment], ['shift+x', toggle_all],
['shift+a', make_bulk('approve')], ['shift+s', make_bulk('spam')],
['shift+d', make_bulk('delete')], ['shift+t', make_bulk('trash')],
['shift+z', make_bulk('untrash')], ['shift+u', make_bulk('unapprove')]],
{ highlight_first: adminCommentsL10n.hotkeys_highlight_first, highlight_last: adminCommentsL10n.hotkeys_highlight_last,
prev_page_link_cb: make_hotkeys_redirect('prev'), next_page_link_cb: make_hotkeys_redirect('next') }
);
}
});
})(jQuery);
| JavaScript |
var thickDims, tbWidth, tbHeight;
jQuery(document).ready(function($) {
thickDims = function() {
var tbWindow = $('#TB_window'), H = $(window).height(), W = $(window).width(), w, h;
w = (tbWidth && tbWidth < W - 90) ? tbWidth : W - 90;
h = (tbHeight && tbHeight < H - 60) ? tbHeight : H - 60;
if ( tbWindow.size() ) {
tbWindow.width(w).height(h);
$('#TB_iframeContent').width(w).height(h - 27);
tbWindow.css({'margin-left': '-' + parseInt((w / 2),10) + 'px'});
if ( typeof document.body.style.maxWidth != 'undefined' )
tbWindow.css({'top':'30px','margin-top':'0'});
}
};
thickDims();
$(window).resize( function() { thickDims() } );
$('a.thickbox-preview').click( function() {
tb_click.call(this);
var alink = $(this).parents('.available-theme').find('.activatelink'), link = '', href = $(this).attr('href'), url, text;
if ( tbWidth = href.match(/&tbWidth=[0-9]+/) )
tbWidth = parseInt(tbWidth[0].replace(/[^0-9]+/g, ''), 10);
else
tbWidth = $(window).width() - 90;
if ( tbHeight = href.match(/&tbHeight=[0-9]+/) )
tbHeight = parseInt(tbHeight[0].replace(/[^0-9]+/g, ''), 10);
else
tbHeight = $(window).height() - 60;
if ( alink.length ) {
url = alink.attr('href') || '';
text = alink.attr('title') || '';
link = ' <a href="' + url + '" target="_top" class="tb-theme-preview-link">' + text + '</a>';
} else {
text = $(this).attr('title') || '';
link = ' <span class="tb-theme-preview-link">' + text + '</span>';
}
$('#TB_title').css({'background-color':'#222','color':'#dfdfdf'});
$('#TB_closeAjaxWindow').css({'float':'left'});
$('#TB_ajaxWindowTitle').css({'float':'right'}).html(link);
$('#TB_iframeContent').width('100%');
thickDims();
return false;
} );
});
| JavaScript |
var ajaxWidgets, ajaxPopulateWidgets, quickPressLoad;
jQuery(document).ready( function($) {
/* Dashboard Welcome Panel */
var welcomePanel = $('#welcome-panel'),
welcomePanelHide = $('#wp_welcome_panel-hide'),
updateWelcomePanel = function( visible ) {
$.post( ajaxurl, {
action: 'update-welcome-panel',
visible: visible,
welcomepanelnonce: $('#welcomepanelnonce').val()
});
};
if ( welcomePanel.hasClass('hidden') && welcomePanelHide.prop('checked') )
welcomePanel.removeClass('hidden');
$('.welcome-panel-close, .welcome-panel-dismiss a', welcomePanel).click( function(e) {
e.preventDefault();
welcomePanel.addClass('hidden');
updateWelcomePanel( 0 );
$('#wp_welcome_panel-hide').prop('checked', false);
});
welcomePanelHide.click( function() {
welcomePanel.toggleClass('hidden', ! this.checked );
updateWelcomePanel( this.checked ? 1 : 0 );
});
// These widgets are sometimes populated via ajax
ajaxWidgets = [
'dashboard_incoming_links',
'dashboard_primary',
'dashboard_secondary',
'dashboard_plugins'
];
ajaxPopulateWidgets = function(el) {
function show(i, id) {
var p, e = $('#' + id + ' div.inside:visible').find('.widget-loading');
if ( e.length ) {
p = e.parent();
setTimeout( function(){
p.load( ajaxurl + '?action=dashboard-widgets&widget=' + id, '', function() {
p.hide().slideDown('normal', function(){
$(this).css('display', '');
});
});
}, i * 500 );
}
}
if ( el ) {
el = el.toString();
if ( $.inArray(el, ajaxWidgets) != -1 )
show(0, el);
} else {
$.each( ajaxWidgets, show );
}
};
ajaxPopulateWidgets();
postboxes.add_postbox_toggles(pagenow, { pbshow: ajaxPopulateWidgets } );
/* QuickPress */
quickPressLoad = function() {
var act = $('#quickpost-action'), t;
t = $('#quick-press').submit( function() {
$('#dashboard_quick_press #publishing-action img.waiting').css('visibility', 'visible');
$('#quick-press .submit input[type="submit"], #quick-press .submit input[type="reset"]').prop('disabled', true);
if ( 'post' == act.val() ) {
act.val( 'post-quickpress-publish' );
}
$('#dashboard_quick_press div.inside').load( t.attr( 'action' ), t.serializeArray(), function() {
$('#dashboard_quick_press #publishing-action img.waiting').css('visibility', 'hidden');
$('#quick-press .submit input[type="submit"], #quick-press .submit input[type="reset"]').prop('disabled', false);
$('#dashboard_quick_press ul').next('p').remove();
$('#dashboard_quick_press ul').find('li').each( function() {
$('#dashboard_recent_drafts ul').prepend( this );
} ).end().remove();
quickPressLoad();
} );
return false;
} );
$('#publish').click( function() { act.val( 'post-quickpress-publish' ); } );
};
quickPressLoad();
} );
| JavaScript |
jQuery(document).ready( function($) {
var before, addBefore, addAfter, delBefore;
before = function() {
var nonce = $('#newmeta [name="_ajax_nonce"]').val(), postId = $('#post_ID').val();
if ( !nonce || !postId ) { return false; }
return [nonce,postId];
}
addBefore = function( s ) {
var b = before();
if ( !b ) { return false; }
s.data = s.data.replace(/_ajax_nonce=[a-f0-9]+/, '_ajax_nonce=' + b[0]) + '&post_id=' + b[1];
return s;
};
addAfter = function( r, s ) {
var postId = $('postid', r).text(), h;
if ( !postId ) { return; }
$('#post_ID').attr( 'name', 'post_ID' ).val( postId );
h = $('#hiddenaction');
if ( 'post' == h.val() ) { h.val( 'postajaxpost' ); }
};
delBefore = function( s ) {
var b = before(); if ( !b ) return false;
s.data._ajax_nonce = b[0]; s.data.post_id = b[1];
return s;
}
$('#the-list')
.wpList( { addBefore: addBefore, addAfter: addAfter, delBefore: delBefore } )
.find('.updatemeta, .deletemeta').attr( 'type', 'button' );
} );
| JavaScript |
var postboxes;
(function($) {
postboxes = {
add_postbox_toggles : function(page, args) {
var self = this;
self.init(page, args);
$('.postbox h3, .postbox .handlediv').bind('click.postboxes', function() {
var p = $(this).parent('.postbox'), id = p.attr('id');
if ( 'dashboard_browser_nag' == id )
return;
p.toggleClass('closed');
if ( page != 'press-this' )
self.save_state(page);
if ( id ) {
if ( !p.hasClass('closed') && $.isFunction(postboxes.pbshow) )
self.pbshow(id);
else if ( p.hasClass('closed') && $.isFunction(postboxes.pbhide) )
self.pbhide(id);
}
});
$('.postbox h3 a').click( function(e) {
e.stopPropagation();
});
$('.postbox a.dismiss').bind('click.postboxes', function(e) {
var hide_id = $(this).parents('.postbox').attr('id') + '-hide';
$( '#' + hide_id ).prop('checked', false).triggerHandler('click');
return false;
});
$('.hide-postbox-tog').bind('click.postboxes', function() {
var box = $(this).val();
if ( $(this).prop('checked') ) {
$('#' + box).show();
if ( $.isFunction( postboxes.pbshow ) )
self.pbshow( box );
} else {
$('#' + box).hide();
if ( $.isFunction( postboxes.pbhide ) )
self.pbhide( box );
}
self.save_state(page);
self._mark_area();
});
$('.columns-prefs input[type="radio"]').bind('click.postboxes', function(){
var n = parseInt($(this).val(), 10);
if ( n ) {
self._pb_edit(n);
self.save_order(page);
}
});
},
init : function(page, args) {
var isMobile = $(document.body).hasClass('mobile');
$.extend( this, args || {} );
$('#wpbody-content').css('overflow','hidden');
$('.meta-box-sortables').sortable({
placeholder: 'sortable-placeholder',
connectWith: '.meta-box-sortables',
items: '.postbox',
handle: '.hndle',
cursor: 'move',
delay: ( isMobile ? 200 : 0 ),
distance: 2,
tolerance: 'pointer',
forcePlaceholderSize: true,
helper: 'clone',
opacity: 0.65,
stop: function(e,ui) {
if ( $(this).find('#dashboard_browser_nag').is(':visible') && 'dashboard_browser_nag' != this.firstChild.id ) {
$(this).sortable('cancel');
return;
}
postboxes.save_order(page);
},
receive: function(e,ui) {
if ( 'dashboard_browser_nag' == ui.item[0].id )
$(ui.sender).sortable('cancel');
postboxes._mark_area();
}
});
if ( isMobile ) {
$(document.body).bind('orientationchange.postboxes', function(){ postboxes._pb_change(); });
this._pb_change();
}
this._mark_area();
},
save_state : function(page) {
var closed = $('.postbox').filter('.closed').map(function() { return this.id; }).get().join(','),
hidden = $('.postbox').filter(':hidden').map(function() { return this.id; }).get().join(',');
$.post(ajaxurl, {
action: 'closed-postboxes',
closed: closed,
hidden: hidden,
closedpostboxesnonce: jQuery('#closedpostboxesnonce').val(),
page: page
});
},
save_order : function(page) {
var postVars, page_columns = $('.columns-prefs input:checked').val() || 0;
postVars = {
action: 'meta-box-order',
_ajax_nonce: $('#meta-box-order-nonce').val(),
page_columns: page_columns,
page: page
}
$('.meta-box-sortables').each( function() {
postVars["order[" + this.id.split('-')[0] + "]"] = $(this).sortable( 'toArray' ).join(',');
} );
$.post( ajaxurl, postVars );
},
_mark_area : function() {
var visible = $('div.postbox:visible').length, side = $('#post-body #side-sortables');
$('#dashboard-widgets .meta-box-sortables:visible').each(function(n, el){
var t = $(this);
if ( visible == 1 || t.children('.postbox:visible').length )
t.removeClass('empty-container');
else
t.addClass('empty-container');
});
if ( side.length ) {
if ( side.children('.postbox:visible').length )
side.removeClass('empty-container');
else if ( $('#postbox-container-1').css('width') == '280px' )
side.addClass('empty-container');
}
},
_pb_edit : function(n) {
var el = $('.metabox-holder').get(0);
el.className = el.className.replace(/columns-\d+/, 'columns-' + n);
},
_pb_change : function() {
switch ( window.orientation ) {
case 90:
case -90:
this._pb_edit(2);
break;
case 0:
case 180:
if ( $('#poststuff').length )
this._pb_edit(1);
else
this._pb_edit(2);
break;
}
},
/* Callbacks */
pbshow : false,
pbhide : false
};
}(jQuery));
| JavaScript |
function WPSetAsThumbnail(id, nonce){
var $link = jQuery('a#wp-post-thumbnail-' + id);
$link.text( setPostThumbnailL10n.saving );
jQuery.post(ajaxurl, {
action:"set-post-thumbnail", post_id: post_id, thumbnail_id: id, _ajax_nonce: nonce, cookie: encodeURIComponent(document.cookie)
}, function(str){
var win = window.dialogArguments || opener || parent || top;
$link.text( setPostThumbnailL10n.setThumbnail );
if ( str == '0' ) {
alert( setPostThumbnailL10n.error );
} else {
jQuery('a.wp-post-thumbnail').show();
$link.text( setPostThumbnailL10n.done );
$link.fadeOut( 2000 );
win.WPSetThumbnailID(id);
win.WPSetThumbnailHTML(str);
}
}
);
}
| JavaScript |
var findPosts;
(function($){
findPosts = {
open : function(af_name, af_val) {
var st = document.documentElement.scrollTop || $(document).scrollTop(),
overlay = $( '.ui-find-overlay' );
if ( overlay.length == 0 ) {
$( 'body' ).append( '<div class="ui-find-overlay"></div>' );
findPosts.overlay();
}
overlay.show();
if ( af_name && af_val ) {
$('#affected').attr('name', af_name).val(af_val);
}
$('#find-posts').show().draggable({
handle: '#find-posts-head'
}).css({'top':st + 50 + 'px','left':'50%','marginLeft':'-328px'});
$('#find-posts-input').focus().keyup(function(e){
if (e.which == 27) { findPosts.close(); } // close on Escape
});
// Pull some results up by default
findPosts.send();
return false;
},
close : function() {
$('#find-posts-response').html('');
$('#find-posts').draggable('destroy').hide();
$( '.ui-find-overlay' ).hide();
},
overlay : function() {
$( '.ui-find-overlay' ).css(
{ 'z-index': '999', 'width': $( document ).width() + 'px', 'height': $( document ).height() + 'px' }
).on('click', function () {
findPosts.close();
});
},
send : function() {
var post = {
ps: $('#find-posts-input').val(),
action: 'find_posts',
_ajax_nonce: $('#_ajax_nonce').val()
},
spinner = $( '.find-box-search .spinner' );
spinner.show();
$.ajax({
type : 'POST',
url : ajaxurl,
data : post,
success : function(x) { findPosts.show(x); spinner.hide(); },
error : function(r) { findPosts.error(r); spinner.hide(); }
});
},
show : function(x) {
if ( typeof(x) == 'string' ) {
this.error({'responseText': x});
return;
}
var r = wpAjax.parseAjaxResponse(x);
if ( r.errors ) {
this.error({'responseText': wpAjax.broken});
}
r = r.responses[0];
$('#find-posts-response').html(r.data);
// Enable whole row to be clicked
$( '.found-posts td' ).on( 'click', function () {
$( this ).parent().find( '.found-radio input' ).prop( 'checked', true );
});
},
error : function(r) {
var er = r.statusText;
if ( r.responseText ) {
er = r.responseText.replace( /<.[^<>]*?>/g, '' );
}
if ( er ) {
$('#find-posts-response').html(er);
}
}
};
$(document).ready(function() {
$('#find-posts-submit').click(function(e) {
if ( '' == $('#find-posts-response').html() )
e.preventDefault();
});
$( '#find-posts .find-box-search :input' ).keypress( function( event ) {
if ( 13 == event.which ) {
findPosts.send();
return false;
}
} );
$( '#find-posts-search' ).click( findPosts.send );
$( '#find-posts-close' ).click( findPosts.close );
$('#doaction, #doaction2').click(function(e){
$('select[name^="action"]').each(function(){
if ( $(this).val() == 'attach' ) {
e.preventDefault();
findPosts.open();
}
});
});
});
$(window).resize(function() {
findPosts.overlay();
});
})(jQuery);
| JavaScript |
( function( $, undef ){
// html stuff
var _before = '<a tabindex="0" class="wp-color-result" />',
_after = '<div class="wp-picker-holder" />',
_wrap = '<div class="wp-picker-container" />',
_button = '<input type="button" class="button button-small hidden" />';
// jQuery UI Widget constructor
var ColorPicker = {
options: {
defaultColor: false,
change: false,
clear: false,
hide: true,
palettes: true
},
_create: function() {
// bail early for IE < 8
if ( $.browser.msie && parseInt( $.browser.version, 10 ) < 8 )
return;
var self = this;
var el = self.element;
$.extend( self.options, el.data() );
self.initialValue = el.val();
// Set up HTML structure, hide things
el.addClass( 'wp-color-picker' ).hide().wrap( _wrap );
self.wrap = el.parent();
self.toggler = $( _before ).insertBefore( el ).css( { backgroundColor: self.initialValue } ).attr( "title", wpColorPickerL10n.pick ).attr( "data-current", wpColorPickerL10n.current );
self.pickerContainer = $( _after ).insertAfter( el );
self.button = $( _button );
if ( self.options.defaultColor )
self.button.addClass( 'wp-picker-default' ).val( wpColorPickerL10n.defaultString );
else
self.button.addClass( 'wp-picker-clear' ).val( wpColorPickerL10n.clear );
el.wrap('<span class="wp-picker-input-wrap" />').after(self.button);
el.iris( {
target: self.pickerContainer,
hide: true,
width: 255,
mode: 'hsv',
palettes: self.options.palettes,
change: function( event, ui ) {
self.toggler.css( { backgroundColor: ui.color.toString() } );
// check for a custom cb
if ( $.isFunction( self.options.change ) )
self.options.change.call( this, event, ui );
}
} );
el.val( self.initialValue );
self._addListeners();
if ( ! self.options.hide )
self.toggler.click();
},
_addListeners: function() {
var self = this;
self.toggler.click( function( event ){
event.stopPropagation();
self.element.toggle().iris( 'toggle' );
self.button.toggleClass('hidden');
self.toggler.toggleClass( 'wp-picker-open' );
// close picker when you click outside it
if ( self.toggler.hasClass( 'wp-picker-open' ) )
$( "body" ).on( 'click', { wrap: self.wrap, toggler: self.toggler }, self._bodyListener );
else
$( "body" ).off( 'click', self._bodyListener );
});
self.element.change(function( event ) {
var me = $(this),
val = me.val();
// Empty = clear
if ( val === '' || val === '#' ) {
self.toggler.css('backgroundColor', '');
// fire clear callback if we have one
if ( $.isFunction( self.options.clear ) )
self.options.clear.call( this, event );
}
});
// open a keyboard-focused closed picker with space or enter
self.toggler.on('keyup', function( e ) {
if ( e.keyCode === 13 || e.keyCode === 32 ) {
e.preventDefault();
self.toggler.trigger('click').next().focus();
}
});
self.button.click( function( event ) {
var me = $(this);
if ( me.hasClass( 'wp-picker-clear' ) ) {
self.element.val( '' );
self.toggler.css('backgroundColor', '');
if ( $.isFunction( self.options.clear ) )
self.options.clear.call( this, event );
} else if ( me.hasClass( 'wp-picker-default' ) ) {
self.element.val( self.options.defaultColor ).change();
}
});
},
_bodyListener: function( event ) {
if ( ! event.data.wrap.find( event.target ).length )
event.data.toggler.click();
},
// $("#input").wpColorPicker('color') returns the current color
// $("#input").wpColorPicker('color', '#bada55') to set
color: function( newColor ) {
if ( newColor === undef )
return this.element.iris( "option", "color" );
this.element.iris( "option", "color", newColor );
},
//$("#input").wpColorPicker('defaultColor') returns the current default color
//$("#input").wpColorPicker('defaultColor', newDefaultColor) to set
defaultColor: function( newDefaultColor ) {
if ( newDefaultColor === undef )
return this.options.defaultColor;
this.options.defaultColor = newDefaultColor;
}
}
$.widget( 'wp.wpColorPicker', ColorPicker );
}( jQuery ) ); | JavaScript |
var showNotice, adminMenu, columns, validateForm, screenMeta;
(function($){
// Removed in 3.3.
// (perhaps) needed for back-compat
adminMenu = {
init : function() {},
fold : function() {},
restoreMenuState : function() {},
toggle : function() {},
favorites : function() {}
};
// show/hide/save table columns
columns = {
init : function() {
var that = this;
$('.hide-column-tog', '#adv-settings').click( function() {
var $t = $(this), column = $t.val();
if ( $t.prop('checked') )
that.checked(column);
else
that.unchecked(column);
columns.saveManageColumnsState();
});
},
saveManageColumnsState : function() {
var hidden = this.hidden();
$.post(ajaxurl, {
action: 'hidden-columns',
hidden: hidden,
screenoptionnonce: $('#screenoptionnonce').val(),
page: pagenow
});
},
checked : function(column) {
$('.column-' + column).show();
this.colSpanChange(+1);
},
unchecked : function(column) {
$('.column-' + column).hide();
this.colSpanChange(-1);
},
hidden : function() {
return $('.manage-column').filter(':hidden').map(function() { return this.id; }).get().join(',');
},
useCheckboxesForHidden : function() {
this.hidden = function(){
return $('.hide-column-tog').not(':checked').map(function() {
var id = this.id;
return id.substring( id, id.length - 5 );
}).get().join(',');
};
},
colSpanChange : function(diff) {
var $t = $('table').find('.colspanchange'), n;
if ( !$t.length )
return;
n = parseInt( $t.attr('colspan'), 10 ) + diff;
$t.attr('colspan', n.toString());
}
}
$(document).ready(function(){columns.init();});
validateForm = function( form ) {
return !$( form ).find('.form-required').filter( function() { return $('input:visible', this).val() == ''; } ).addClass( 'form-invalid' ).find('input:visible').change( function() { $(this).closest('.form-invalid').removeClass( 'form-invalid' ); } ).size();
}
// stub for doing better warnings
showNotice = {
warn : function() {
var msg = commonL10n.warnDelete || '';
if ( confirm(msg) ) {
return true;
}
return false;
},
note : function(text) {
alert(text);
}
};
screenMeta = {
element: null, // #screen-meta
toggles: null, // .screen-meta-toggle
page: null, // #wpcontent
init: function() {
this.element = $('#screen-meta');
this.toggles = $('.screen-meta-toggle a');
this.page = $('#wpcontent');
this.toggles.click( this.toggleEvent );
},
toggleEvent: function( e ) {
var panel = $( this.href.replace(/.+#/, '#') );
e.preventDefault();
if ( !panel.length )
return;
if ( panel.is(':visible') )
screenMeta.close( panel, $(this) );
else
screenMeta.open( panel, $(this) );
},
open: function( panel, link ) {
$('.screen-meta-toggle').not( link.parent() ).css('visibility', 'hidden');
panel.parent().show();
panel.slideDown( 'fast', function() {
panel.focus();
link.addClass('screen-meta-active').attr('aria-expanded', true);
});
},
close: function( panel, link ) {
panel.slideUp( 'fast', function() {
link.removeClass('screen-meta-active').attr('aria-expanded', false);
$('.screen-meta-toggle').css('visibility', '');
panel.parent().hide();
});
}
};
/**
* Help tabs.
*/
$('.contextual-help-tabs').delegate('a', 'click focus', function(e) {
var link = $(this),
panel;
e.preventDefault();
// Don't do anything if the click is for the tab already showing.
if ( link.is('.active a') )
return false;
// Links
$('.contextual-help-tabs .active').removeClass('active');
link.parent('li').addClass('active');
panel = $( link.attr('href') );
// Panels
$('.help-tab-content').not( panel ).removeClass('active').hide();
panel.addClass('active').show();
});
$(document).ready( function() {
var lastClicked = false, checks, first, last, checked, menu = $('#adminmenu'), mobileEvent,
pageInput = $('input.current-page'), currentPage = pageInput.val();
// when the menu is folded, make the fly-out submenu header clickable
menu.on('click.wp-submenu-head', '.wp-submenu-head', function(e){
$(e.target).parent().siblings('a').get(0).click();
});
$('#collapse-menu').on('click.collapse-menu', function(e){
var body = $(document.body);
// reset any compensation for submenus near the bottom of the screen
$('#adminmenu div.wp-submenu').css('margin-top', '');
if ( $(window).width() < 900 ) {
if ( body.hasClass('auto-fold') ) {
body.removeClass('auto-fold');
setUserSetting('unfold', 1);
body.removeClass('folded');
deleteUserSetting('mfold');
} else {
body.addClass('auto-fold');
deleteUserSetting('unfold');
}
} else {
if ( body.hasClass('folded') ) {
body.removeClass('folded');
deleteUserSetting('mfold');
} else {
body.addClass('folded');
setUserSetting('mfold', 'f');
}
}
});
if ( 'ontouchstart' in window || /IEMobile\/[1-9]/.test(navigator.userAgent) ) { // touch screen device
// iOS Safari works with touchstart, the rest work with click
mobileEvent = /Mobile\/.+Safari/.test(navigator.userAgent) ? 'touchstart' : 'click';
// close any open submenus when touch/click is not on the menu
$(document.body).on( mobileEvent+'.wp-mobile-hover', function(e) {
if ( !$(e.target).closest('#adminmenu').length )
menu.find('li.wp-has-submenu.opensub').removeClass('opensub');
});
menu.find('a.wp-has-submenu').on( mobileEvent+'.wp-mobile-hover', function(e) {
var el = $(this), parent = el.parent();
// Show the sub instead of following the link if:
// - the submenu is not open
// - the submenu is not shown inline or the menu is not folded
if ( !parent.hasClass('opensub') && ( !parent.hasClass('wp-menu-open') || parent.width() < 40 ) ) {
e.preventDefault();
menu.find('li.opensub').removeClass('opensub');
parent.addClass('opensub');
}
});
}
menu.find('li.wp-has-submenu').hoverIntent({
over: function(e){
var b, h, o, f, m = $(this).find('.wp-submenu'), menutop, wintop, maxtop, top = parseInt( m.css('top'), 10 );
if ( isNaN(top) || top > -5 ) // meaning the submenu is visible
return;
menutop = $(this).offset().top;
wintop = $(window).scrollTop();
maxtop = menutop - wintop - 30; // max = make the top of the sub almost touch admin bar
b = menutop + m.height() + 1; // Bottom offset of the menu
h = $('#wpwrap').height(); // Height of the entire page
o = 60 + b - h;
f = $(window).height() + wintop - 15; // The fold
if ( f < (b - o) )
o = b - f;
if ( o > maxtop )
o = maxtop;
if ( o > 1 )
m.css('margin-top', '-'+o+'px');
else
m.css('margin-top', '');
menu.find('li.menu-top').removeClass('opensub');
$(this).addClass('opensub');
},
out: function(){
$(this).removeClass('opensub').find('.wp-submenu').css('margin-top', '');
},
timeout: 200,
sensitivity: 7,
interval: 90
});
menu.on('focus.adminmenu', '.wp-submenu a', function(e){
$(e.target).closest('li.menu-top').addClass('opensub');
}).on('blur.adminmenu', '.wp-submenu a', function(e){
$(e.target).closest('li.menu-top').removeClass('opensub');
});
// Move .updated and .error alert boxes. Don't move boxes designed to be inline.
$('div.wrap h2:first').nextAll('div.updated, div.error').addClass('below-h2');
$('div.updated, div.error').not('.below-h2, .inline').insertAfter( $('div.wrap h2:first') );
// Init screen meta
screenMeta.init();
// check all checkboxes
$('tbody').children().children('.check-column').find(':checkbox').click( function(e) {
if ( 'undefined' == e.shiftKey ) { return true; }
if ( e.shiftKey ) {
if ( !lastClicked ) { return true; }
checks = $( lastClicked ).closest( 'form' ).find( ':checkbox' );
first = checks.index( lastClicked );
last = checks.index( this );
checked = $(this).prop('checked');
if ( 0 < first && 0 < last && first != last ) {
checks.slice( first, last ).prop( 'checked', function(){
if ( $(this).closest('tr').is(':visible') )
return checked;
return false;
});
}
}
lastClicked = this;
// toggle "check all" checkboxes
var unchecked = $(this).closest('tbody').find(':checkbox').filter(':visible').not(':checked');
$(this).closest('table').children('thead, tfoot').find(':checkbox').prop('checked', function() {
return ( 0 == unchecked.length );
});
return true;
});
$('thead, tfoot').find('.check-column :checkbox').click( function(e) {
var c = $(this).prop('checked'),
kbtoggle = 'undefined' == typeof toggleWithKeyboard ? false : toggleWithKeyboard,
toggle = e.shiftKey || kbtoggle;
$(this).closest( 'table' ).children( 'tbody' ).filter(':visible')
.children().children('.check-column').find(':checkbox')
.prop('checked', function() {
if ( $(this).closest('tr').is(':hidden') )
return false;
if ( toggle )
return $(this).prop( 'checked' );
else if (c)
return true;
return false;
});
$(this).closest('table').children('thead, tfoot').filter(':visible')
.children().children('.check-column').find(':checkbox')
.prop('checked', function() {
if ( toggle )
return false;
else if (c)
return true;
return false;
});
});
$('#default-password-nag-no').click( function() {
setUserSetting('default_password_nag', 'hide');
$('div.default-password-nag').hide();
return false;
});
// tab in textareas
$('#newcontent').bind('keydown.wpevent_InsertTab', function(e) {
var el = e.target, selStart, selEnd, val, scroll, sel;
if ( e.keyCode == 27 ) { // escape key
$(el).data('tab-out', true);
return;
}
if ( e.keyCode != 9 || e.ctrlKey || e.altKey || e.shiftKey ) // tab key
return;
if ( $(el).data('tab-out') ) {
$(el).data('tab-out', false);
return;
}
selStart = el.selectionStart;
selEnd = el.selectionEnd;
val = el.value;
try {
this.lastKey = 9; // not a standard DOM property, lastKey is to help stop Opera tab event. See blur handler below.
} catch(err) {}
if ( document.selection ) {
el.focus();
sel = document.selection.createRange();
sel.text = '\t';
} else if ( selStart >= 0 ) {
scroll = this.scrollTop;
el.value = val.substring(0, selStart).concat('\t', val.substring(selEnd) );
el.selectionStart = el.selectionEnd = selStart + 1;
this.scrollTop = scroll;
}
if ( e.stopPropagation )
e.stopPropagation();
if ( e.preventDefault )
e.preventDefault();
});
$('#newcontent').bind('blur.wpevent_InsertTab', function(e) {
if ( this.lastKey && 9 == this.lastKey )
this.focus();
});
if ( pageInput.length ) {
pageInput.closest('form').submit( function(e){
// Reset paging var for new filters/searches but not for bulk actions. See #17685.
if ( $('select[name="action"]').val() == -1 && $('select[name="action2"]').val() == -1 && pageInput.val() == currentPage )
pageInput.val('1');
});
}
// Scroll into view when focused
$('#contextual-help-link, #show-settings-link').on( 'focus.scroll-into-view', function(e){
if ( e.target.scrollIntoView )
e.target.scrollIntoView(false);
});
// Disable upload buttons until files are selected
(function(){
var button, input, form = $('form.wp-upload-form');
if ( ! form.length )
return;
button = form.find('input[type="submit"]');
input = form.find('input[type="file"]');
function toggleUploadButton() {
button.prop('disabled', '' === input.map( function() {
return $(this).val();
}).get().join(''));
}
toggleUploadButton();
input.on('change', toggleUploadButton);
})();
});
// internal use
$(document).bind( 'wp_CloseOnEscape', function( e, data ) {
if ( typeof(data.cb) != 'function' )
return;
if ( typeof(data.condition) != 'function' || data.condition() )
data.cb();
return true;
});
})(jQuery);
| JavaScript |
var ajaxWidgets, ajaxPopulateWidgets, quickPressLoad;
jQuery(document).ready( function($) {
/* Dashboard Welcome Panel */
var welcomePanel = $('#welcome-panel'),
welcomePanelHide = $('#wp_welcome_panel-hide'),
updateWelcomePanel = function( visible ) {
$.post( ajaxurl, {
action: 'update-welcome-panel',
visible: visible,
welcomepanelnonce: $('#welcomepanelnonce').val()
});
};
if ( welcomePanel.hasClass('hidden') && welcomePanelHide.prop('checked') )
welcomePanel.removeClass('hidden');
$('.welcome-panel-close, .welcome-panel-dismiss a', welcomePanel).click( function(e) {
e.preventDefault();
welcomePanel.addClass('hidden');
updateWelcomePanel( 0 );
$('#wp_welcome_panel-hide').prop('checked', false);
});
welcomePanelHide.click( function() {
welcomePanel.toggleClass('hidden', ! this.checked );
updateWelcomePanel( this.checked ? 1 : 0 );
});
// These widgets are sometimes populated via ajax
ajaxWidgets = [
'dashboard_incoming_links',
'dashboard_primary',
'dashboard_secondary',
'dashboard_plugins'
];
ajaxPopulateWidgets = function(el) {
function show(i, id) {
var p, e = $('#' + id + ' div.inside:visible').find('.widget-loading');
if ( e.length ) {
p = e.parent();
setTimeout( function(){
p.load( ajaxurl + '?action=dashboard-widgets&widget=' + id, '', function() {
p.hide().slideDown('normal', function(){
$(this).css('display', '');
});
});
}, i * 500 );
}
}
if ( el ) {
el = el.toString();
if ( $.inArray(el, ajaxWidgets) != -1 )
show(0, el);
} else {
$.each( ajaxWidgets, show );
}
};
ajaxPopulateWidgets();
postboxes.add_postbox_toggles(pagenow, { pbshow: ajaxPopulateWidgets } );
/* QuickPress */
quickPressLoad = function() {
var act = $('#quickpost-action'), t;
t = $('#quick-press').submit( function() {
$('#dashboard_quick_press #publishing-action .spinner').show();
$('#quick-press .submit input[type="submit"], #quick-press .submit input[type="reset"]').prop('disabled', true);
if ( 'post' == act.val() ) {
act.val( 'post-quickpress-publish' );
}
$('#dashboard_quick_press div.inside').load( t.attr( 'action' ), t.serializeArray(), function() {
$('#dashboard_quick_press #publishing-action .spinner').hide();
$('#quick-press .submit input[type="submit"], #quick-press .submit input[type="reset"]').prop('disabled', false);
$('#dashboard_quick_press ul').next('p').remove();
$('#dashboard_quick_press ul').find('li').each( function() {
$('#dashboard_recent_drafts ul').prepend( this );
} ).end().remove();
quickPressLoad();
} );
return false;
} );
$('#publish').click( function() { act.val( 'post-quickpress-publish' ); } );
$('#title, #tags-input').each( function() {
var input = $(this), prompt = $('#' + this.id + '-prompt-text');
if ( '' === this.value )
prompt.removeClass('screen-reader-text');
prompt.click( function() {
$(this).addClass('screen-reader-text');
input.focus();
});
input.blur( function() {
if ( '' === this.value )
prompt.removeClass('screen-reader-text');
});
input.focus( function() {
prompt.addClass('screen-reader-text');
});
});
$('#quick-press').on( 'click focusin', function() {
wpActiveEditor = 'content';
});
};
quickPressLoad();
} );
| JavaScript |
/**
* WordPress Administration Navigation Menu
* Interface JS functions
*
* @version 2.0.0
*
* @package WordPress
* @subpackage Administration
*/
var wpNavMenu;
(function($) {
var api = wpNavMenu = {
options : {
menuItemDepthPerLevel : 30, // Do not use directly. Use depthToPx and pxToDepth instead.
globalMaxDepth : 11
},
menuList : undefined, // Set in init.
targetList : undefined, // Set in init.
menusChanged : false,
isRTL: !! ( 'undefined' != typeof isRtl && isRtl ),
negateIfRTL: ( 'undefined' != typeof isRtl && isRtl ) ? -1 : 1,
// Functions that run on init.
init : function() {
api.menuList = $('#menu-to-edit');
api.targetList = api.menuList;
this.jQueryExtensions();
this.attachMenuEditListeners();
this.setupInputWithDefaultTitle();
this.attachQuickSearchListeners();
this.attachThemeLocationsListeners();
this.attachTabsPanelListeners();
this.attachUnsavedChangesListener();
if( api.menuList.length ) // If no menu, we're in the + tab.
this.initSortables();
this.initToggles();
this.initTabManager();
},
jQueryExtensions : function() {
// jQuery extensions
$.fn.extend({
menuItemDepth : function() {
var margin = api.isRTL ? this.eq(0).css('margin-right') : this.eq(0).css('margin-left');
return api.pxToDepth( margin && -1 != margin.indexOf('px') ? margin.slice(0, -2) : 0 );
},
updateDepthClass : function(current, prev) {
return this.each(function(){
var t = $(this);
prev = prev || t.menuItemDepth();
$(this).removeClass('menu-item-depth-'+ prev )
.addClass('menu-item-depth-'+ current );
});
},
shiftDepthClass : function(change) {
return this.each(function(){
var t = $(this),
depth = t.menuItemDepth();
$(this).removeClass('menu-item-depth-'+ depth )
.addClass('menu-item-depth-'+ (depth + change) );
});
},
childMenuItems : function() {
var result = $();
this.each(function(){
var t = $(this), depth = t.menuItemDepth(), next = t.next();
while( next.length && next.menuItemDepth() > depth ) {
result = result.add( next );
next = next.next();
}
});
return result;
},
updateParentMenuItemDBId : function() {
return this.each(function(){
var item = $(this),
input = item.find('.menu-item-data-parent-id'),
depth = item.menuItemDepth(),
parent = item.prev();
if( depth == 0 ) { // Item is on the top level, has no parent
input.val(0);
} else { // Find the parent item, and retrieve its object id.
while( ! parent[0] || ! parent[0].className || -1 == parent[0].className.indexOf('menu-item') || ( parent.menuItemDepth() != depth - 1 ) )
parent = parent.prev();
input.val( parent.find('.menu-item-data-db-id').val() );
}
});
},
hideAdvancedMenuItemFields : function() {
return this.each(function(){
var that = $(this);
$('.hide-column-tog').not(':checked').each(function(){
that.find('.field-' + $(this).val() ).addClass('hidden-field');
});
});
},
/**
* Adds selected menu items to the menu.
*
* @param jQuery metabox The metabox jQuery object.
*/
addSelectedToMenu : function(processMethod) {
if ( 0 == $('#menu-to-edit').length ) {
return false;
}
return this.each(function() {
var t = $(this), menuItems = {},
checkboxes = t.find('.tabs-panel-active .categorychecklist li input:checked'),
re = new RegExp('menu-item\\[(\[^\\]\]*)');
processMethod = processMethod || api.addMenuItemToBottom;
// If no items are checked, bail.
if ( !checkboxes.length )
return false;
// Show the ajax spinner
t.find('.spinner').show();
// Retrieve menu item data
$(checkboxes).each(function(){
var t = $(this),
listItemDBIDMatch = re.exec( t.attr('name') ),
listItemDBID = 'undefined' == typeof listItemDBIDMatch[1] ? 0 : parseInt(listItemDBIDMatch[1], 10);
if ( this.className && -1 != this.className.indexOf('add-to-top') )
processMethod = api.addMenuItemToTop;
menuItems[listItemDBID] = t.closest('li').getItemData( 'add-menu-item', listItemDBID );
});
// Add the items
api.addItemToMenu(menuItems, processMethod, function(){
// Deselect the items and hide the ajax spinner
checkboxes.removeAttr('checked');
t.find('.spinner').hide();
});
});
},
getItemData : function( itemType, id ) {
itemType = itemType || 'menu-item';
var itemData = {}, i,
fields = [
'menu-item-db-id',
'menu-item-object-id',
'menu-item-object',
'menu-item-parent-id',
'menu-item-position',
'menu-item-type',
'menu-item-title',
'menu-item-url',
'menu-item-description',
'menu-item-attr-title',
'menu-item-target',
'menu-item-classes',
'menu-item-xfn'
];
if( !id && itemType == 'menu-item' ) {
id = this.find('.menu-item-data-db-id').val();
}
if( !id ) return itemData;
this.find('input').each(function() {
var field;
i = fields.length;
while ( i-- ) {
if( itemType == 'menu-item' )
field = fields[i] + '[' + id + ']';
else if( itemType == 'add-menu-item' )
field = 'menu-item[' + id + '][' + fields[i] + ']';
if (
this.name &&
field == this.name
) {
itemData[fields[i]] = this.value;
}
}
});
return itemData;
},
setItemData : function( itemData, itemType, id ) { // Can take a type, such as 'menu-item', or an id.
itemType = itemType || 'menu-item';
if( !id && itemType == 'menu-item' ) {
id = $('.menu-item-data-db-id', this).val();
}
if( !id ) return this;
this.find('input').each(function() {
var t = $(this), field;
$.each( itemData, function( attr, val ) {
if( itemType == 'menu-item' )
field = attr + '[' + id + ']';
else if( itemType == 'add-menu-item' )
field = 'menu-item[' + id + '][' + attr + ']';
if ( field == t.attr('name') ) {
t.val( val );
}
});
});
return this;
}
});
},
initToggles : function() {
// init postboxes
postboxes.add_postbox_toggles('nav-menus');
// adjust columns functions for menus UI
columns.useCheckboxesForHidden();
columns.checked = function(field) {
$('.field-' + field).removeClass('hidden-field');
}
columns.unchecked = function(field) {
$('.field-' + field).addClass('hidden-field');
}
// hide fields
api.menuList.hideAdvancedMenuItemFields();
},
initSortables : function() {
var currentDepth = 0, originalDepth, minDepth, maxDepth,
prev, next, prevBottom, nextThreshold, helperHeight, transport,
menuEdge = api.menuList.offset().left,
body = $('body'), maxChildDepth,
menuMaxDepth = initialMenuMaxDepth();
// Use the right edge if RTL.
menuEdge += api.isRTL ? api.menuList.width() : 0;
api.menuList.sortable({
handle: '.menu-item-handle',
placeholder: 'sortable-placeholder',
start: function(e, ui) {
var height, width, parent, children, tempHolder;
// handle placement for rtl orientation
if ( api.isRTL )
ui.item[0].style.right = 'auto';
transport = ui.item.children('.menu-item-transport');
// Set depths. currentDepth must be set before children are located.
originalDepth = ui.item.menuItemDepth();
updateCurrentDepth(ui, originalDepth);
// Attach child elements to parent
// Skip the placeholder
parent = ( ui.item.next()[0] == ui.placeholder[0] ) ? ui.item.next() : ui.item;
children = parent.childMenuItems();
transport.append( children );
// Update the height of the placeholder to match the moving item.
height = transport.outerHeight();
// If there are children, account for distance between top of children and parent
height += ( height > 0 ) ? (ui.placeholder.css('margin-top').slice(0, -2) * 1) : 0;
height += ui.helper.outerHeight();
helperHeight = height;
height -= 2; // Subtract 2 for borders
ui.placeholder.height(height);
// Update the width of the placeholder to match the moving item.
maxChildDepth = originalDepth;
children.each(function(){
var depth = $(this).menuItemDepth();
maxChildDepth = (depth > maxChildDepth) ? depth : maxChildDepth;
});
width = ui.helper.find('.menu-item-handle').outerWidth(); // Get original width
width += api.depthToPx(maxChildDepth - originalDepth); // Account for children
width -= 2; // Subtract 2 for borders
ui.placeholder.width(width);
// Update the list of menu items.
tempHolder = ui.placeholder.next();
tempHolder.css( 'margin-top', helperHeight + 'px' ); // Set the margin to absorb the placeholder
ui.placeholder.detach(); // detach or jQuery UI will think the placeholder is a menu item
$(this).sortable( "refresh" ); // The children aren't sortable. We should let jQ UI know.
ui.item.after( ui.placeholder ); // reattach the placeholder.
tempHolder.css('margin-top', 0); // reset the margin
// Now that the element is complete, we can update...
updateSharedVars(ui);
},
stop: function(e, ui) {
var children, depthChange = currentDepth - originalDepth;
// Return child elements to the list
children = transport.children().insertAfter(ui.item);
// Update depth classes
if( depthChange != 0 ) {
ui.item.updateDepthClass( currentDepth );
children.shiftDepthClass( depthChange );
updateMenuMaxDepth( depthChange );
}
// Register a change
api.registerChange();
// Update the item data.
ui.item.updateParentMenuItemDBId();
// address sortable's incorrectly-calculated top in opera
ui.item[0].style.top = 0;
// handle drop placement for rtl orientation
if ( api.isRTL ) {
ui.item[0].style.left = 'auto';
ui.item[0].style.right = 0;
}
// The width of the tab bar might have changed. Just in case.
api.refreshMenuTabs( true );
},
change: function(e, ui) {
// Make sure the placeholder is inside the menu.
// Otherwise fix it, or we're in trouble.
if( ! ui.placeholder.parent().hasClass('menu') )
(prev.length) ? prev.after( ui.placeholder ) : api.menuList.prepend( ui.placeholder );
updateSharedVars(ui);
},
sort: function(e, ui) {
var offset = ui.helper.offset(),
edge = api.isRTL ? offset.left + ui.helper.width() : offset.left,
depth = api.negateIfRTL * api.pxToDepth( edge - menuEdge );
// Check and correct if depth is not within range.
// Also, if the dragged element is dragged upwards over
// an item, shift the placeholder to a child position.
if ( depth > maxDepth || offset.top < prevBottom ) depth = maxDepth;
else if ( depth < minDepth ) depth = minDepth;
if( depth != currentDepth )
updateCurrentDepth(ui, depth);
// If we overlap the next element, manually shift downwards
if( nextThreshold && offset.top + helperHeight > nextThreshold ) {
next.after( ui.placeholder );
updateSharedVars( ui );
$(this).sortable( "refreshPositions" );
}
}
});
function updateSharedVars(ui) {
var depth;
prev = ui.placeholder.prev();
next = ui.placeholder.next();
// Make sure we don't select the moving item.
if( prev[0] == ui.item[0] ) prev = prev.prev();
if( next[0] == ui.item[0] ) next = next.next();
prevBottom = (prev.length) ? prev.offset().top + prev.height() : 0;
nextThreshold = (next.length) ? next.offset().top + next.height() / 3 : 0;
minDepth = (next.length) ? next.menuItemDepth() : 0;
if( prev.length )
maxDepth = ( (depth = prev.menuItemDepth() + 1) > api.options.globalMaxDepth ) ? api.options.globalMaxDepth : depth;
else
maxDepth = 0;
}
function updateCurrentDepth(ui, depth) {
ui.placeholder.updateDepthClass( depth, currentDepth );
currentDepth = depth;
}
function initialMenuMaxDepth() {
if( ! body[0].className ) return 0;
var match = body[0].className.match(/menu-max-depth-(\d+)/);
return match && match[1] ? parseInt(match[1]) : 0;
}
function updateMenuMaxDepth( depthChange ) {
var depth, newDepth = menuMaxDepth;
if ( depthChange === 0 ) {
return;
} else if ( depthChange > 0 ) {
depth = maxChildDepth + depthChange;
if( depth > menuMaxDepth )
newDepth = depth;
} else if ( depthChange < 0 && maxChildDepth == menuMaxDepth ) {
while( ! $('.menu-item-depth-' + newDepth, api.menuList).length && newDepth > 0 )
newDepth--;
}
// Update the depth class.
body.removeClass( 'menu-max-depth-' + menuMaxDepth ).addClass( 'menu-max-depth-' + newDepth );
menuMaxDepth = newDepth;
}
},
attachMenuEditListeners : function() {
var that = this;
$('#update-nav-menu').bind('click', function(e) {
if ( e.target && e.target.className ) {
if ( -1 != e.target.className.indexOf('item-edit') ) {
return that.eventOnClickEditLink(e.target);
} else if ( -1 != e.target.className.indexOf('menu-save') ) {
return that.eventOnClickMenuSave(e.target);
} else if ( -1 != e.target.className.indexOf('menu-delete') ) {
return that.eventOnClickMenuDelete(e.target);
} else if ( -1 != e.target.className.indexOf('item-delete') ) {
return that.eventOnClickMenuItemDelete(e.target);
} else if ( -1 != e.target.className.indexOf('item-cancel') ) {
return that.eventOnClickCancelLink(e.target);
}
}
});
$('#add-custom-links input[type="text"]').keypress(function(e){
if ( e.keyCode === 13 ) {
e.preventDefault();
$("#submit-customlinkdiv").click();
}
});
},
/**
* An interface for managing default values for input elements
* that is both JS and accessibility-friendly.
*
* Input elements that add the class 'input-with-default-title'
* will have their values set to the provided HTML title when empty.
*/
setupInputWithDefaultTitle : function() {
var name = 'input-with-default-title';
$('.' + name).each( function(){
var $t = $(this), title = $t.attr('title'), val = $t.val();
$t.data( name, title );
if( '' == val ) $t.val( title );
else if ( title == val ) return;
else $t.removeClass( name );
}).focus( function(){
var $t = $(this);
if( $t.val() == $t.data(name) )
$t.val('').removeClass( name );
}).blur( function(){
var $t = $(this);
if( '' == $t.val() )
$t.addClass( name ).val( $t.data(name) );
});
},
attachThemeLocationsListeners : function() {
var loc = $('#nav-menu-theme-locations'), params = {};
params['action'] = 'menu-locations-save';
params['menu-settings-column-nonce'] = $('#menu-settings-column-nonce').val();
loc.find('input[type="submit"]').click(function() {
loc.find('select').each(function() {
params[this.name] = $(this).val();
});
loc.find('.spinner').show();
$.post( ajaxurl, params, function(r) {
loc.find('.spinner').hide();
});
return false;
});
},
attachQuickSearchListeners : function() {
var searchTimer;
$('.quick-search').keypress(function(e){
var t = $(this);
if( 13 == e.which ) {
api.updateQuickSearchResults( t );
return false;
}
if( searchTimer ) clearTimeout(searchTimer);
searchTimer = setTimeout(function(){
api.updateQuickSearchResults( t );
}, 400);
}).attr('autocomplete','off');
},
updateQuickSearchResults : function(input) {
var panel, params,
minSearchLength = 2,
q = input.val();
if( q.length < minSearchLength ) return;
panel = input.parents('.tabs-panel');
params = {
'action': 'menu-quick-search',
'response-format': 'markup',
'menu': $('#menu').val(),
'menu-settings-column-nonce': $('#menu-settings-column-nonce').val(),
'q': q,
'type': input.attr('name')
};
$('.spinner', panel).show();
$.post( ajaxurl, params, function(menuMarkup) {
api.processQuickSearchQueryResponse(menuMarkup, params, panel);
});
},
addCustomLink : function( processMethod ) {
var url = $('#custom-menu-item-url').val(),
label = $('#custom-menu-item-name').val();
processMethod = processMethod || api.addMenuItemToBottom;
if ( '' == url || 'http://' == url )
return false;
// Show the ajax spinner
$('.customlinkdiv .spinner').show();
this.addLinkToMenu( url, label, processMethod, function() {
// Remove the ajax spinner
$('.customlinkdiv .spinner').hide();
// Set custom link form back to defaults
$('#custom-menu-item-name').val('').blur();
$('#custom-menu-item-url').val('http://');
});
},
addLinkToMenu : function(url, label, processMethod, callback) {
processMethod = processMethod || api.addMenuItemToBottom;
callback = callback || function(){};
api.addItemToMenu({
'-1': {
'menu-item-type': 'custom',
'menu-item-url': url,
'menu-item-title': label
}
}, processMethod, callback);
},
addItemToMenu : function(menuItem, processMethod, callback) {
var menu = $('#menu').val(),
nonce = $('#menu-settings-column-nonce').val();
processMethod = processMethod || function(){};
callback = callback || function(){};
params = {
'action': 'add-menu-item',
'menu': menu,
'menu-settings-column-nonce': nonce,
'menu-item': menuItem
};
$.post( ajaxurl, params, function(menuMarkup) {
var ins = $('#menu-instructions');
processMethod(menuMarkup, params);
if( ! ins.hasClass('menu-instructions-inactive') && ins.siblings().length )
ins.addClass('menu-instructions-inactive');
callback();
});
},
/**
* Process the add menu item request response into menu list item.
*
* @param string menuMarkup The text server response of menu item markup.
* @param object req The request arguments.
*/
addMenuItemToBottom : function( menuMarkup, req ) {
$(menuMarkup).hideAdvancedMenuItemFields().appendTo( api.targetList );
},
addMenuItemToTop : function( menuMarkup, req ) {
$(menuMarkup).hideAdvancedMenuItemFields().prependTo( api.targetList );
},
attachUnsavedChangesListener : function() {
$('#menu-management input, #menu-management select, #menu-management, #menu-management textarea').change(function(){
api.registerChange();
});
if ( 0 != $('#menu-to-edit').length ) {
window.onbeforeunload = function(){
if ( api.menusChanged )
return navMenuL10n.saveAlert;
};
} else {
// Make the post boxes read-only, as they can't be used yet
$('#menu-settings-column').find('input,select').prop('disabled', true).end().find('a').attr('href', '#').unbind('click');
}
},
registerChange : function() {
api.menusChanged = true;
},
attachTabsPanelListeners : function() {
$('#menu-settings-column').bind('click', function(e) {
var selectAreaMatch, panelId, wrapper, items,
target = $(e.target);
if ( target.hasClass('nav-tab-link') ) {
panelId = /#(.*)$/.exec(e.target.href);
if ( panelId && panelId[1] )
panelId = panelId[1]
else
return false;
wrapper = target.parents('.inside').first();
// upon changing tabs, we want to uncheck all checkboxes
$('input', wrapper).removeAttr('checked');
$('.tabs-panel-active', wrapper).removeClass('tabs-panel-active').addClass('tabs-panel-inactive');
$('#' + panelId, wrapper).removeClass('tabs-panel-inactive').addClass('tabs-panel-active');
$('.tabs', wrapper).removeClass('tabs');
target.parent().addClass('tabs');
// select the search bar
$('.quick-search', wrapper).focus();
return false;
} else if ( target.hasClass('select-all') ) {
selectAreaMatch = /#(.*)$/.exec(e.target.href);
if ( selectAreaMatch && selectAreaMatch[1] ) {
items = $('#' + selectAreaMatch[1] + ' .tabs-panel-active .menu-item-title input');
if( items.length === items.filter(':checked').length )
items.removeAttr('checked');
else
items.prop('checked', true);
return false;
}
} else if ( target.hasClass('submit-add-to-menu') ) {
api.registerChange();
if ( e.target.id && 'submit-customlinkdiv' == e.target.id )
api.addCustomLink( api.addMenuItemToBottom );
else if ( e.target.id && -1 != e.target.id.indexOf('submit-') )
$('#' + e.target.id.replace(/submit-/, '')).addSelectedToMenu( api.addMenuItemToBottom );
return false;
} else if ( target.hasClass('page-numbers') ) {
$.post( ajaxurl, e.target.href.replace(/.*\?/, '').replace(/action=([^&]*)/, '') + '&action=menu-get-metabox',
function( resp ) {
if ( -1 == resp.indexOf('replace-id') )
return;
var metaBoxData = $.parseJSON(resp),
toReplace = document.getElementById(metaBoxData['replace-id']),
placeholder = document.createElement('div'),
wrap = document.createElement('div');
if ( ! metaBoxData['markup'] || ! toReplace )
return;
wrap.innerHTML = metaBoxData['markup'] ? metaBoxData['markup'] : '';
toReplace.parentNode.insertBefore( placeholder, toReplace );
placeholder.parentNode.removeChild( toReplace );
placeholder.parentNode.insertBefore( wrap, placeholder );
placeholder.parentNode.removeChild( placeholder );
}
);
return false;
}
});
},
initTabManager : function() {
var fixed = $('.nav-tabs-wrapper'),
fluid = fixed.children('.nav-tabs'),
active = fluid.children('.nav-tab-active'),
tabs = fluid.children('.nav-tab'),
tabsWidth = 0,
fixedRight, fixedLeft,
arrowLeft, arrowRight, resizeTimer, css = {},
marginFluid = api.isRTL ? 'margin-right' : 'margin-left',
marginFixed = api.isRTL ? 'margin-left' : 'margin-right',
msPerPx = 2;
/**
* Refreshes the menu tabs.
* Will show and hide arrows where necessary.
* Scrolls to the active tab by default.
*
* @param savePosition {boolean} Optional. Prevents scrolling so
* that the current position is maintained. Default false.
**/
api.refreshMenuTabs = function( savePosition ) {
var fixedWidth = fixed.width(),
margin = 0, css = {};
fixedLeft = fixed.offset().left;
fixedRight = fixedLeft + fixedWidth;
if( !savePosition )
active.makeTabVisible();
// Prevent space from building up next to the last tab if there's more to show
if( tabs.last().isTabVisible() ) {
margin = fixed.width() - tabsWidth;
margin = margin > 0 ? 0 : margin;
css[marginFluid] = margin + 'px';
fluid.animate( css, 100, "linear" );
}
// Show the arrows only when necessary
if( fixedWidth > tabsWidth )
arrowLeft.add( arrowRight ).hide();
else
arrowLeft.add( arrowRight ).show();
}
$.fn.extend({
makeTabVisible : function() {
var t = this.eq(0), left, right, css = {}, shift = 0;
if( ! t.length ) return this;
left = t.offset().left;
right = left + t.outerWidth();
if( right > fixedRight )
shift = fixedRight - right;
else if ( left < fixedLeft )
shift = fixedLeft - left;
if( ! shift ) return this;
css[marginFluid] = "+=" + api.negateIfRTL * shift + 'px';
fluid.animate( css, Math.abs( shift ) * msPerPx, "linear" );
return this;
},
isTabVisible : function() {
var t = this.eq(0),
left = t.offset().left,
right = left + t.outerWidth();
return ( right <= fixedRight && left >= fixedLeft ) ? true : false;
}
});
// Find the width of all tabs
tabs.each(function(){
tabsWidth += $(this).outerWidth(true);
});
// Set up fixed margin for overflow, unset padding
css['padding'] = 0;
css[marginFixed] = (-1 * tabsWidth) + 'px';
fluid.css( css );
// Build tab navigation
arrowLeft = $('<div class="nav-tabs-arrow nav-tabs-arrow-left"><a>«</a></div>');
arrowRight = $('<div class="nav-tabs-arrow nav-tabs-arrow-right"><a>»</a></div>');
// Attach to the document
fixed.wrap('<div class="nav-tabs-nav"/>').parent().prepend( arrowLeft ).append( arrowRight );
// Set the menu tabs
api.refreshMenuTabs();
// Make sure the tabs reset on resize
$(window).resize(function() {
if( resizeTimer ) clearTimeout(resizeTimer);
resizeTimer = setTimeout( api.refreshMenuTabs, 200);
});
// Build arrow functions
$.each([{
arrow : arrowLeft,
next : "next",
last : "first",
operator : "+="
},{
arrow : arrowRight,
next : "prev",
last : "last",
operator : "-="
}], function(){
var that = this;
this.arrow.mousedown(function(){
var marginFluidVal = Math.abs( parseInt( fluid.css(marginFluid) ) ),
shift = marginFluidVal,
css = {};
if( "-=" == that.operator )
shift = Math.abs( tabsWidth - fixed.width() ) - marginFluidVal;
if( ! shift ) return;
css[marginFluid] = that.operator + shift + 'px';
fluid.animate( css, shift * msPerPx, "linear" );
}).mouseup(function(){
var tab, next;
fluid.stop(true);
tab = tabs[that.last]();
while( (next = tab[that.next]()) && next.length && ! next.isTabVisible() ) {
tab = next;
}
tab.makeTabVisible();
});
});
},
eventOnClickEditLink : function(clickedEl) {
var settings, item,
matchedSection = /#(.*)$/.exec(clickedEl.href);
if ( matchedSection && matchedSection[1] ) {
settings = $('#'+matchedSection[1]);
item = settings.parent();
if( 0 != item.length ) {
if( item.hasClass('menu-item-edit-inactive') ) {
if( ! settings.data('menu-item-data') ) {
settings.data( 'menu-item-data', settings.getItemData() );
}
settings.slideDown('fast');
item.removeClass('menu-item-edit-inactive')
.addClass('menu-item-edit-active');
} else {
settings.slideUp('fast');
item.removeClass('menu-item-edit-active')
.addClass('menu-item-edit-inactive');
}
return false;
}
}
},
eventOnClickCancelLink : function(clickedEl) {
var settings = $(clickedEl).closest('.menu-item-settings');
settings.setItemData( settings.data('menu-item-data') );
return false;
},
eventOnClickMenuSave : function(clickedEl) {
var locs = '',
menuName = $('#menu-name'),
menuNameVal = menuName.val();
// Cancel and warn if invalid menu name
if( !menuNameVal || menuNameVal == menuName.attr('title') || !menuNameVal.replace(/\s+/, '') ) {
menuName.parent().addClass('form-invalid');
return false;
}
// Copy menu theme locations
$('#nav-menu-theme-locations select').each(function() {
locs += '<input type="hidden" name="' + this.name + '" value="' + $(this).val() + '" />';
});
$('#update-nav-menu').append( locs );
// Update menu item position data
api.menuList.find('.menu-item-data-position').val( function(index) { return index + 1; } );
window.onbeforeunload = null;
return true;
},
eventOnClickMenuDelete : function(clickedEl) {
// Delete warning AYS
if ( confirm( navMenuL10n.warnDeleteMenu ) ) {
window.onbeforeunload = null;
return true;
}
return false;
},
eventOnClickMenuItemDelete : function(clickedEl) {
var itemID = parseInt(clickedEl.id.replace('delete-', ''), 10);
api.removeMenuItem( $('#menu-item-' + itemID) );
api.registerChange();
return false;
},
/**
* Process the quick search response into a search result
*
* @param string resp The server response to the query.
* @param object req The request arguments.
* @param jQuery panel The tabs panel we're searching in.
*/
processQuickSearchQueryResponse : function(resp, req, panel) {
var matched, newID,
takenIDs = {},
form = document.getElementById('nav-menu-meta'),
pattern = new RegExp('menu-item\\[(\[^\\]\]*)', 'g'),
$items = $('<div>').html(resp).find('li'),
$item;
if( ! $items.length ) {
$('.categorychecklist', panel).html( '<li><p>' + navMenuL10n.noResultsFound + '</p></li>' );
$('.spinner', panel).hide();
return;
}
$items.each(function(){
$item = $(this);
// make a unique DB ID number
matched = pattern.exec($item.html());
if ( matched && matched[1] ) {
newID = matched[1];
while( form.elements['menu-item[' + newID + '][menu-item-type]'] || takenIDs[ newID ] ) {
newID--;
}
takenIDs[newID] = true;
if ( newID != matched[1] ) {
$item.html( $item.html().replace(new RegExp(
'menu-item\\[' + matched[1] + '\\]', 'g'),
'menu-item[' + newID + ']'
) );
}
}
});
$('.categorychecklist', panel).html( $items );
$('.spinner', panel).hide();
},
removeMenuItem : function(el) {
var children = el.childMenuItems();
el.addClass('deleting').animate({
opacity : 0,
height: 0
}, 350, function() {
var ins = $('#menu-instructions');
el.remove();
children.shiftDepthClass(-1).updateParentMenuItemDBId();
if( ! ins.siblings().length )
ins.removeClass('menu-instructions-inactive');
});
},
depthToPx : function(depth) {
return depth * api.options.menuItemDepthPerLevel;
},
pxToDepth : function(px) {
return Math.floor(px / api.options.menuItemDepthPerLevel);
}
};
$(document).ready(function(){ wpNavMenu.init(); });
})(jQuery);
| JavaScript |
(function($) {
var frame;
$( function() {
// Fetch available headers and apply jQuery.masonry
// once the images have loaded.
var $headers = $('.available-headers');
$headers.imagesLoaded( function() {
$headers.masonry({
itemSelector: '.default-header',
isRTL: !! ( 'undefined' != typeof isRtl && isRtl )
});
});
// Build the choose from library frame.
$('#choose-from-library-link').click( function( event ) {
var $el = $(this);
event.preventDefault();
// If the media frame already exists, reopen it.
if ( frame ) {
frame.open();
return;
}
// Create the media frame.
frame = wp.media.frames.customHeader = wp.media({
// Set the title of the modal.
title: $el.data('choose'),
// Tell the modal to show only images.
library: {
type: 'image'
},
// Customize the submit button.
button: {
// Set the text of the button.
text: $el.data('update'),
// Tell the button not to close the modal, since we're
// going to refresh the page when the image is selected.
close: false
}
});
// When an image is selected, run a callback.
frame.on( 'select', function() {
// Grab the selected attachment.
var attachment = frame.state().get('selection').first(),
link = $el.data('updateLink');
// Tell the browser to navigate to the crop step.
window.location = link + '&file=' + attachment.id;
});
frame.open();
});
});
}(jQuery));
| JavaScript |
var tagBox, commentsBox, editPermalink, makeSlugeditClickable, WPSetThumbnailHTML, WPSetThumbnailID, WPRemoveThumbnail, wptitlehint;
// return an array with any duplicate, whitespace or values removed
function array_unique_noempty(a) {
var out = [];
jQuery.each( a, function(key, val) {
val = jQuery.trim(val);
if ( val && jQuery.inArray(val, out) == -1 )
out.push(val);
} );
return out;
}
(function($){
tagBox = {
clean : function(tags) {
var comma = postL10n.comma;
if ( ',' !== comma )
tags = tags.replace(new RegExp(comma, 'g'), ',');
tags = tags.replace(/\s*,\s*/g, ',').replace(/,+/g, ',').replace(/[,\s]+$/, '').replace(/^[,\s]+/, '');
if ( ',' !== comma )
tags = tags.replace(/,/g, comma);
return tags;
},
parseTags : function(el) {
var id = el.id, num = id.split('-check-num-')[1], taxbox = $(el).closest('.tagsdiv'),
thetags = taxbox.find('.the-tags'), comma = postL10n.comma,
current_tags = thetags.val().split(comma), new_tags = [];
delete current_tags[num];
$.each( current_tags, function(key, val) {
val = $.trim(val);
if ( val ) {
new_tags.push(val);
}
});
thetags.val( this.clean( new_tags.join(comma) ) );
this.quickClicks(taxbox);
return false;
},
quickClicks : function(el) {
var thetags = $('.the-tags', el),
tagchecklist = $('.tagchecklist', el),
id = $(el).attr('id'),
current_tags, disabled;
if ( !thetags.length )
return;
disabled = thetags.prop('disabled');
current_tags = thetags.val().split(postL10n.comma);
tagchecklist.empty();
$.each( current_tags, function( key, val ) {
var span, xbutton;
val = $.trim( val );
if ( ! val )
return;
// Create a new span, and ensure the text is properly escaped.
span = $('<span />').text( val );
// If tags editing isn't disabled, create the X button.
if ( ! disabled ) {
xbutton = $( '<a id="' + id + '-check-num-' + key + '" class="ntdelbutton">X</a>' );
xbutton.click( function(){ tagBox.parseTags(this); });
span.prepend(' ').prepend( xbutton );
}
// Append the span to the tag list.
tagchecklist.append( span );
});
},
flushTags : function(el, a, f) {
a = a || false;
var tags = $('.the-tags', el),
newtag = $('input.newtag', el),
comma = postL10n.comma,
newtags, text;
text = a ? $(a).text() : newtag.val();
tagsval = tags.val();
newtags = tagsval ? tagsval + comma + text : text;
newtags = this.clean( newtags );
newtags = array_unique_noempty( newtags.split(comma) ).join(comma);
tags.val(newtags);
this.quickClicks(el);
if ( !a )
newtag.val('');
if ( 'undefined' == typeof(f) )
newtag.focus();
return false;
},
get : function(id) {
var tax = id.substr(id.indexOf('-')+1);
$.post(ajaxurl, {'action':'get-tagcloud', 'tax':tax}, function(r, stat) {
if ( 0 == r || 'success' != stat )
r = wpAjax.broken;
r = $('<p id="tagcloud-'+tax+'" class="the-tagcloud">'+r+'</p>');
$('a', r).click(function(){
tagBox.flushTags( $(this).closest('.inside').children('.tagsdiv'), this);
return false;
});
$('#'+id).after(r);
});
},
init : function() {
var t = this, ajaxtag = $('div.ajaxtag');
$('.tagsdiv').each( function() {
tagBox.quickClicks(this);
});
$('input.tagadd', ajaxtag).click(function(){
t.flushTags( $(this).closest('.tagsdiv') );
});
$('div.taghint', ajaxtag).click(function(){
$(this).css('visibility', 'hidden').parent().siblings('.newtag').focus();
});
$('input.newtag', ajaxtag).blur(function() {
if ( this.value == '' )
$(this).parent().siblings('.taghint').css('visibility', '');
}).focus(function(){
$(this).parent().siblings('.taghint').css('visibility', 'hidden');
}).keyup(function(e){
if ( 13 == e.which ) {
tagBox.flushTags( $(this).closest('.tagsdiv') );
return false;
}
}).keypress(function(e){
if ( 13 == e.which ) {
e.preventDefault();
return false;
}
}).each(function(){
var tax = $(this).closest('div.tagsdiv').attr('id');
$(this).suggest( ajaxurl + '?action=ajax-tag-search&tax=' + tax, { delay: 500, minchars: 2, multiple: true, multipleSep: postL10n.comma + ' ' } );
});
// save tags on post save/publish
$('#post').submit(function(){
$('div.tagsdiv').each( function() {
tagBox.flushTags(this, false, 1);
});
});
// tag cloud
$('a.tagcloud-link').click(function(){
if ( ! $('.the-tagcloud').length )
tagBox.get( $(this).attr('id') );
$(this).siblings('.the-tagcloud').toggle();
return false;
});
}
};
commentsBox = {
st : 0,
get : function(total, num) {
var st = this.st, data;
if ( ! num )
num = 20;
this.st += num;
this.total = total;
$('#commentsdiv .spinner').show();
data = {
'action' : 'get-comments',
'mode' : 'single',
'_ajax_nonce' : $('#add_comment_nonce').val(),
'p' : $('#post_ID').val(),
'start' : st,
'number' : num
};
$.post(ajaxurl, data,
function(r) {
r = wpAjax.parseAjaxResponse(r);
$('#commentsdiv .widefat').show();
$('#commentsdiv .spinner').hide();
if ( 'object' == typeof r && r.responses[0] ) {
$('#the-comment-list').append( r.responses[0].data );
theList = theExtraList = null;
$("a[className*=':']").unbind();
if ( commentsBox.st > commentsBox.total )
$('#show-comments').hide();
else
$('#show-comments').show().children('a').html(postL10n.showcomm);
return;
} else if ( 1 == r ) {
$('#show-comments').html(postL10n.endcomm);
return;
}
$('#the-comment-list').append('<tr><td colspan="2">'+wpAjax.broken+'</td></tr>');
}
);
return false;
}
};
WPSetThumbnailHTML = function(html){
$('.inside', '#postimagediv').html(html);
};
WPSetThumbnailID = function(id){
var field = $('input[value="_thumbnail_id"]', '#list-table');
if ( field.size() > 0 ) {
$('#meta\\[' + field.attr('id').match(/[0-9]+/) + '\\]\\[value\\]').text(id);
}
};
WPRemoveThumbnail = function(nonce){
$.post(ajaxurl, {
action:"set-post-thumbnail", post_id: $('#post_ID').val(), thumbnail_id: -1, _ajax_nonce: nonce, cookie: encodeURIComponent(document.cookie)
}, function(str){
if ( str == '0' ) {
alert( setPostThumbnailL10n.error );
} else {
WPSetThumbnailHTML(str);
}
}
);
};
})(jQuery);
jQuery(document).ready( function($) {
var stamp, visibility, sticky = '', last = 0, co = $('#content');
postboxes.add_postbox_toggles(pagenow);
// multi-taxonomies
if ( $('#tagsdiv-post_tag').length ) {
tagBox.init();
} else {
$('#side-sortables, #normal-sortables, #advanced-sortables').children('div.postbox').each(function(){
if ( this.id.indexOf('tagsdiv-') === 0 ) {
tagBox.init();
return false;
}
});
}
// categories
$('.categorydiv').each( function(){
var this_id = $(this).attr('id'), noSyncChecks = false, syncChecks, catAddAfter, taxonomyParts, taxonomy, settingName;
taxonomyParts = this_id.split('-');
taxonomyParts.shift();
taxonomy = taxonomyParts.join('-');
settingName = taxonomy + '_tab';
if ( taxonomy == 'category' )
settingName = 'cats';
// TODO: move to jQuery 1.3+, support for multiple hierarchical taxonomies, see wp-lists.js
$('a', '#' + taxonomy + '-tabs').click( function(){
var t = $(this).attr('href');
$(this).parent().addClass('tabs').siblings('li').removeClass('tabs');
$('#' + taxonomy + '-tabs').siblings('.tabs-panel').hide();
$(t).show();
if ( '#' + taxonomy + '-all' == t )
deleteUserSetting(settingName);
else
setUserSetting(settingName, 'pop');
return false;
});
if ( getUserSetting(settingName) )
$('a[href="#' + taxonomy + '-pop"]', '#' + taxonomy + '-tabs').click();
// Ajax Cat
$('#new' + taxonomy).one( 'focus', function() { $(this).val( '' ).removeClass( 'form-input-tip' ) } );
$('#new' + taxonomy).keypress( function(event){
if( 13 === event.keyCode ) {
event.preventDefault();
$('#' + taxonomy + '-add-submit').click();
}
});
$('#' + taxonomy + '-add-submit').click( function(){ $('#new' + taxonomy).focus(); });
syncChecks = function() {
if ( noSyncChecks )
return;
noSyncChecks = true;
var th = jQuery(this), c = th.is(':checked'), id = th.val().toString();
$('#in-' + taxonomy + '-' + id + ', #in-' + taxonomy + '-category-' + id).prop( 'checked', c );
noSyncChecks = false;
};
catAddBefore = function( s ) {
if ( !$('#new'+taxonomy).val() )
return false;
s.data += '&' + $( ':checked', '#'+taxonomy+'checklist' ).serialize();
$( '#' + taxonomy + '-add-submit' ).prop( 'disabled', true );
return s;
};
catAddAfter = function( r, s ) {
var sup, drop = $('#new'+taxonomy+'_parent');
$( '#' + taxonomy + '-add-submit' ).prop( 'disabled', false );
if ( 'undefined' != s.parsed.responses[0] && (sup = s.parsed.responses[0].supplemental.newcat_parent) ) {
drop.before(sup);
drop.remove();
}
};
$('#' + taxonomy + 'checklist').wpList({
alt: '',
response: taxonomy + '-ajax-response',
addBefore: catAddBefore,
addAfter: catAddAfter
});
$('#' + taxonomy + '-add-toggle').click( function() {
$('#' + taxonomy + '-adder').toggleClass( 'wp-hidden-children' );
$('a[href="#' + taxonomy + '-all"]', '#' + taxonomy + '-tabs').click();
$('#new'+taxonomy).focus();
return false;
});
$('#' + taxonomy + 'checklist li.popular-category input[type="checkbox"], #' + taxonomy + 'checklist-pop input[type="checkbox"]').live( 'click', function(){
var t = $(this), c = t.is(':checked'), id = t.val();
if ( id && t.parents('#taxonomy-'+taxonomy).length )
$('#in-' + taxonomy + '-' + id + ', #in-popular-' + taxonomy + '-' + id).prop( 'checked', c );
});
}); // end cats
// Custom Fields
if ( $('#postcustom').length ) {
$('#the-list').wpList( { addAfter: function( xml, s ) {
$('table#list-table').show();
}, addBefore: function( s ) {
s.data += '&post_id=' + $('#post_ID').val();
return s;
}
});
}
// submitdiv
if ( $('#submitdiv').length ) {
stamp = $('#timestamp').html();
visibility = $('#post-visibility-display').html();
function updateVisibility() {
var pvSelect = $('#post-visibility-select');
if ( $('input:radio:checked', pvSelect).val() != 'public' ) {
$('#sticky').prop('checked', false);
$('#sticky-span').hide();
} else {
$('#sticky-span').show();
}
if ( $('input:radio:checked', pvSelect).val() != 'password' ) {
$('#password-span').hide();
} else {
$('#password-span').show();
}
}
function updateText() {
if ( ! $('#timestampdiv').length )
return true;
var attemptedDate, originalDate, currentDate, publishOn, postStatus = $('#post_status'),
optPublish = $('option[value="publish"]', postStatus), aa = $('#aa').val(),
mm = $('#mm').val(), jj = $('#jj').val(), hh = $('#hh').val(), mn = $('#mn').val();
attemptedDate = new Date( aa, mm - 1, jj, hh, mn );
originalDate = new Date( $('#hidden_aa').val(), $('#hidden_mm').val() -1, $('#hidden_jj').val(), $('#hidden_hh').val(), $('#hidden_mn').val() );
currentDate = new Date( $('#cur_aa').val(), $('#cur_mm').val() -1, $('#cur_jj').val(), $('#cur_hh').val(), $('#cur_mn').val() );
if ( attemptedDate.getFullYear() != aa || (1 + attemptedDate.getMonth()) != mm || attemptedDate.getDate() != jj || attemptedDate.getMinutes() != mn ) {
$('.timestamp-wrap', '#timestampdiv').addClass('form-invalid');
return false;
} else {
$('.timestamp-wrap', '#timestampdiv').removeClass('form-invalid');
}
if ( attemptedDate > currentDate && $('#original_post_status').val() != 'future' ) {
publishOn = postL10n.publishOnFuture;
$('#publish').val( postL10n.schedule );
} else if ( attemptedDate <= currentDate && $('#original_post_status').val() != 'publish' ) {
publishOn = postL10n.publishOn;
$('#publish').val( postL10n.publish );
} else {
publishOn = postL10n.publishOnPast;
$('#publish').val( postL10n.update );
}
if ( originalDate.toUTCString() == attemptedDate.toUTCString() ) { //hack
$('#timestamp').html(stamp);
} else {
$('#timestamp').html(
publishOn + ' <b>' +
$('option[value="' + $('#mm').val() + '"]', '#mm').text() + ' ' +
jj + ', ' +
aa + ' @ ' +
hh + ':' +
mn + '</b> '
);
}
if ( $('input:radio:checked', '#post-visibility-select').val() == 'private' ) {
$('#publish').val( postL10n.update );
if ( optPublish.length == 0 ) {
postStatus.append('<option value="publish">' + postL10n.privatelyPublished + '</option>');
} else {
optPublish.html( postL10n.privatelyPublished );
}
$('option[value="publish"]', postStatus).prop('selected', true);
$('.edit-post-status', '#misc-publishing-actions').hide();
} else {
if ( $('#original_post_status').val() == 'future' || $('#original_post_status').val() == 'draft' ) {
if ( optPublish.length ) {
optPublish.remove();
postStatus.val($('#hidden_post_status').val());
}
} else {
optPublish.html( postL10n.published );
}
if ( postStatus.is(':hidden') )
$('.edit-post-status', '#misc-publishing-actions').show();
}
$('#post-status-display').html($('option:selected', postStatus).text());
if ( $('option:selected', postStatus).val() == 'private' || $('option:selected', postStatus).val() == 'publish' ) {
$('#save-post').hide();
} else {
$('#save-post').show();
if ( $('option:selected', postStatus).val() == 'pending' ) {
$('#save-post').show().val( postL10n.savePending );
} else {
$('#save-post').show().val( postL10n.saveDraft );
}
}
return true;
}
$('.edit-visibility', '#visibility').click(function () {
if ($('#post-visibility-select').is(":hidden")) {
updateVisibility();
$('#post-visibility-select').slideDown('fast');
$(this).hide();
}
return false;
});
$('.cancel-post-visibility', '#post-visibility-select').click(function () {
$('#post-visibility-select').slideUp('fast');
$('#visibility-radio-' + $('#hidden-post-visibility').val()).prop('checked', true);
$('#post_password').val($('#hidden_post_password').val());
$('#sticky').prop('checked', $('#hidden-post-sticky').prop('checked'));
$('#post-visibility-display').html(visibility);
$('.edit-visibility', '#visibility').show();
updateText();
return false;
});
$('.save-post-visibility', '#post-visibility-select').click(function () { // crazyhorse - multiple ok cancels
var pvSelect = $('#post-visibility-select');
pvSelect.slideUp('fast');
$('.edit-visibility', '#visibility').show();
updateText();
if ( $('input:radio:checked', pvSelect).val() != 'public' ) {
$('#sticky').prop('checked', false);
} // WEAPON LOCKED
if ( true == $('#sticky').prop('checked') ) {
sticky = 'Sticky';
} else {
sticky = '';
}
$('#post-visibility-display').html( postL10n[$('input:radio:checked', pvSelect).val() + sticky] );
return false;
});
$('input:radio', '#post-visibility-select').change(function() {
updateVisibility();
});
$('#timestampdiv').siblings('a.edit-timestamp').click(function() {
if ($('#timestampdiv').is(":hidden")) {
$('#timestampdiv').slideDown('fast');
$('#mm').focus();
$(this).hide();
}
return false;
});
$('.cancel-timestamp', '#timestampdiv').click(function() {
$('#timestampdiv').slideUp('fast');
$('#mm').val($('#hidden_mm').val());
$('#jj').val($('#hidden_jj').val());
$('#aa').val($('#hidden_aa').val());
$('#hh').val($('#hidden_hh').val());
$('#mn').val($('#hidden_mn').val());
$('#timestampdiv').siblings('a.edit-timestamp').show();
updateText();
return false;
});
$('.save-timestamp', '#timestampdiv').click(function () { // crazyhorse - multiple ok cancels
if ( updateText() ) {
$('#timestampdiv').slideUp('fast');
$('#timestampdiv').siblings('a.edit-timestamp').show();
}
return false;
});
$('#post').on( 'submit', function(e){
if ( ! updateText() ) {
e.preventDefault();
$('#timestampdiv').show();
$('#publishing-action .spinner').hide();
$('#publish').prop('disabled', false).removeClass('button-primary-disabled');
return false;
}
});
$('#post-status-select').siblings('a.edit-post-status').click(function() {
if ($('#post-status-select').is(":hidden")) {
$('#post-status-select').slideDown('fast');
$(this).hide();
}
return false;
});
$('.save-post-status', '#post-status-select').click(function() {
$('#post-status-select').slideUp('fast');
$('#post-status-select').siblings('a.edit-post-status').show();
updateText();
return false;
});
$('.cancel-post-status', '#post-status-select').click(function() {
$('#post-status-select').slideUp('fast');
$('#post_status').val($('#hidden_post_status').val());
$('#post-status-select').siblings('a.edit-post-status').show();
updateText();
return false;
});
} // end submitdiv
// permalink
if ( $('#edit-slug-box').length ) {
editPermalink = function(post_id) {
var i, c = 0, e = $('#editable-post-name'), revert_e = e.html(), real_slug = $('#post_name'), revert_slug = real_slug.val(), b = $('#edit-slug-buttons'), revert_b = b.html(), full = $('#editable-post-name-full').html();
$('#view-post-btn').hide();
b.html('<a href="#" class="save button button-small">'+postL10n.ok+'</a> <a class="cancel" href="#">'+postL10n.cancel+'</a>');
b.children('.save').click(function() {
var new_slug = e.children('input').val();
if ( new_slug == $('#editable-post-name-full').text() ) {
return $('.cancel', '#edit-slug-buttons').click();
}
$.post(ajaxurl, {
action: 'sample-permalink',
post_id: post_id,
new_slug: new_slug,
new_title: $('#title').val(),
samplepermalinknonce: $('#samplepermalinknonce').val()
}, function(data) {
$('#edit-slug-box').html(data);
b.html(revert_b);
real_slug.val(new_slug);
makeSlugeditClickable();
$('#view-post-btn').show();
});
return false;
});
$('.cancel', '#edit-slug-buttons').click(function() {
$('#view-post-btn').show();
e.html(revert_e);
b.html(revert_b);
real_slug.val(revert_slug);
return false;
});
for ( i = 0; i < full.length; ++i ) {
if ( '%' == full.charAt(i) )
c++;
}
slug_value = ( c > full.length / 4 ) ? '' : full;
e.html('<input type="text" id="new-post-slug" value="'+slug_value+'" />').children('input').keypress(function(e){
var key = e.keyCode || 0;
// on enter, just save the new slug, don't save the post
if ( 13 == key ) {
b.children('.save').click();
return false;
}
if ( 27 == key ) {
b.children('.cancel').click();
return false;
}
real_slug.val(this.value);
}).focus();
}
makeSlugeditClickable = function() {
$('#editable-post-name').click(function() {
$('#edit-slug-buttons').children('.edit-slug').click();
});
}
makeSlugeditClickable();
}
// word count
if ( typeof(wpWordCount) != 'undefined' ) {
$(document).triggerHandler('wpcountwords', [ co.val() ]);
co.keyup( function(e) {
var k = e.keyCode || e.charCode;
if ( k == last )
return true;
if ( 13 == k || 8 == last || 46 == last )
$(document).triggerHandler('wpcountwords', [ co.val() ]);
last = k;
return true;
});
}
wptitlehint = function(id) {
id = id || 'title';
var title = $('#' + id), titleprompt = $('#' + id + '-prompt-text');
if ( title.val() == '' )
titleprompt.removeClass('screen-reader-text');
titleprompt.click(function(){
$(this).addClass('screen-reader-text');
title.focus();
});
title.blur(function(){
if ( this.value == '' )
titleprompt.removeClass('screen-reader-text');
}).focus(function(){
titleprompt.addClass('screen-reader-text');
}).keydown(function(e){
titleprompt.addClass('screen-reader-text');
$(this).unbind(e);
});
}
wptitlehint();
// resizable textarea#content
(function() {
var textarea = $('textarea#content'), offset = null, el;
// No point for touch devices
if ( 'ontouchstart' in window )
return;
function dragging(e) {
textarea.height( Math.max(50, offset + e.pageY) + 'px' );
return false;
}
function endDrag(e) {
var height = $('#wp-content-editor-container').height();
textarea.focus();
$(document).unbind('mousemove', dragging).unbind('mouseup', endDrag);
height -= 33; // compensate for toolbars, padding...
// sanity check
if ( height > 50 && height < 5000 && height != getUserSetting( 'ed_size' ) )
setUserSetting( 'ed_size', height );
}
textarea.css('resize', 'none');
el = $('<div id="content-resize-handle"><br></div>');
$('#wp-content-wrap').append(el);
el.on('mousedown', function(e) {
offset = textarea.height() - e.pageY;
textarea.blur();
$(document).mousemove(dragging).mouseup(endDrag);
return false;
});
})();
if ( typeof(tinymce) != 'undefined' ) {
tinymce.onAddEditor.add(function(mce, ed){
// iOS expands the iframe to full height and the user cannot adjust it.
if ( ed.id != 'content' || tinymce.isIOS5 )
return;
// resize TinyMCE to match the textarea height when switching Text -> Visual
ed.onLoadContent.add( function(ed, o) {
var ifr_height, height = parseInt( $('#content').css('height'), 10 ),
tb_height = $('#content_tbl tr.mceFirst').height();
if ( height && !isNaN(height) && tb_height ) {
ifr_height = (height - tb_height) + 12; // compensate for padding in the textarea
// sanity check
if ( ifr_height > 50 && ifr_height < 5000 ) {
$('#content_tbl').css('height', '' );
$('#content_ifr').css('height', ifr_height + 'px' );
}
}
});
// resize the textarea to match TinyMCE's height when switching Visual -> Text
ed.onSaveContent.add( function(ed, o) {
var height = $('#content_tbl').height();
if ( height && height > 83 && height < 5000 ) {
height -= 33;
$('#content').css( 'height', height + 'px' );
}
});
// save on resizing TinyMCE
ed.onPostRender.add(function() {
$('#content_resize').on('mousedown.wp-mce-resize', function(e){
$(document).on('mouseup.wp-mce-resize', function(e){
var height = $('#wp-content-editor-container').height();
height -= 33;
// sanity check
if ( height > 50 && height < 5000 && height != getUserSetting( 'ed_size' ) )
setUserSetting( 'ed_size', height );
$(document).off('mouseup.wp-mce-resize');
});
});
});
});
}
});
| JavaScript |
/**
* PubSub
*
* A lightweight publish/subscribe implementation.
* Private use only!
*/
var PubSub, fullscreen, wptitlehint;
PubSub = function() {
this.topics = {};
};
PubSub.prototype.subscribe = function( topic, callback ) {
if ( ! this.topics[ topic ] )
this.topics[ topic ] = [];
this.topics[ topic ].push( callback );
return callback;
};
PubSub.prototype.unsubscribe = function( topic, callback ) {
var i, l,
topics = this.topics[ topic ];
if ( ! topics )
return callback || [];
// Clear matching callbacks
if ( callback ) {
for ( i = 0, l = topics.length; i < l; i++ ) {
if ( callback == topics[i] )
topics.splice( i, 1 );
}
return callback;
// Clear all callbacks
} else {
this.topics[ topic ] = [];
return topics;
}
};
PubSub.prototype.publish = function( topic, args ) {
var i, l, broken,
topics = this.topics[ topic ];
if ( ! topics )
return;
args = args || [];
for ( i = 0, l = topics.length; i < l; i++ ) {
broken = ( topics[i].apply( null, args ) === false || broken );
}
return ! broken;
};
/**
* Distraction Free Writing
* (wp-fullscreen)
*
* Access the API globally using the fullscreen variable.
*/
(function($){
var api, ps, bounder, s;
// Initialize the fullscreen/api object
fullscreen = api = {};
// Create the PubSub (publish/subscribe) interface.
ps = api.pubsub = new PubSub();
timer = 0;
block = false;
s = api.settings = { // Settings
visible : false,
mode : 'tinymce',
editor_id : 'content',
title_id : '',
timer : 0,
toolbar_shown : false
}
/**
* Bounder
*
* Creates a function that publishes start/stop topics.
* Used to throttle events.
*/
bounder = api.bounder = function( start, stop, delay, e ) {
var y, top;
delay = delay || 1250;
if ( e ) {
y = e.pageY || e.clientY || e.offsetY;
top = $(document).scrollTop();
if ( !e.isDefaultPrevented ) // test if e ic jQuery normalized
y = 135 + y;
if ( y - top > 120 )
return;
}
if ( block )
return;
block = true;
setTimeout( function() {
block = false;
}, 400 );
if ( s.timer )
clearTimeout( s.timer );
else
ps.publish( start );
function timed() {
ps.publish( stop );
s.timer = 0;
}
s.timer = setTimeout( timed, delay );
};
/**
* on()
*
* Turns fullscreen on.
*
* @param string mode Optional. Switch to the given mode before opening.
*/
api.on = function() {
if ( s.visible )
return;
// Settings can be added or changed by defining "wp_fullscreen_settings" JS object.
if ( typeof(wp_fullscreen_settings) == 'object' )
$.extend( s, wp_fullscreen_settings );
s.editor_id = wpActiveEditor || 'content';
if ( $('input#title').length && s.editor_id == 'content' )
s.title_id = 'title';
else if ( $('input#' + s.editor_id + '-title').length ) // the title input field should have [editor_id]-title HTML ID to be auto detected
s.title_id = s.editor_id + '-title';
else
$('#wp-fullscreen-title, #wp-fullscreen-title-prompt-text').hide();
s.mode = $('#' + s.editor_id).is(':hidden') ? 'tinymce' : 'html';
s.qt_canvas = $('#' + s.editor_id).get(0);
if ( ! s.element )
api.ui.init();
s.is_mce_on = s.has_tinymce && typeof( tinyMCE.get(s.editor_id) ) != 'undefined';
api.ui.fade( 'show', 'showing', 'shown' );
};
/**
* off()
*
* Turns fullscreen off.
*/
api.off = function() {
if ( ! s.visible )
return;
api.ui.fade( 'hide', 'hiding', 'hidden' );
};
/**
* switchmode()
*
* @return string - The current mode.
*
* @param string to - The fullscreen mode to switch to.
* @event switchMode
* @eventparam string to - The new mode.
* @eventparam string from - The old mode.
*/
api.switchmode = function( to ) {
var from = s.mode;
if ( ! to || ! s.visible || ! s.has_tinymce )
return from;
// Don't switch if the mode is the same.
if ( from == to )
return from;
ps.publish( 'switchMode', [ from, to ] );
s.mode = to;
ps.publish( 'switchedMode', [ from, to ] );
return to;
};
/**
* General
*/
api.save = function() {
var hidden = $('#hiddenaction'), old = hidden.val(), spinner = $('#wp-fullscreen-save .spinner'),
message = $('#wp-fullscreen-save span');
spinner.show();
api.savecontent();
hidden.val('wp-fullscreen-save-post');
$.post( ajaxurl, $('form#post').serialize(), function(r){
spinner.hide();
message.show();
setTimeout( function(){
message.fadeOut(1000);
}, 3000 );
if ( r.last_edited )
$('#wp-fullscreen-save input').attr( 'title', r.last_edited );
}, 'json');
hidden.val(old);
}
api.savecontent = function() {
var ed, content;
if ( s.title_id )
$('#' + s.title_id).val( $('#wp-fullscreen-title').val() );
if ( s.mode === 'tinymce' && (ed = tinyMCE.get('wp_mce_fullscreen')) ) {
content = ed.save();
} else {
content = $('#wp_mce_fullscreen').val();
}
$('#' + s.editor_id).val( content );
$(document).triggerHandler('wpcountwords', [ content ]);
}
set_title_hint = function( title ) {
if ( ! title.val().length )
title.siblings('label').css( 'visibility', '' );
else
title.siblings('label').css( 'visibility', 'hidden' );
}
api.dfw_width = function(n) {
var el = $('#wp-fullscreen-wrap'), w = el.width();
if ( !n ) { // reset to theme width
el.width( $('#wp-fullscreen-central-toolbar').width() );
deleteUserSetting('dfw_width');
return;
}
w = n + w;
if ( w < 200 || w > 1200 ) // sanity check
return;
el.width( w );
setUserSetting('dfw_width', w);
}
ps.subscribe( 'showToolbar', function() {
s.toolbars.removeClass('fade-1000').addClass('fade-300');
api.fade.In( s.toolbars, 300, function(){ ps.publish('toolbarShown'); }, true );
$('#wp-fullscreen-body').addClass('wp-fullscreen-focus');
s.toolbar_shown = true;
});
ps.subscribe( 'hideToolbar', function() {
s.toolbars.removeClass('fade-300').addClass('fade-1000');
api.fade.Out( s.toolbars, 1000, function(){ ps.publish('toolbarHidden'); }, true );
$('#wp-fullscreen-body').removeClass('wp-fullscreen-focus');
});
ps.subscribe( 'toolbarShown', function() {
s.toolbars.removeClass('fade-300');
});
ps.subscribe( 'toolbarHidden', function() {
s.toolbars.removeClass('fade-1000');
s.toolbar_shown = false;
});
ps.subscribe( 'show', function() { // This event occurs before the overlay blocks the UI.
var title;
if ( s.title_id ) {
title = $('#wp-fullscreen-title').val( $('#' + s.title_id).val() );
set_title_hint( title );
}
$('#wp-fullscreen-save input').attr( 'title', $('#last-edit').text() );
s.textarea_obj.value = s.qt_canvas.value;
if ( s.has_tinymce && s.mode === 'tinymce' )
tinyMCE.execCommand('wpFullScreenInit');
s.orig_y = $(window).scrollTop();
});
ps.subscribe( 'showing', function() { // This event occurs while the DFW overlay blocks the UI.
$( document.body ).addClass( 'fullscreen-active' );
api.refresh_buttons();
$( document ).bind( 'mousemove.fullscreen', function(e) { bounder( 'showToolbar', 'hideToolbar', 2000, e ); } );
bounder( 'showToolbar', 'hideToolbar', 2000 );
api.bind_resize();
setTimeout( api.resize_textarea, 200 );
// scroll to top so the user is not disoriented
scrollTo(0, 0);
// needed it for IE7 and compat mode
$('#wpadminbar').hide();
});
ps.subscribe( 'shown', function() { // This event occurs after the DFW overlay is shown
var interim_init;
s.visible = true;
// init the standard TinyMCE instance if missing
if ( s.has_tinymce && ! s.is_mce_on ) {
interim_init = function(mce, ed) {
var el = ed.getElement(), old_val = el.value, settings = tinyMCEPreInit.mceInit[s.editor_id];
if ( settings && settings.wpautop && typeof(switchEditors) != 'undefined' )
el.value = switchEditors.wpautop( el.value );
ed.onInit.add(function(ed) {
ed.hide();
ed.getElement().value = old_val;
tinymce.onAddEditor.remove(interim_init);
});
};
tinymce.onAddEditor.add(interim_init);
tinyMCE.init(tinyMCEPreInit.mceInit[s.editor_id]);
s.is_mce_on = true;
}
wpActiveEditor = 'wp_mce_fullscreen';
});
ps.subscribe( 'hide', function() { // This event occurs before the overlay blocks DFW.
var htmled_is_hidden = $('#' + s.editor_id).is(':hidden');
// Make sure the correct editor is displaying.
if ( s.has_tinymce && s.mode === 'tinymce' && !htmled_is_hidden ) {
switchEditors.go(s.editor_id, 'tmce');
} else if ( s.mode === 'html' && htmled_is_hidden ) {
switchEditors.go(s.editor_id, 'html');
}
// Save content must be after switchEditors or content will be overwritten. See #17229.
api.savecontent();
$( document ).unbind( '.fullscreen' );
$(s.textarea_obj).unbind('.grow');
if ( s.has_tinymce && s.mode === 'tinymce' )
tinyMCE.execCommand('wpFullScreenSave');
if ( s.title_id )
set_title_hint( $('#' + s.title_id) );
s.qt_canvas.value = s.textarea_obj.value;
});
ps.subscribe( 'hiding', function() { // This event occurs while the overlay blocks the DFW UI.
$( document.body ).removeClass( 'fullscreen-active' );
scrollTo(0, s.orig_y);
$('#wpadminbar').show();
});
ps.subscribe( 'hidden', function() { // This event occurs after DFW is removed.
s.visible = false;
$('#wp_mce_fullscreen, #wp-fullscreen-title').removeAttr('style');
if ( s.has_tinymce && s.is_mce_on )
tinyMCE.execCommand('wpFullScreenClose');
s.textarea_obj.value = '';
api.oldheight = 0;
wpActiveEditor = s.editor_id;
});
ps.subscribe( 'switchMode', function( from, to ) {
var ed;
if ( !s.has_tinymce || !s.is_mce_on )
return;
ed = tinyMCE.get('wp_mce_fullscreen');
if ( from === 'html' && to === 'tinymce' ) {
if ( tinyMCE.get(s.editor_id).getParam('wpautop') && typeof(switchEditors) != 'undefined' )
s.textarea_obj.value = switchEditors.wpautop( s.textarea_obj.value );
if ( 'undefined' == typeof(ed) )
tinyMCE.execCommand('wpFullScreenInit');
else
ed.show();
} else if ( from === 'tinymce' && to === 'html' ) {
if ( ed )
ed.hide();
}
});
ps.subscribe( 'switchedMode', function( from, to ) {
api.refresh_buttons(true);
if ( to === 'html' )
setTimeout( api.resize_textarea, 200 );
});
/**
* Buttons
*/
api.b = function() {
if ( s.has_tinymce && 'tinymce' === s.mode )
tinyMCE.execCommand('Bold');
}
api.i = function() {
if ( s.has_tinymce && 'tinymce' === s.mode )
tinyMCE.execCommand('Italic');
}
api.ul = function() {
if ( s.has_tinymce && 'tinymce' === s.mode )
tinyMCE.execCommand('InsertUnorderedList');
}
api.ol = function() {
if ( s.has_tinymce && 'tinymce' === s.mode )
tinyMCE.execCommand('InsertOrderedList');
}
api.link = function() {
if ( s.has_tinymce && 'tinymce' === s.mode )
tinyMCE.execCommand('WP_Link');
else
wpLink.open();
}
api.unlink = function() {
if ( s.has_tinymce && 'tinymce' === s.mode )
tinyMCE.execCommand('unlink');
}
api.atd = function() {
if ( s.has_tinymce && 'tinymce' === s.mode )
tinyMCE.execCommand('mceWritingImprovementTool');
}
api.help = function() {
if ( s.has_tinymce && 'tinymce' === s.mode )
tinyMCE.execCommand('WP_Help');
}
api.blockquote = function() {
if ( s.has_tinymce && 'tinymce' === s.mode )
tinyMCE.execCommand('mceBlockQuote');
}
api.medialib = function() {
if ( typeof wp !== 'undefined' && wp.media && wp.media.editor )
wp.media.editor.open(s.editor_id);
}
api.refresh_buttons = function( fade ) {
fade = fade || false;
if ( s.mode === 'html' ) {
$('#wp-fullscreen-mode-bar').removeClass('wp-tmce-mode').addClass('wp-html-mode');
if ( fade )
$('#wp-fullscreen-button-bar').fadeOut( 150, function(){
$(this).addClass('wp-html-mode').fadeIn( 150 );
});
else
$('#wp-fullscreen-button-bar').addClass('wp-html-mode');
} else if ( s.mode === 'tinymce' ) {
$('#wp-fullscreen-mode-bar').removeClass('wp-html-mode').addClass('wp-tmce-mode');
if ( fade )
$('#wp-fullscreen-button-bar').fadeOut( 150, function(){
$(this).removeClass('wp-html-mode').fadeIn( 150 );
});
else
$('#wp-fullscreen-button-bar').removeClass('wp-html-mode');
}
}
/**
* UI Elements
*
* Used for transitioning between states.
*/
api.ui = {
init: function() {
var topbar = $('#fullscreen-topbar'), txtarea = $('#wp_mce_fullscreen'), last = 0;
s.toolbars = topbar.add( $('#wp-fullscreen-status') );
s.element = $('#fullscreen-fader');
s.textarea_obj = txtarea[0];
s.has_tinymce = typeof(tinymce) != 'undefined';
if ( !s.has_tinymce )
$('#wp-fullscreen-mode-bar').hide();
if ( wptitlehint && $('#wp-fullscreen-title').length )
wptitlehint('wp-fullscreen-title');
$(document).keyup(function(e){
var c = e.keyCode || e.charCode, a, data;
if ( !fullscreen.settings.visible )
return true;
if ( navigator.platform && navigator.platform.indexOf('Mac') != -1 )
a = e.ctrlKey; // Ctrl key for Mac
else
a = e.altKey; // Alt key for Win & Linux
if ( 27 == c ) { // Esc
data = {
event: e,
what: 'dfw',
cb: fullscreen.off,
condition: function(){
if ( $('#TB_window').is(':visible') || $('.wp-dialog').is(':visible') )
return false;
return true;
}
};
if ( ! jQuery(document).triggerHandler( 'wp_CloseOnEscape', [data] ) )
fullscreen.off();
}
if ( a && (61 == c || 107 == c || 187 == c) ) // +
api.dfw_width(25);
if ( a && (45 == c || 109 == c || 189 == c) ) // -
api.dfw_width(-25);
if ( a && 48 == c ) // 0
api.dfw_width(0);
return false;
});
// word count in Text mode
if ( typeof(wpWordCount) != 'undefined' ) {
txtarea.keyup( function(e) {
var k = e.keyCode || e.charCode;
if ( k == last )
return true;
if ( 13 == k || 8 == last || 46 == last )
$(document).triggerHandler('wpcountwords', [ txtarea.val() ]);
last = k;
return true;
});
}
topbar.mouseenter(function(e){
s.toolbars.addClass('fullscreen-make-sticky');
$( document ).unbind( '.fullscreen' );
clearTimeout( s.timer );
s.timer = 0;
}).mouseleave(function(e){
s.toolbars.removeClass('fullscreen-make-sticky');
if ( s.visible )
$( document ).bind( 'mousemove.fullscreen', function(e) { bounder( 'showToolbar', 'hideToolbar', 2000, e ); } );
});
},
fade: function( before, during, after ) {
if ( ! s.element )
api.ui.init();
// If any callback bound to before returns false, bail.
if ( before && ! ps.publish( before ) )
return;
api.fade.In( s.element, 600, function() {
if ( during )
ps.publish( during );
api.fade.Out( s.element, 600, function() {
if ( after )
ps.publish( after );
})
});
}
};
api.fade = {
transitionend: 'transitionend webkitTransitionEnd oTransitionEnd',
// Sensitivity to allow browsers to render the blank element before animating.
sensitivity: 100,
In: function( element, speed, callback, stop ) {
callback = callback || $.noop;
speed = speed || 400;
stop = stop || false;
if ( api.fade.transitions ) {
if ( element.is(':visible') ) {
element.addClass( 'fade-trigger' );
return element;
}
element.show();
element.first().one( this.transitionend, function() {
callback();
});
setTimeout( function() { element.addClass( 'fade-trigger' ); }, this.sensitivity );
} else {
if ( stop )
element.stop();
element.css( 'opacity', 1 );
element.first().fadeIn( speed, callback );
if ( element.length > 1 )
element.not(':first').fadeIn( speed );
}
return element;
},
Out: function( element, speed, callback, stop ) {
callback = callback || $.noop;
speed = speed || 400;
stop = stop || false;
if ( ! element.is(':visible') )
return element;
if ( api.fade.transitions ) {
element.first().one( api.fade.transitionend, function() {
if ( element.hasClass('fade-trigger') )
return;
element.hide();
callback();
});
setTimeout( function() { element.removeClass( 'fade-trigger' ); }, this.sensitivity );
} else {
if ( stop )
element.stop();
element.first().fadeOut( speed, callback );
if ( element.length > 1 )
element.not(':first').fadeOut( speed );
}
return element;
},
transitions: (function() { // Check if the browser supports CSS 3.0 transitions
var s = document.documentElement.style;
return ( typeof ( s.WebkitTransition ) == 'string' ||
typeof ( s.MozTransition ) == 'string' ||
typeof ( s.OTransition ) == 'string' ||
typeof ( s.transition ) == 'string' );
})()
};
/**
* Resize API
*
* Automatically updates textarea height.
*/
api.bind_resize = function() {
$(s.textarea_obj).bind('keypress.grow click.grow paste.grow', function(){
setTimeout( api.resize_textarea, 200 );
});
}
api.oldheight = 0;
api.resize_textarea = function() {
var txt = s.textarea_obj, newheight;
newheight = txt.scrollHeight > 300 ? txt.scrollHeight : 300;
if ( newheight != api.oldheight ) {
txt.style.height = newheight + 'px';
api.oldheight = newheight;
}
};
})(jQuery);
| JavaScript |
var thickDims, tbWidth, tbHeight;
jQuery(document).ready(function($) {
thickDims = function() {
var tbWindow = $('#TB_window'), H = $(window).height(), W = $(window).width(), w, h;
w = (tbWidth && tbWidth < W - 90) ? tbWidth : W - 90;
h = (tbHeight && tbHeight < H - 60) ? tbHeight : H - 60;
if ( tbWindow.size() ) {
tbWindow.width(w).height(h);
$('#TB_iframeContent').width(w).height(h - 27);
tbWindow.css({'margin-left': '-' + parseInt((w / 2),10) + 'px'});
if ( typeof document.body.style.maxWidth != 'undefined' )
tbWindow.css({'top':'30px','margin-top':'0'});
}
};
thickDims();
$(window).resize( function() { thickDims() } );
$('a.thickbox-preview').click( function() {
tb_click.call(this);
var alink = $(this).parents('.available-theme').find('.activatelink'), link = '', href = $(this).attr('href'), url, text;
if ( tbWidth = href.match(/&tbWidth=[0-9]+/) )
tbWidth = parseInt(tbWidth[0].replace(/[^0-9]+/g, ''), 10);
else
tbWidth = $(window).width() - 90;
if ( tbHeight = href.match(/&tbHeight=[0-9]+/) )
tbHeight = parseInt(tbHeight[0].replace(/[^0-9]+/g, ''), 10);
else
tbHeight = $(window).height() - 60;
if ( alink.length ) {
url = alink.attr('href') || '';
text = alink.attr('title') || '';
link = ' <a href="' + url + '" target="_top" class="tb-theme-preview-link">' + text + '</a>';
} else {
text = $(this).attr('title') || '';
link = ' <span class="tb-theme-preview-link">' + text + '</span>';
}
$('#TB_title').css({'background-color':'#222','color':'#dfdfdf'});
$('#TB_closeAjaxWindow').css({'float':'left'});
$('#TB_ajaxWindowTitle').css({'float':'right'}).html(link);
$('#TB_iframeContent').width('100%');
thickDims();
return false;
} );
});
| JavaScript |
/*!
* Farbtastic: jQuery color picker plug-in v1.3u
*
* Licensed under the GPL license:
* http://www.gnu.org/licenses/gpl.html
*/
(function($) {
$.fn.farbtastic = function (options) {
$.farbtastic(this, options);
return this;
};
$.farbtastic = function (container, callback) {
var container = $(container).get(0);
return container.farbtastic || (container.farbtastic = new $._farbtastic(container, callback));
};
$._farbtastic = function (container, callback) {
// Store farbtastic object
var fb = this;
// Insert markup
$(container).html('<div class="farbtastic"><div class="color"></div><div class="wheel"></div><div class="overlay"></div><div class="h-marker marker"></div><div class="sl-marker marker"></div></div>');
var e = $('.farbtastic', container);
fb.wheel = $('.wheel', container).get(0);
// Dimensions
fb.radius = 84;
fb.square = 100;
fb.width = 194;
// Fix background PNGs in IE6
if (navigator.appVersion.match(/MSIE [0-6]\./)) {
$('*', e).each(function () {
if (this.currentStyle.backgroundImage != 'none') {
var image = this.currentStyle.backgroundImage;
image = this.currentStyle.backgroundImage.substring(5, image.length - 2);
$(this).css({
'backgroundImage': 'none',
'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='" + image + "')"
});
}
});
}
/**
* Link to the given element(s) or callback.
*/
fb.linkTo = function (callback) {
// Unbind previous nodes
if (typeof fb.callback == 'object') {
$(fb.callback).unbind('keyup', fb.updateValue);
}
// Reset color
fb.color = null;
// Bind callback or elements
if (typeof callback == 'function') {
fb.callback = callback;
}
else if (typeof callback == 'object' || typeof callback == 'string') {
fb.callback = $(callback);
fb.callback.bind('keyup', fb.updateValue);
if (fb.callback.get(0).value) {
fb.setColor(fb.callback.get(0).value);
}
}
return this;
};
fb.updateValue = function (event) {
if (this.value && this.value != fb.color) {
fb.setColor(this.value);
}
};
/**
* Change color with HTML syntax #123456
*/
fb.setColor = function (color) {
var unpack = fb.unpack(color);
if (fb.color != color && unpack) {
fb.color = color;
fb.rgb = unpack;
fb.hsl = fb.RGBToHSL(fb.rgb);
fb.updateDisplay();
}
return this;
};
/**
* Change color with HSL triplet [0..1, 0..1, 0..1]
*/
fb.setHSL = function (hsl) {
fb.hsl = hsl;
fb.rgb = fb.HSLToRGB(hsl);
fb.color = fb.pack(fb.rgb);
fb.updateDisplay();
return this;
};
/////////////////////////////////////////////////////
/**
* Retrieve the coordinates of the given event relative to the center
* of the widget.
*/
fb.widgetCoords = function (event) {
var offset = $(fb.wheel).offset();
return { x: (event.pageX - offset.left) - fb.width / 2, y: (event.pageY - offset.top) - fb.width / 2 };
};
/**
* Mousedown handler
*/
fb.mousedown = function (event) {
// Capture mouse
if (!document.dragging) {
$(document).bind('mousemove', fb.mousemove).bind('mouseup', fb.mouseup);
document.dragging = true;
}
// Check which area is being dragged
var pos = fb.widgetCoords(event);
fb.circleDrag = Math.max(Math.abs(pos.x), Math.abs(pos.y)) * 2 > fb.square;
// Process
fb.mousemove(event);
return false;
};
/**
* Mousemove handler
*/
fb.mousemove = function (event) {
// Get coordinates relative to color picker center
var pos = fb.widgetCoords(event);
// Set new HSL parameters
if (fb.circleDrag) {
var hue = Math.atan2(pos.x, -pos.y) / 6.28;
if (hue < 0) hue += 1;
fb.setHSL([hue, fb.hsl[1], fb.hsl[2]]);
}
else {
var sat = Math.max(0, Math.min(1, -(pos.x / fb.square) + .5));
var lum = Math.max(0, Math.min(1, -(pos.y / fb.square) + .5));
fb.setHSL([fb.hsl[0], sat, lum]);
}
return false;
};
/**
* Mouseup handler
*/
fb.mouseup = function () {
// Uncapture mouse
$(document).unbind('mousemove', fb.mousemove);
$(document).unbind('mouseup', fb.mouseup);
document.dragging = false;
};
/**
* Update the markers and styles
*/
fb.updateDisplay = function () {
// Markers
var angle = fb.hsl[0] * 6.28;
$('.h-marker', e).css({
left: Math.round(Math.sin(angle) * fb.radius + fb.width / 2) + 'px',
top: Math.round(-Math.cos(angle) * fb.radius + fb.width / 2) + 'px'
});
$('.sl-marker', e).css({
left: Math.round(fb.square * (.5 - fb.hsl[1]) + fb.width / 2) + 'px',
top: Math.round(fb.square * (.5 - fb.hsl[2]) + fb.width / 2) + 'px'
});
// Saturation/Luminance gradient
$('.color', e).css('backgroundColor', fb.pack(fb.HSLToRGB([fb.hsl[0], 1, 0.5])));
// Linked elements or callback
if (typeof fb.callback == 'object') {
// Set background/foreground color
$(fb.callback).css({
backgroundColor: fb.color,
color: fb.hsl[2] > 0.5 ? '#000' : '#fff'
});
// Change linked value
$(fb.callback).each(function() {
if (this.value && this.value != fb.color) {
this.value = fb.color;
}
});
}
else if (typeof fb.callback == 'function') {
fb.callback.call(fb, fb.color);
}
};
/* Various color utility functions */
fb.pack = function (rgb) {
var r = Math.round(rgb[0] * 255);
var g = Math.round(rgb[1] * 255);
var b = Math.round(rgb[2] * 255);
return '#' + (r < 16 ? '0' : '') + r.toString(16) +
(g < 16 ? '0' : '') + g.toString(16) +
(b < 16 ? '0' : '') + b.toString(16);
};
fb.unpack = function (color) {
if (color.length == 7) {
return [parseInt('0x' + color.substring(1, 3)) / 255,
parseInt('0x' + color.substring(3, 5)) / 255,
parseInt('0x' + color.substring(5, 7)) / 255];
}
else if (color.length == 4) {
return [parseInt('0x' + color.substring(1, 2)) / 15,
parseInt('0x' + color.substring(2, 3)) / 15,
parseInt('0x' + color.substring(3, 4)) / 15];
}
};
fb.HSLToRGB = function (hsl) {
var m1, m2, r, g, b;
var h = hsl[0], s = hsl[1], l = hsl[2];
m2 = (l <= 0.5) ? l * (s + 1) : l + s - l*s;
m1 = l * 2 - m2;
return [this.hueToRGB(m1, m2, h+0.33333),
this.hueToRGB(m1, m2, h),
this.hueToRGB(m1, m2, h-0.33333)];
};
fb.hueToRGB = function (m1, m2, h) {
h = (h < 0) ? h + 1 : ((h > 1) ? h - 1 : h);
if (h * 6 < 1) return m1 + (m2 - m1) * h * 6;
if (h * 2 < 1) return m2;
if (h * 3 < 2) return m1 + (m2 - m1) * (0.66666 - h) * 6;
return m1;
};
fb.RGBToHSL = function (rgb) {
var min, max, delta, h, s, l;
var r = rgb[0], g = rgb[1], b = rgb[2];
min = Math.min(r, Math.min(g, b));
max = Math.max(r, Math.max(g, b));
delta = max - min;
l = (min + max) / 2;
s = 0;
if (l > 0 && l < 1) {
s = delta / (l < 0.5 ? (2 * l) : (2 - 2 * l));
}
h = 0;
if (delta > 0) {
if (max == r && max != g) h += (g - b) / delta;
if (max == g && max != b) h += (2 + (b - r) / delta);
if (max == b && max != r) h += (4 + (r - g) / delta);
h /= 6;
}
return [h, s, l];
};
// Install mousedown handler (the others are set on the document on-demand)
$('*', e).mousedown(fb.mousedown);
// Init color
fb.setColor('#000000');
// Set linked elements/callback
if (callback) {
fb.linkTo(callback);
}
};
})(jQuery); | JavaScript |
jQuery(document).ready( function($) {
postboxes.add_postbox_toggles('comment');
var stamp = $('#timestamp').html();
$('.edit-timestamp').click(function () {
if ($('#timestampdiv').is(":hidden")) {
$('#timestampdiv').slideDown("normal");
$('.edit-timestamp').hide();
}
return false;
});
$('.cancel-timestamp').click(function() {
$('#timestampdiv').slideUp("normal");
$('#mm').val($('#hidden_mm').val());
$('#jj').val($('#hidden_jj').val());
$('#aa').val($('#hidden_aa').val());
$('#hh').val($('#hidden_hh').val());
$('#mn').val($('#hidden_mn').val());
$('#timestamp').html(stamp);
$('.edit-timestamp').show();
return false;
});
$('.save-timestamp').click(function () { // crazyhorse - multiple ok cancels
var aa = $('#aa').val(), mm = $('#mm').val(), jj = $('#jj').val(), hh = $('#hh').val(), mn = $('#mn').val(),
newD = new Date( aa, mm - 1, jj, hh, mn );
if ( newD.getFullYear() != aa || (1 + newD.getMonth()) != mm || newD.getDate() != jj || newD.getMinutes() != mn ) {
$('.timestamp-wrap', '#timestampdiv').addClass('form-invalid');
return false;
} else {
$('.timestamp-wrap', '#timestampdiv').removeClass('form-invalid');
}
$('#timestampdiv').slideUp("normal");
$('.edit-timestamp').show();
$('#timestamp').html(
commentL10n.submittedOn + ' <b>' +
$( '#mm option[value="' + mm + '"]' ).text() + ' ' +
jj + ', ' +
aa + ' @ ' +
hh + ':' +
mn + '</b> '
);
return false;
});
});
| JavaScript |
function WPSetAsThumbnail(id, nonce){
var $link = jQuery('a#wp-post-thumbnail-' + id);
$link.text( setPostThumbnailL10n.saving );
jQuery.post(ajaxurl, {
action:"set-post-thumbnail", post_id: post_id, thumbnail_id: id, _ajax_nonce: nonce, cookie: encodeURIComponent(document.cookie)
}, function(str){
var win = window.dialogArguments || opener || parent || top;
$link.text( setPostThumbnailL10n.setThumbnail );
if ( str == '0' ) {
alert( setPostThumbnailL10n.error );
} else {
jQuery('a.wp-post-thumbnail').show();
$link.text( setPostThumbnailL10n.done );
$link.fadeOut( 2000 );
win.WPSetThumbnailID(id);
win.WPSetThumbnailHTML(str);
}
}
);
}
| JavaScript |
// Password strength meter
function passwordStrength(password1, username, password2) {
var shortPass = 1, badPass = 2, goodPass = 3, strongPass = 4, mismatch = 5, symbolSize = 0, natLog, score;
// password 1 != password 2
if ( (password1 != password2) && password2.length > 0)
return mismatch
//password < 4
if ( password1.length < 4 )
return shortPass
//password1 == username
if ( password1.toLowerCase() == username.toLowerCase() )
return badPass;
if ( password1.match(/[0-9]/) )
symbolSize +=10;
if ( password1.match(/[a-z]/) )
symbolSize +=26;
if ( password1.match(/[A-Z]/) )
symbolSize +=26;
if ( password1.match(/[^a-zA-Z0-9]/) )
symbolSize +=31;
natLog = Math.log( Math.pow(symbolSize, password1.length) );
score = natLog / Math.LN2;
if (score < 40 )
return badPass
if (score < 56 )
return goodPass
return strongPass;
}
| JavaScript |
var imageEdit;
(function($) {
imageEdit = {
iasapi : {},
hold : {},
postid : '',
intval : function(f) {
return f | 0;
},
setDisabled : function(el, s) {
if ( s ) {
el.removeClass('disabled');
$('input', el).removeAttr('disabled');
} else {
el.addClass('disabled');
$('input', el).prop('disabled', true);
}
},
init : function(postid, nonce) {
var t = this, old = $('#image-editor-' + t.postid),
x = t.intval( $('#imgedit-x-' + postid).val() ),
y = t.intval( $('#imgedit-y-' + postid).val() );
if ( t.postid != postid && old.length )
t.close(t.postid);
t.hold['w'] = t.hold['ow'] = x;
t.hold['h'] = t.hold['oh'] = y;
t.hold['xy_ratio'] = x / y;
t.hold['sizer'] = parseFloat( $('#imgedit-sizer-' + postid).val() );
t.postid = postid;
$('#imgedit-response-' + postid).empty();
$('input[type="text"]', '#imgedit-panel-' + postid).keypress(function(e) {
var k = e.keyCode;
if ( 36 < k && k < 41 )
$(this).blur()
if ( 13 == k ) {
e.preventDefault();
e.stopPropagation();
return false;
}
});
},
toggleEditor : function(postid, toggle) {
var wait = $('#imgedit-wait-' + postid);
if ( toggle )
wait.height( $('#imgedit-panel-' + postid).height() ).fadeIn('fast');
else
wait.fadeOut('fast');
},
toggleHelp : function(el) {
$(el).siblings('.imgedit-help').slideToggle('fast');
return false;
},
getTarget : function(postid) {
return $('input[name="imgedit-target-' + postid + '"]:checked', '#imgedit-save-target-' + postid).val() || 'full';
},
scaleChanged : function(postid, x) {
var w = $('#imgedit-scale-width-' + postid), h = $('#imgedit-scale-height-' + postid),
warn = $('#imgedit-scale-warn-' + postid), w1 = '', h1 = '';
if ( x ) {
h1 = (w.val() != '') ? Math.round( w.val() / this.hold['xy_ratio'] ) : '';
h.val( h1 );
} else {
w1 = (h.val() != '') ? Math.round( h.val() * this.hold['xy_ratio'] ) : '';
w.val( w1 );
}
if ( ( h1 && h1 > this.hold['oh'] ) || ( w1 && w1 > this.hold['ow'] ) )
warn.css('visibility', 'visible');
else
warn.css('visibility', 'hidden');
},
getSelRatio : function(postid) {
var x = this.hold['w'], y = this.hold['h'],
X = this.intval( $('#imgedit-crop-width-' + postid).val() ),
Y = this.intval( $('#imgedit-crop-height-' + postid).val() );
if ( X && Y )
return X + ':' + Y;
if ( x && y )
return x + ':' + y;
return '1:1';
},
filterHistory : function(postid, setSize) {
// apply undo state to history
var history = $('#imgedit-history-' + postid).val(), pop, n, o, i, op = [];
if ( history != '' ) {
history = JSON.parse(history);
pop = this.intval( $('#imgedit-undone-' + postid).val() );
if ( pop > 0 ) {
while ( pop > 0 ) {
history.pop();
pop--;
}
}
if ( setSize ) {
if ( !history.length ) {
this.hold['w'] = this.hold['ow'];
this.hold['h'] = this.hold['oh'];
return '';
}
// restore
o = history[history.length - 1];
o = o.c || o.r || o.f || false;
if ( o ) {
this.hold['w'] = o.fw;
this.hold['h'] = o.fh;
}
}
// filter the values
for ( n in history ) {
i = history[n];
if ( i.hasOwnProperty('c') ) {
op[n] = { 'c': { 'x': i.c.x, 'y': i.c.y, 'w': i.c.w, 'h': i.c.h } };
} else if ( i.hasOwnProperty('r') ) {
op[n] = { 'r': i.r.r };
} else if ( i.hasOwnProperty('f') ) {
op[n] = { 'f': i.f.f };
}
}
return JSON.stringify(op);
}
return '';
},
refreshEditor : function(postid, nonce, callback) {
var t = this, data, img;
t.toggleEditor(postid, 1);
data = {
'action': 'imgedit-preview',
'_ajax_nonce': nonce,
'postid': postid,
'history': t.filterHistory(postid, 1),
'rand': t.intval(Math.random() * 1000000)
};
img = $('<img id="image-preview-' + postid + '" />');
img.load( function() {
var max1, max2, parent = $('#imgedit-crop-' + postid), t = imageEdit;
parent.empty().append(img);
// w, h are the new full size dims
max1 = Math.max( t.hold.w, t.hold.h );
max2 = Math.max( $(img).width(), $(img).height() );
t.hold['sizer'] = max1 > max2 ? max2 / max1 : 1;
t.initCrop(postid, img, parent);
t.setCropSelection(postid, 0);
if ( (typeof callback != "unknown") && callback != null )
callback();
if ( $('#imgedit-history-' + postid).val() && $('#imgedit-undone-' + postid).val() == 0 )
$('input.imgedit-submit-btn', '#imgedit-panel-' + postid).removeAttr('disabled');
else
$('input.imgedit-submit-btn', '#imgedit-panel-' + postid).prop('disabled', true);
t.toggleEditor(postid, 0);
}).error(function(){
$('#imgedit-crop-' + postid).empty().append('<div class="error"><p>' + imageEditL10n.error + '</p></div>');
t.toggleEditor(postid, 0);
}).attr('src', ajaxurl + '?' + $.param(data));
},
action : function(postid, nonce, action) {
var t = this, data, w, h, fw, fh;
if ( t.notsaved(postid) )
return false;
data = {
'action': 'image-editor',
'_ajax_nonce': nonce,
'postid': postid
};
if ( 'scale' == action ) {
w = $('#imgedit-scale-width-' + postid),
h = $('#imgedit-scale-height-' + postid),
fw = t.intval(w.val()),
fh = t.intval(h.val());
if ( fw < 1 ) {
w.focus();
return false;
} else if ( fh < 1 ) {
h.focus();
return false;
}
if ( fw == t.hold.ow || fh == t.hold.oh )
return false;
data['do'] = 'scale';
data['fwidth'] = fw;
data['fheight'] = fh;
} else if ( 'restore' == action ) {
data['do'] = 'restore';
} else {
return false;
}
t.toggleEditor(postid, 1);
$.post(ajaxurl, data, function(r) {
$('#image-editor-' + postid).empty().append(r);
t.toggleEditor(postid, 0);
});
},
save : function(postid, nonce) {
var data, target = this.getTarget(postid), history = this.filterHistory(postid, 0);
if ( '' == history )
return false;
this.toggleEditor(postid, 1);
data = {
'action': 'image-editor',
'_ajax_nonce': nonce,
'postid': postid,
'history': history,
'target': target,
'context': $('#image-edit-context').length ? $('#image-edit-context').val() : null,
'do': 'save'
};
$.post(ajaxurl, data, function(r) {
var ret = JSON.parse(r);
if ( ret.error ) {
$('#imgedit-response-' + postid).html('<div class="error"><p>' + ret.error + '</p><div>');
imageEdit.close(postid);
return;
}
if ( ret.fw && ret.fh )
$('#media-dims-' + postid).html( ret.fw + ' × ' + ret.fh );
if ( ret.thumbnail )
$('.thumbnail', '#thumbnail-head-' + postid).attr('src', ''+ret.thumbnail);
if ( ret.msg )
$('#imgedit-response-' + postid).html('<div class="updated"><p>' + ret.msg + '</p></div>');
imageEdit.close(postid);
});
},
open : function(postid, nonce) {
var data, elem = $('#image-editor-' + postid), head = $('#media-head-' + postid),
btn = $('#imgedit-open-btn-' + postid), spin = btn.siblings('.spinner');
btn.prop('disabled', true);
spin.show();
data = {
'action': 'image-editor',
'_ajax_nonce': nonce,
'postid': postid,
'do': 'open'
};
elem.load(ajaxurl, data, function() {
elem.fadeIn('fast');
head.fadeOut('fast', function(){
btn.removeAttr('disabled');
spin.hide();
});
});
},
imgLoaded : function(postid) {
var img = $('#image-preview-' + postid), parent = $('#imgedit-crop-' + postid);
this.initCrop(postid, img, parent);
this.setCropSelection(postid, 0);
this.toggleEditor(postid, 0);
},
initCrop : function(postid, image, parent) {
var t = this, selW = $('#imgedit-sel-width-' + postid),
selH = $('#imgedit-sel-height-' + postid);
t.iasapi = $(image).imgAreaSelect({
parent: parent,
instance: true,
handles: true,
keys: true,
minWidth: 3,
minHeight: 3,
onInit: function(img, c) {
parent.children().mousedown(function(e){
var ratio = false, sel, defRatio;
if ( e.shiftKey ) {
sel = t.iasapi.getSelection();
defRatio = t.getSelRatio(postid);
ratio = ( sel && sel.width && sel.height ) ? sel.width + ':' + sel.height : defRatio;
}
t.iasapi.setOptions({
aspectRatio: ratio
});
});
},
onSelectStart: function(img, c) {
imageEdit.setDisabled($('#imgedit-crop-sel-' + postid), 1);
},
onSelectEnd: function(img, c) {
imageEdit.setCropSelection(postid, c);
},
onSelectChange: function(img, c) {
var sizer = imageEdit.hold.sizer;
selW.val( imageEdit.round(c.width / sizer) );
selH.val( imageEdit.round(c.height / sizer) );
}
});
},
setCropSelection : function(postid, c) {
var sel, min = $('#imgedit-minthumb-' + postid).val() || '128:128',
sizer = this.hold['sizer'];
min = min.split(':');
c = c || 0;
if ( !c || ( c.width < 3 && c.height < 3 ) ) {
this.setDisabled($('.imgedit-crop', '#imgedit-panel-' + postid), 0);
this.setDisabled($('#imgedit-crop-sel-' + postid), 0);
$('#imgedit-sel-width-' + postid).val('');
$('#imgedit-sel-height-' + postid).val('');
$('#imgedit-selection-' + postid).val('');
return false;
}
if ( c.width < (min[0] * sizer) && c.height < (min[1] * sizer) ) {
this.setDisabled($('.imgedit-crop', '#imgedit-panel-' + postid), 0);
$('#imgedit-selection-' + postid).val('');
return false;
}
sel = { 'x': c.x1, 'y': c.y1, 'w': c.width, 'h': c.height };
this.setDisabled($('.imgedit-crop', '#imgedit-panel-' + postid), 1);
$('#imgedit-selection-' + postid).val( JSON.stringify(sel) );
},
close : function(postid, warn) {
warn = warn || false;
if ( warn && this.notsaved(postid) )
return false;
this.iasapi = {};
this.hold = {};
$('#image-editor-' + postid).fadeOut('fast', function() {
$('#media-head-' + postid).fadeIn('fast');
$(this).empty();
});
},
notsaved : function(postid) {
var h = $('#imgedit-history-' + postid).val(),
history = (h != '') ? JSON.parse(h) : new Array(),
pop = this.intval( $('#imgedit-undone-' + postid).val() );
if ( pop < history.length ) {
if ( confirm( $('#imgedit-leaving-' + postid).html() ) )
return false;
return true;
}
return false;
},
addStep : function(op, postid, nonce) {
var t = this, elem = $('#imgedit-history-' + postid),
history = (elem.val() != '') ? JSON.parse(elem.val()) : new Array(),
undone = $('#imgedit-undone-' + postid),
pop = t.intval(undone.val());
while ( pop > 0 ) {
history.pop();
pop--;
}
undone.val(0); // reset
history.push(op);
elem.val( JSON.stringify(history) );
t.refreshEditor(postid, nonce, function() {
t.setDisabled($('#image-undo-' + postid), true);
t.setDisabled($('#image-redo-' + postid), false);
});
},
rotate : function(angle, postid, nonce, t) {
if ( $(t).hasClass('disabled') )
return false;
this.addStep({ 'r': { 'r': angle, 'fw': this.hold['h'], 'fh': this.hold['w'] }}, postid, nonce);
},
flip : function (axis, postid, nonce, t) {
if ( $(t).hasClass('disabled') )
return false;
this.addStep({ 'f': { 'f': axis, 'fw': this.hold['w'], 'fh': this.hold['h'] }}, postid, nonce);
},
crop : function (postid, nonce, t) {
var sel = $('#imgedit-selection-' + postid).val(),
w = this.intval( $('#imgedit-sel-width-' + postid).val() ),
h = this.intval( $('#imgedit-sel-height-' + postid).val() );
if ( $(t).hasClass('disabled') || sel == '' )
return false;
sel = JSON.parse(sel);
if ( sel.w > 0 && sel.h > 0 && w > 0 && h > 0 ) {
sel['fw'] = w;
sel['fh'] = h;
this.addStep({ 'c': sel }, postid, nonce);
}
},
undo : function (postid, nonce) {
var t = this, button = $('#image-undo-' + postid), elem = $('#imgedit-undone-' + postid),
pop = t.intval( elem.val() ) + 1;
if ( button.hasClass('disabled') )
return;
elem.val(pop);
t.refreshEditor(postid, nonce, function() {
var elem = $('#imgedit-history-' + postid),
history = (elem.val() != '') ? JSON.parse(elem.val()) : new Array();
t.setDisabled($('#image-redo-' + postid), true);
t.setDisabled(button, pop < history.length);
});
},
redo : function(postid, nonce) {
var t = this, button = $('#image-redo-' + postid), elem = $('#imgedit-undone-' + postid),
pop = t.intval( elem.val() ) - 1;
if ( button.hasClass('disabled') )
return;
elem.val(pop);
t.refreshEditor(postid, nonce, function() {
t.setDisabled($('#image-undo-' + postid), true);
t.setDisabled(button, pop > 0);
});
},
setNumSelection : function(postid) {
var sel, elX = $('#imgedit-sel-width-' + postid), elY = $('#imgedit-sel-height-' + postid),
x = this.intval( elX.val() ), y = this.intval( elY.val() ),
img = $('#image-preview-' + postid), imgh = img.height(), imgw = img.width(),
sizer = this.hold['sizer'], x1, y1, x2, y2, ias = this.iasapi;
if ( x < 1 ) {
elX.val('');
return false;
}
if ( y < 1 ) {
elY.val('');
return false;
}
if ( x && y && ( sel = ias.getSelection() ) ) {
x2 = sel.x1 + Math.round( x * sizer );
y2 = sel.y1 + Math.round( y * sizer );
x1 = sel.x1;
y1 = sel.y1;
if ( x2 > imgw ) {
x1 = 0;
x2 = imgw;
elX.val( Math.round( x2 / sizer ) );
}
if ( y2 > imgh ) {
y1 = 0;
y2 = imgh;
elY.val( Math.round( y2 / sizer ) );
}
ias.setSelection( x1, y1, x2, y2 );
ias.update();
this.setCropSelection(postid, ias.getSelection());
}
},
round : function(num) {
var s;
num = Math.round(num);
if ( this.hold.sizer > 0.6 )
return num;
s = num.toString().slice(-1);
if ( '1' == s )
return num - 1;
else if ( '9' == s )
return num + 1;
return num;
},
setRatioSelection : function(postid, n, el) {
var sel, r, x = this.intval( $('#imgedit-crop-width-' + postid).val() ),
y = this.intval( $('#imgedit-crop-height-' + postid).val() ),
h = $('#image-preview-' + postid).height();
if ( !this.intval( $(el).val() ) ) {
$(el).val('');
return;
}
if ( x && y ) {
this.iasapi.setOptions({
aspectRatio: x + ':' + y
});
if ( sel = this.iasapi.getSelection(true) ) {
r = Math.ceil( sel.y1 + ((sel.x2 - sel.x1) / (x / y)) );
if ( r > h ) {
r = h;
if ( n )
$('#imgedit-crop-height-' + postid).val('');
else
$('#imgedit-crop-width-' + postid).val('');
}
this.iasapi.setSelection( sel.x1, sel.y1, sel.x2, r );
this.iasapi.update();
}
}
}
}
})(jQuery);
| JavaScript |
jQuery(document).ready( function($) {
var before, addBefore, addAfter, delBefore;
before = function() {
var nonce = $('#newmeta [name="_ajax_nonce"]').val(), postId = $('#post_ID').val();
if ( !nonce || !postId ) { return false; }
return [nonce,postId];
}
addBefore = function( s ) {
var b = before();
if ( !b ) { return false; }
s.data = s.data.replace(/_ajax_nonce=[a-f0-9]+/, '_ajax_nonce=' + b[0]) + '&post_id=' + b[1];
return s;
};
addAfter = function( r, s ) {
var postId = $('postid', r).text(), h;
if ( !postId ) { return; }
$('#post_ID').attr( 'name', 'post_ID' ).val( postId );
h = $('#hiddenaction');
if ( 'post' == h.val() ) { h.val( 'postajaxpost' ); }
};
delBefore = function( s ) {
var b = before(); if ( !b ) return false;
s.data._ajax_nonce = b[0]; s.data.post_id = b[1];
return s;
}
$('#the-list')
.wpList( { addBefore: addBefore, addAfter: addAfter, delBefore: delBefore } )
.find('.updatemeta, .deletemeta').attr( 'type', 'button' );
} );
| JavaScript |
(function($) {
var id = 'undefined' !== typeof current_site_id ? '&site_id=' + current_site_id : '';
$(document).ready( function() {
$( '.wp-suggest-user' ).autocomplete({
source: ajaxurl + '?action=autocomplete-user&autocomplete_type=add' + id,
delay: 500,
minLength: 2,
position: ( 'undefined' !== typeof isRtl && isRtl ) ? { my: 'right top', at: 'right bottom', offset: '0, -1' } : { offset: '0, -1' },
open: function() { $(this).addClass('open'); },
close: function() { $(this).removeClass('open'); }
});
});
})(jQuery); | JavaScript |
var wpWidgets;
(function($) {
wpWidgets = {
init : function() {
var rem, sidebars = $('div.widgets-sortables'), isRTL = !! ( 'undefined' != typeof isRtl && isRtl ),
margin = ( isRtl ? 'marginRight' : 'marginLeft' ), the_id;
$('#widgets-right').children('.widgets-holder-wrap').children('.sidebar-name').click(function(){
var c = $(this).siblings('.widgets-sortables'), p = $(this).parent();
if ( !p.hasClass('closed') ) {
c.sortable('disable');
p.addClass('closed');
} else {
p.removeClass('closed');
c.sortable('enable').sortable('refresh');
}
});
$('#widgets-left').children('.widgets-holder-wrap').children('.sidebar-name').click(function() {
$(this).parent().toggleClass('closed');
});
sidebars.each(function(){
if ( $(this).parent().hasClass('inactive') )
return true;
var h = 50, H = $(this).children('.widget').length;
h = h + parseInt(H * 48, 10);
$(this).css( 'minHeight', h + 'px' );
});
$(document.body).bind('click.widgets-toggle', function(e){
var target = $(e.target), css = {}, widget, inside, w;
if ( target.parents('.widget-top').length && ! target.parents('#available-widgets').length ) {
widget = target.closest('div.widget');
inside = widget.children('.widget-inside');
w = parseInt( widget.find('input.widget-width').val(), 10 );
if ( inside.is(':hidden') ) {
if ( w > 250 && inside.closest('div.widgets-sortables').length ) {
css['width'] = w + 30 + 'px';
if ( inside.closest('div.widget-liquid-right').length )
css[margin] = 235 - w + 'px';
widget.css(css);
}
wpWidgets.fixLabels(widget);
inside.slideDown('fast');
} else {
inside.slideUp('fast', function() {
widget.css({'width':'', margin:''});
});
}
e.preventDefault();
} else if ( target.hasClass('widget-control-save') ) {
wpWidgets.save( target.closest('div.widget'), 0, 1, 0 );
e.preventDefault();
} else if ( target.hasClass('widget-control-remove') ) {
wpWidgets.save( target.closest('div.widget'), 1, 1, 0 );
e.preventDefault();
} else if ( target.hasClass('widget-control-close') ) {
wpWidgets.close( target.closest('div.widget') );
e.preventDefault();
}
});
sidebars.children('.widget').each(function() {
wpWidgets.appendTitle(this);
if ( $('p.widget-error', this).length )
$('a.widget-action', this).click();
});
$('#widget-list').children('.widget').draggable({
connectToSortable: 'div.widgets-sortables',
handle: '> .widget-top > .widget-title',
distance: 2,
helper: 'clone',
zIndex: 100,
containment: 'document',
start: function(e,ui) {
ui.helper.find('div.widget-description').hide();
the_id = this.id;
},
stop: function(e,ui) {
if ( rem )
$(rem).hide();
rem = '';
}
});
sidebars.sortable({
placeholder: 'widget-placeholder',
items: '> .widget',
handle: '> .widget-top > .widget-title',
cursor: 'move',
distance: 2,
containment: 'document',
start: function(e,ui) {
ui.item.children('.widget-inside').hide();
ui.item.css({margin:'', 'width':''});
},
stop: function(e,ui) {
if ( ui.item.hasClass('ui-draggable') && ui.item.data('draggable') )
ui.item.draggable('destroy');
if ( ui.item.hasClass('deleting') ) {
wpWidgets.save( ui.item, 1, 0, 1 ); // delete widget
ui.item.remove();
return;
}
var add = ui.item.find('input.add_new').val(),
n = ui.item.find('input.multi_number').val(),
id = the_id,
sb = $(this).attr('id');
ui.item.css({margin:'', 'width':''});
the_id = '';
if ( add ) {
if ( 'multi' == add ) {
ui.item.html( ui.item.html().replace(/<[^<>]+>/g, function(m){ return m.replace(/__i__|%i%/g, n); }) );
ui.item.attr( 'id', id.replace('__i__', n) );
n++;
$('div#' + id).find('input.multi_number').val(n);
} else if ( 'single' == add ) {
ui.item.attr( 'id', 'new-' + id );
rem = 'div#' + id;
}
wpWidgets.save( ui.item, 0, 0, 1 );
ui.item.find('input.add_new').val('');
ui.item.find('a.widget-action').click();
return;
}
wpWidgets.saveOrder(sb);
},
receive: function(e, ui) {
var sender = $(ui.sender);
if ( !$(this).is(':visible') || this.id.indexOf('orphaned_widgets') != -1 )
sender.sortable('cancel');
if ( sender.attr('id').indexOf('orphaned_widgets') != -1 && !sender.children('.widget').length ) {
sender.parents('.orphan-sidebar').slideUp(400, function(){ $(this).remove(); });
}
}
}).sortable('option', 'connectWith', 'div.widgets-sortables').parent().filter('.closed').children('.widgets-sortables').sortable('disable');
$('#available-widgets').droppable({
tolerance: 'pointer',
accept: function(o){
return $(o).parent().attr('id') != 'widget-list';
},
drop: function(e,ui) {
ui.draggable.addClass('deleting');
$('#removing-widget').hide().children('span').html('');
},
over: function(e,ui) {
ui.draggable.addClass('deleting');
$('div.widget-placeholder').hide();
if ( ui.draggable.hasClass('ui-sortable-helper') )
$('#removing-widget').show().children('span')
.html( ui.draggable.find('div.widget-title').children('h4').html() );
},
out: function(e,ui) {
ui.draggable.removeClass('deleting');
$('div.widget-placeholder').show();
$('#removing-widget').hide().children('span').html('');
}
});
},
saveOrder : function(sb) {
if ( sb )
$('#' + sb).closest('div.widgets-holder-wrap').find('.spinner').css('display', 'inline-block');
var a = {
action: 'widgets-order',
savewidgets: $('#_wpnonce_widgets').val(),
sidebars: []
};
$('div.widgets-sortables').each( function() {
if ( $(this).sortable )
a['sidebars[' + $(this).attr('id') + ']'] = $(this).sortable('toArray').join(',');
});
$.post( ajaxurl, a, function() {
$('.spinner').hide();
});
this.resize();
},
save : function(widget, del, animate, order) {
var sb = widget.closest('div.widgets-sortables').attr('id'), data = widget.find('form').serialize(), a;
widget = $(widget);
$('.spinner', widget).show();
a = {
action: 'save-widget',
savewidgets: $('#_wpnonce_widgets').val(),
sidebar: sb
};
if ( del )
a['delete_widget'] = 1;
data += '&' + $.param(a);
$.post( ajaxurl, data, function(r){
var id;
if ( del ) {
if ( !$('input.widget_number', widget).val() ) {
id = $('input.widget-id', widget).val();
$('#available-widgets').find('input.widget-id').each(function(){
if ( $(this).val() == id )
$(this).closest('div.widget').show();
});
}
if ( animate ) {
order = 0;
widget.slideUp('fast', function(){
$(this).remove();
wpWidgets.saveOrder();
});
} else {
widget.remove();
wpWidgets.resize();
}
} else {
$('.spinner').hide();
if ( r && r.length > 2 ) {
$('div.widget-content', widget).html(r);
wpWidgets.appendTitle(widget);
wpWidgets.fixLabels(widget);
}
}
if ( order )
wpWidgets.saveOrder();
});
},
appendTitle : function(widget) {
var title = $('input[id*="-title"]', widget).val() || '';
if ( title )
title = ': ' + title.replace(/<[^<>]+>/g, '').replace(/</g, '<').replace(/>/g, '>');
$(widget).children('.widget-top').children('.widget-title').children()
.children('.in-widget-title').html(title);
},
resize : function() {
$('div.widgets-sortables').each(function(){
if ( $(this).parent().hasClass('inactive') )
return true;
var h = 50, H = $(this).children('.widget').length;
h = h + parseInt(H * 48, 10);
$(this).css( 'minHeight', h + 'px' );
});
},
fixLabels : function(widget) {
widget.children('.widget-inside').find('label').each(function(){
var f = $(this).attr('for');
if ( f && f == $('input', this).attr('id') )
$(this).removeAttr('for');
});
},
close : function(widget) {
widget.children('.widget-inside').slideUp('fast', function(){
widget.css({'width':'', margin:''});
});
}
};
$(document).ready(function($){ wpWidgets.init(); });
})(jQuery);
| JavaScript |
(function( exports, $ ){
var api = wp.customize;
/*
* @param options
* - previewer - The Previewer instance to sync with.
* - transport - The transport to use for previewing. Supports 'refresh' and 'postMessage'.
*/
api.Setting = api.Value.extend({
initialize: function( id, value, options ) {
var element;
api.Value.prototype.initialize.call( this, value, options );
this.id = id;
this.transport = this.transport || 'refresh';
this.bind( this.preview );
},
preview: function() {
switch ( this.transport ) {
case 'refresh':
return this.previewer.refresh();
case 'postMessage':
return this.previewer.send( 'setting', [ this.id, this() ] );
}
}
});
api.Control = api.Class.extend({
initialize: function( id, options ) {
var control = this,
nodes, radios, settings;
this.params = {};
$.extend( this, options || {} );
this.id = id;
this.selector = '#customize-control-' + id.replace( ']', '' ).replace( '[', '-' );
this.container = $( this.selector );
settings = $.map( this.params.settings, function( value ) {
return value;
});
api.apply( api, settings.concat( function() {
var key;
control.settings = {};
for ( key in control.params.settings ) {
control.settings[ key ] = api( control.params.settings[ key ] );
}
control.setting = control.settings['default'] || null;
control.ready();
}) );
control.elements = [];
nodes = this.container.find('[data-customize-setting-link]');
radios = {};
nodes.each( function() {
var node = $(this),
name;
if ( node.is(':radio') ) {
name = node.prop('name');
if ( radios[ name ] )
return;
radios[ name ] = true;
node = nodes.filter( '[name="' + name + '"]' );
}
api( node.data('customizeSettingLink'), function( setting ) {
var element = new api.Element( node );
control.elements.push( element );
element.sync( setting );
element.set( setting() );
});
});
},
ready: function() {},
dropdownInit: function() {
var control = this,
statuses = this.container.find('.dropdown-status'),
params = this.params,
update = function( to ) {
if ( typeof to === 'string' && params.statuses && params.statuses[ to ] )
statuses.html( params.statuses[ to ] ).show();
else
statuses.hide();
};
var toggleFreeze = false;
// Support the .dropdown class to open/close complex elements
this.container.on( 'click keydown', '.dropdown', function( event ) {
if ( event.type === 'keydown' && 13 !== event.which ) // enter
return;
event.preventDefault();
if (!toggleFreeze)
control.container.toggleClass('open');
if ( control.container.hasClass('open') )
control.container.parent().parent().find('li.library-selected').focus();
// Don't want to fire focus and click at same time
toggleFreeze = true;
setTimeout(function () {
toggleFreeze = false;
}, 400);
});
this.setting.bind( update );
update( this.setting() );
}
});
api.ColorControl = api.Control.extend({
ready: function() {
var control = this,
picker = this.container.find('.color-picker-hex');
picker.val( control.setting() ).wpColorPicker({
change: function( event, options ) {
control.setting.set( picker.wpColorPicker('color') );
},
clear: function() {
control.setting.set( false );
}
});
}
});
api.UploadControl = api.Control.extend({
ready: function() {
var control = this;
this.params.removed = this.params.removed || '';
this.success = $.proxy( this.success, this );
this.uploader = $.extend({
container: this.container,
browser: this.container.find('.upload'),
dropzone: this.container.find('.upload-dropzone'),
success: this.success,
plupload: {},
params: {}
}, this.uploader || {} );
if ( control.params.extensions ) {
control.uploader.plupload.filters = [{
title: api.l10n.allowedFiles,
extensions: control.params.extensions
}];
}
if ( control.params.context )
control.uploader.params['post_data[context]'] = this.params.context;
if ( api.settings.theme.stylesheet )
control.uploader.params['post_data[theme]'] = api.settings.theme.stylesheet;
this.uploader = new wp.Uploader( this.uploader );
this.remover = this.container.find('.remove');
this.remover.on( 'click keydown', function( event ) {
if ( event.type === 'keydown' && 13 !== event.which ) // enter
return;
control.setting.set( control.params.removed );
event.preventDefault();
});
this.removerVisibility = $.proxy( this.removerVisibility, this );
this.setting.bind( this.removerVisibility );
this.removerVisibility( this.setting.get() );
},
success: function( attachment ) {
this.setting.set( attachment.get('url') );
},
removerVisibility: function( to ) {
this.remover.toggle( to != this.params.removed );
}
});
api.ImageControl = api.UploadControl.extend({
ready: function() {
var control = this,
panels;
this.uploader = {
init: function( up ) {
var fallback, button;
if ( this.supports.dragdrop )
return;
// Maintain references while wrapping the fallback button.
fallback = control.container.find( '.upload-fallback' );
button = fallback.children().detach();
this.browser.detach().empty().append( button );
fallback.append( this.browser ).show();
}
};
api.UploadControl.prototype.ready.call( this );
this.thumbnail = this.container.find('.preview-thumbnail img');
this.thumbnailSrc = $.proxy( this.thumbnailSrc, this );
this.setting.bind( this.thumbnailSrc );
this.library = this.container.find('.library');
// Generate tab objects
this.tabs = {};
panels = this.library.find('.library-content');
this.library.children('ul').children('li').each( function() {
var link = $(this),
id = link.data('customizeTab'),
panel = panels.filter('[data-customize-tab="' + id + '"]');
control.tabs[ id ] = {
both: link.add( panel ),
link: link,
panel: panel
};
});
// Bind tab switch events
this.library.children('ul').on( 'click keydown', 'li', function( event ) {
if ( event.type === 'keydown' && 13 !== event.which ) // enter
return;
var id = $(this).data('customizeTab'),
tab = control.tabs[ id ];
event.preventDefault();
if ( tab.link.hasClass('library-selected') )
return;
control.selected.both.removeClass('library-selected');
control.selected = tab;
control.selected.both.addClass('library-selected');
});
// Bind events to switch image urls.
this.library.on( 'click keydown', 'a', function( event ) {
if ( event.type === 'keydown' && 13 !== event.which ) // enter
return;
var value = $(this).data('customizeImageValue');
if ( value ) {
control.setting.set( value );
event.preventDefault();
}
});
if ( this.tabs.uploaded ) {
this.tabs.uploaded.target = this.library.find('.uploaded-target');
if ( ! this.tabs.uploaded.panel.find('.thumbnail').length )
this.tabs.uploaded.both.addClass('hidden');
}
// Select a tab
panels.each( function() {
var tab = control.tabs[ $(this).data('customizeTab') ];
// Select the first visible tab.
if ( ! tab.link.hasClass('hidden') ) {
control.selected = tab;
tab.both.addClass('library-selected');
return false;
}
});
this.dropdownInit();
},
success: function( attachment ) {
api.UploadControl.prototype.success.call( this, attachment );
// Add the uploaded image to the uploaded tab.
if ( this.tabs.uploaded && this.tabs.uploaded.target.length ) {
this.tabs.uploaded.both.removeClass('hidden');
// @todo: Do NOT store this on the attachment model. That is bad.
attachment.element = $( '<a href="#" class="thumbnail"></a>' )
.data( 'customizeImageValue', attachment.get('url') )
.append( '<img src="' + attachment.get('url')+ '" />' )
.appendTo( this.tabs.uploaded.target );
}
},
thumbnailSrc: function( to ) {
if ( /^(https?:)?\/\//.test( to ) )
this.thumbnail.prop( 'src', to ).show();
else
this.thumbnail.hide();
}
});
// Change objects contained within the main customize object to Settings.
api.defaultConstructor = api.Setting;
// Create the collection of Control objects.
api.control = new api.Values({ defaultConstructor: api.Control });
api.PreviewFrame = api.Messenger.extend({
sensitivity: 2000,
initialize: function( params, options ) {
var deferred = $.Deferred(),
self = this;
// This is the promise object.
deferred.promise( this );
this.container = params.container;
this.signature = params.signature;
$.extend( params, { channel: api.PreviewFrame.uuid() });
api.Messenger.prototype.initialize.call( this, params, options );
this.add( 'previewUrl', params.previewUrl );
this.query = $.extend( params.query || {}, { customize_messenger_channel: this.channel() });
this.run( deferred );
},
run: function( deferred ) {
var self = this,
loaded = false,
ready = false;
if ( this._ready )
this.unbind( 'ready', this._ready );
this._ready = function() {
ready = true;
if ( loaded )
deferred.resolveWith( self );
};
this.bind( 'ready', this._ready );
this.request = $.ajax( this.previewUrl(), {
type: 'POST',
data: this.query,
xhrFields: {
withCredentials: true
}
} );
this.request.fail( function() {
deferred.rejectWith( self, [ 'request failure' ] );
});
this.request.done( function( response ) {
var location = self.request.getResponseHeader('Location'),
signature = self.signature,
index;
// Check if the location response header differs from the current URL.
// If so, the request was redirected; try loading the requested page.
if ( location && location != self.previewUrl() ) {
deferred.rejectWith( self, [ 'redirect', location ] );
return;
}
// Check if the user is not logged in.
if ( '0' === response ) {
self.login( deferred );
return;
}
// Check for cheaters.
if ( '-1' === response ) {
deferred.rejectWith( self, [ 'cheatin' ] );
return;
}
// Check for a signature in the request.
index = response.lastIndexOf( signature );
if ( -1 === index || index < response.lastIndexOf('</html>') ) {
deferred.rejectWith( self, [ 'unsigned' ] );
return;
}
// Strip the signature from the request.
response = response.slice( 0, index ) + response.slice( index + signature.length );
// Create the iframe and inject the html content.
self.iframe = $('<iframe />').appendTo( self.container );
// Bind load event after the iframe has been added to the page;
// otherwise it will fire when injected into the DOM.
self.iframe.one( 'load', function() {
loaded = true;
if ( ready ) {
deferred.resolveWith( self );
} else {
setTimeout( function() {
deferred.rejectWith( self, [ 'ready timeout' ] );
}, self.sensitivity );
}
});
self.targetWindow( self.iframe[0].contentWindow );
self.targetWindow().document.open();
self.targetWindow().document.write( response );
self.targetWindow().document.close();
});
},
login: function( deferred ) {
var self = this,
reject;
reject = function() {
deferred.rejectWith( self, [ 'logged out' ] );
};
if ( this.triedLogin )
return reject();
// Check if we have an admin cookie.
$.get( api.settings.url.ajax, {
action: 'logged-in'
}).fail( reject ).done( function( response ) {
var iframe;
if ( '1' !== response )
reject();
iframe = $('<iframe src="' + self.previewUrl() + '" />').hide();
iframe.appendTo( self.container );
iframe.load( function() {
self.triedLogin = true;
iframe.remove();
self.run( deferred );
});
});
},
destroy: function() {
api.Messenger.prototype.destroy.call( this );
this.request.abort();
if ( this.iframe )
this.iframe.remove();
delete this.request;
delete this.iframe;
delete this.targetWindow;
}
});
(function(){
var uuid = 0;
api.PreviewFrame.uuid = function() {
return 'preview-' + uuid++;
};
}());
api.Previewer = api.Messenger.extend({
refreshBuffer: 250,
/**
* Requires params:
* - container - a selector or jQuery element
* - previewUrl - the URL of preview frame
*/
initialize: function( params, options ) {
var self = this,
rscheme = /^https?/,
url;
$.extend( this, options || {} );
/*
* Wrap this.refresh to prevent it from hammering the servers:
*
* If refresh is called once and no other refresh requests are
* loading, trigger the request immediately.
*
* If refresh is called while another refresh request is loading,
* debounce the refresh requests:
* 1. Stop the loading request (as it is instantly outdated).
* 2. Trigger the new request once refresh hasn't been called for
* self.refreshBuffer milliseconds.
*/
this.refresh = (function( self ) {
var refresh = self.refresh,
callback = function() {
timeout = null;
refresh.call( self );
},
timeout;
return function() {
if ( typeof timeout !== 'number' ) {
if ( self.loading ) {
self.abort();
} else {
return callback();
}
}
clearTimeout( timeout );
timeout = setTimeout( callback, self.refreshBuffer );
};
})( this );
this.container = api.ensure( params.container );
this.allowedUrls = params.allowedUrls;
this.signature = params.signature;
params.url = window.location.href;
api.Messenger.prototype.initialize.call( this, params );
this.add( 'scheme', this.origin() ).link( this.origin ).setter( function( to ) {
var match = to.match( rscheme );
return match ? match[0] : '';
});
// Limit the URL to internal, front-end links.
//
// If the frontend and the admin are served from the same domain, load the
// preview over ssl if the customizer is being loaded over ssl. This avoids
// insecure content warnings. This is not attempted if the admin and frontend
// are on different domains to avoid the case where the frontend doesn't have
// ssl certs.
this.add( 'previewUrl', params.previewUrl ).setter( function( to ) {
var result;
// Check for URLs that include "/wp-admin/" or end in "/wp-admin".
// Strip hashes and query strings before testing.
if ( /\/wp-admin(\/|$)/.test( to.replace(/[#?].*$/, '') ) )
return null;
// Attempt to match the URL to the control frame's scheme
// and check if it's allowed. If not, try the original URL.
$.each([ to.replace( rscheme, self.scheme() ), to ], function( i, url ) {
$.each( self.allowedUrls, function( i, allowed ) {
if ( 0 === url.indexOf( allowed ) ) {
result = url;
return false;
}
});
if ( result )
return false;
});
// If we found a matching result, return it. If not, bail.
return result ? result : null;
});
// Refresh the preview when the URL is changed (but not yet).
this.previewUrl.bind( this.refresh );
this.scroll = 0;
this.bind( 'scroll', function( distance ) {
this.scroll = distance;
});
// Update the URL when the iframe sends a URL message.
this.bind( 'url', this.previewUrl );
},
query: function() {},
abort: function() {
if ( this.loading ) {
this.loading.destroy();
delete this.loading;
}
},
refresh: function() {
var self = this;
this.abort();
this.loading = new api.PreviewFrame({
url: this.url(),
previewUrl: this.previewUrl(),
query: this.query() || {},
container: this.container,
signature: this.signature
});
this.loading.done( function() {
// 'this' is the loading frame
this.bind( 'synced', function() {
if ( self.preview )
self.preview.destroy();
self.preview = this;
delete self.loading;
self.targetWindow( this.targetWindow() );
self.channel( this.channel() );
self.send( 'active' );
});
this.send( 'sync', {
scroll: self.scroll,
settings: api.get()
});
});
this.loading.fail( function( reason, location ) {
if ( 'redirect' === reason && location )
self.previewUrl( location );
if ( 'logged out' === reason ) {
if ( self.preview ) {
self.preview.destroy();
delete self.preview;
}
self.login().done( self.refresh );
}
if ( 'cheatin' === reason )
self.cheatin();
});
},
login: function() {
var previewer = this,
deferred, messenger, iframe;
if ( this._login )
return this._login;
deferred = $.Deferred();
this._login = deferred.promise();
messenger = new api.Messenger({
channel: 'login',
url: api.settings.url.login
});
iframe = $('<iframe src="' + api.settings.url.login + '" />').appendTo( this.container );
messenger.targetWindow( iframe[0].contentWindow );
messenger.bind( 'login', function() {
iframe.remove();
messenger.destroy();
delete previewer._login;
deferred.resolve();
});
return this._login;
},
cheatin: function() {
$( document.body ).empty().addClass('cheatin').append( '<p>' + api.l10n.cheatin + '</p>' );
}
});
/* =====================================================================
* Ready.
* ===================================================================== */
api.controlConstructor = {
color: api.ColorControl,
upload: api.UploadControl,
image: api.ImageControl
};
$( function() {
api.settings = window._wpCustomizeSettings;
api.l10n = window._wpCustomizeControlsL10n;
// Check if we can run the customizer.
if ( ! api.settings )
return;
// Redirect to the fallback preview if any incompatibilities are found.
if ( ! $.support.postMessage || ( ! $.support.cors && api.settings.isCrossDomain ) )
return window.location = api.settings.url.fallback;
var body = $( document.body ),
overlay = body.children('.wp-full-overlay'),
query, previewer, parent;
// Prevent the form from saving when enter is pressed.
$('#customize-controls').on( 'keydown', function( e ) {
if ( $( e.target ).is('textarea') )
return;
if ( 13 === e.which ) // Enter
e.preventDefault();
});
// Initialize Previewer
previewer = new api.Previewer({
container: '#customize-preview',
form: '#customize-controls',
previewUrl: api.settings.url.preview,
allowedUrls: api.settings.url.allowed,
signature: 'WP_CUSTOMIZER_SIGNATURE'
}, {
nonce: api.settings.nonce,
query: function() {
return {
wp_customize: 'on',
theme: api.settings.theme.stylesheet,
customized: JSON.stringify( api.get() ),
nonce: this.nonce.preview
};
},
save: function() {
var self = this,
query = $.extend( this.query(), {
action: 'customize_save',
nonce: this.nonce.save
}),
request = $.post( api.settings.url.ajax, query );
api.trigger( 'save', request );
body.addClass('saving');
request.always( function() {
body.removeClass('saving');
});
request.done( function( response ) {
// Check if the user is logged out.
if ( '0' === response ) {
self.preview.iframe.hide();
self.login().done( function() {
self.save();
self.preview.iframe.show();
});
return;
}
// Check for cheaters.
if ( '-1' === response ) {
self.cheatin();
return;
}
api.trigger( 'saved' );
});
}
});
// Refresh the nonces if the preview sends updated nonces over.
previewer.bind( 'nonce', function( nonce ) {
$.extend( this.nonce, nonce );
});
$.each( api.settings.settings, function( id, data ) {
api.create( id, id, data.value, {
transport: data.transport,
previewer: previewer
} );
});
$.each( api.settings.controls, function( id, data ) {
var constructor = api.controlConstructor[ data.type ] || api.Control,
control;
control = api.control.add( id, new constructor( id, {
params: data,
previewer: previewer
} ) );
});
// Check if preview url is valid and load the preview frame.
if ( previewer.previewUrl() )
previewer.refresh();
else
previewer.previewUrl( api.settings.url.home );
// Save and activated states
(function() {
var state = new api.Values(),
saved = state.create('saved'),
activated = state.create('activated');
state.bind( 'change', function() {
var save = $('#save'),
back = $('.back');
if ( ! activated() ) {
save.val( api.l10n.activate ).prop( 'disabled', false );
back.text( api.l10n.cancel );
} else if ( saved() ) {
save.val( api.l10n.saved ).prop( 'disabled', true );
back.text( api.l10n.close );
} else {
save.val( api.l10n.save ).prop( 'disabled', false );
back.text( api.l10n.cancel );
}
});
// Set default states.
saved( true );
activated( api.settings.theme.active );
api.bind( 'change', function() {
state('saved').set( false );
});
api.bind( 'saved', function() {
state('saved').set( true );
state('activated').set( true );
});
activated.bind( function( to ) {
if ( to )
api.trigger( 'activated' );
});
// Expose states to the API.
api.state = state;
}());
// Temporary accordion code.
$('.customize-section-title').bind('click keydown', function( event ) {
if ( event.type === 'keydown' && 13 !== event.which ) // enter
return;
var clicked = $( this ).parents( '.customize-section' );
if ( clicked.hasClass('cannot-expand') )
return;
// Scroll up if on #customize-section-title_tagline
if ('customize-section-title_tagline' === clicked.attr('id'))
$('.wp-full-overlay-sidebar-content').scrollTop(0);
$( '.customize-section' ).not( clicked ).removeClass( 'open' );
clicked.toggleClass( 'open' );
event.preventDefault();
});
// Button bindings.
$('#save').click( function( event ) {
previewer.save();
event.preventDefault();
}).keydown( function( event ) {
if ( 9 === event.which ) // tab
return;
if ( 13 === event.which ) // enter
previewer.save();
event.preventDefault();
});
$('.back').keydown( function( event ) {
if ( 9 === event.which ) // tab
return;
if ( 13 === event.which ) // enter
parent.send( 'close' );
event.preventDefault();
});
$('.collapse-sidebar').on( 'click keydown', function( event ) {
if ( event.type === 'keydown' && 13 !== event.which ) // enter
return;
overlay.toggleClass( 'collapsed' ).toggleClass( 'expanded' );
event.preventDefault();
});
// Create a potential postMessage connection with the parent frame.
parent = new api.Messenger({
url: api.settings.url.parent,
channel: 'loader'
});
// If we receive a 'back' event, we're inside an iframe.
// Send any clicks to the 'Return' link to the parent page.
parent.bind( 'back', function() {
$('.back').on( 'click.back', function( event ) {
event.preventDefault();
parent.send( 'close' );
});
});
// Pass events through to the parent.
api.bind( 'saved', function() {
parent.send( 'saved' );
});
// When activated, let the loader handle redirecting the page.
// If no loader exists, redirect the page ourselves (if a url exists).
api.bind( 'activated', function() {
if ( parent.targetWindow() )
parent.send( 'activated', api.settings.url.activated );
else if ( api.settings.url.activated )
window.location = api.settings.url.activated;
});
// Initialize the connection with the parent frame.
parent.send( 'ready' );
// Control visibility for default controls
$.each({
'background_image': {
controls: [ 'background_repeat', 'background_position_x', 'background_attachment' ],
callback: function( to ) { return !! to }
},
'show_on_front': {
controls: [ 'page_on_front', 'page_for_posts' ],
callback: function( to ) { return 'page' === to }
},
'header_textcolor': {
controls: [ 'header_textcolor' ],
callback: function( to ) { return 'blank' !== to }
}
}, function( settingId, o ) {
api( settingId, function( setting ) {
$.each( o.controls, function( i, controlId ) {
api.control( controlId, function( control ) {
var visibility = function( to ) {
control.container.toggle( o.callback( to ) );
};
visibility( setting.get() );
setting.bind( visibility );
});
});
});
});
// Juggle the two controls that use header_textcolor
api.control( 'display_header_text', function( control ) {
var last = '';
control.elements[0].unsync( api( 'header_textcolor' ) );
control.element = new api.Element( control.container.find('input') );
control.element.set( 'blank' !== control.setting() );
control.element.bind( function( to ) {
if ( ! to )
last = api( 'header_textcolor' ).get();
control.setting.set( to ? last : 'blank' );
});
control.setting.bind( function( to ) {
control.element.set( 'blank' !== to );
});
});
// Handle header image data
api.control( 'header_image', function( control ) {
control.setting.bind( function( to ) {
if ( to === control.params.removed )
control.settings.data.set( false );
});
control.library.on( 'click', 'a', function( event ) {
control.settings.data.set( $(this).data('customizeHeaderImageData') );
});
control.uploader.success = function( attachment ) {
var data;
api.ImageControl.prototype.success.call( control, attachment );
data = {
attachment_id: attachment.get('id'),
url: attachment.get('url'),
thumbnail_url: attachment.get('url'),
height: attachment.get('height'),
width: attachment.get('width')
};
attachment.element.data( 'customizeHeaderImageData', data );
control.settings.data.set( data );
};
});
api.trigger( 'ready' );
// Make sure left column gets focus
var topFocus = $('.back');
topFocus.focus();
setTimeout(function () {
topFocus.focus();
}, 200);
});
})( wp, jQuery );
| JavaScript |
// send html to the post editor
var wpActiveEditor;
function send_to_editor(h) {
var ed, mce = typeof(tinymce) != 'undefined', qt = typeof(QTags) != 'undefined';
if ( !wpActiveEditor ) {
if ( mce && tinymce.activeEditor ) {
ed = tinymce.activeEditor;
wpActiveEditor = ed.id;
} else if ( !qt ) {
return false;
}
} else if ( mce ) {
if ( tinymce.activeEditor && (tinymce.activeEditor.id == 'mce_fullscreen' || tinymce.activeEditor.id == 'wp_mce_fullscreen') )
ed = tinymce.activeEditor;
else
ed = tinymce.get(wpActiveEditor);
}
if ( ed && !ed.isHidden() ) {
// restore caret position on IE
if ( tinymce.isIE && ed.windowManager.insertimagebookmark )
ed.selection.moveToBookmark(ed.windowManager.insertimagebookmark);
if ( h.indexOf('[caption') !== -1 ) {
if ( ed.wpSetImgCaption )
h = ed.wpSetImgCaption(h);
} else if ( h.indexOf('[gallery') !== -1 ) {
if ( ed.plugins.wpgallery )
h = ed.plugins.wpgallery._do_gallery(h);
} else if ( h.indexOf('[embed') === 0 ) {
if ( ed.plugins.wordpress )
h = ed.plugins.wordpress._setEmbed(h);
}
ed.execCommand('mceInsertContent', false, h);
} else if ( qt ) {
QTags.insertContent(h);
} else {
document.getElementById(wpActiveEditor).value += h;
}
try{tb_remove();}catch(e){};
}
// thickbox settings
var tb_position;
(function($) {
tb_position = function() {
var tbWindow = $('#TB_window'), width = $(window).width(), H = $(window).height(), W = ( 720 < width ) ? 720 : width, adminbar_height = 0;
if ( $('body.admin-bar').length )
adminbar_height = 28;
if ( tbWindow.size() ) {
tbWindow.width( W - 50 ).height( H - 45 - adminbar_height );
$('#TB_iframeContent').width( W - 50 ).height( H - 75 - adminbar_height );
tbWindow.css({'margin-left': '-' + parseInt((( W - 50 ) / 2),10) + 'px'});
if ( typeof document.body.style.maxWidth != 'undefined' )
tbWindow.css({'top': 20 + adminbar_height + 'px','margin-top':'0'});
};
return $('a.thickbox').each( function() {
var href = $(this).attr('href');
if ( ! href ) return;
href = href.replace(/&width=[0-9]+/g, '');
href = href.replace(/&height=[0-9]+/g, '');
$(this).attr( 'href', href + '&width=' + ( W - 80 ) + '&height=' + ( H - 85 - adminbar_height ) );
});
};
$(window).resize(function(){ tb_position(); });
// store caret position in IE
$(document).ready(function($){
$('a.thickbox').click(function(){
var ed;
if ( typeof(tinymce) != 'undefined' && tinymce.isIE && ( ed = tinymce.get(wpActiveEditor) ) && !ed.isHidden() ) {
ed.focus();
ed.windowManager.insertimagebookmark = ed.selection.getBookmark();
}
});
});
})(jQuery);
| JavaScript |
(function($,undefined) {
wpWordCount = {
settings : {
strip : /<[a-zA-Z\/][^<>]*>/g, // strip HTML tags
clean : /[0-9.(),;:!?%#$¿'"_+=\\/-]+/g, // regexp to remove punctuation, etc.
w : /\S\s+/g, // word-counting regexp
c : /\S/g // char-counting regexp for asian languages
},
block : 0,
wc : function(tx, type) {
var t = this, w = $('.word-count'), tc = 0;
if ( type === undefined )
type = wordCountL10n.type;
if ( type !== 'w' && type !== 'c' )
type = 'w';
if ( t.block )
return;
t.block = 1;
setTimeout( function() {
if ( tx ) {
tx = tx.replace( t.settings.strip, ' ' ).replace( / | /gi, ' ' );
tx = tx.replace( t.settings.clean, '' );
tx.replace( t.settings[type], function(){tc++;} );
}
w.html(tc.toString());
setTimeout( function() { t.block = 0; }, 2000 );
}, 1 );
}
}
$(document).bind( 'wpcountwords', function(e, txt) {
wpWordCount.wc(txt);
});
}(jQuery));
| JavaScript |
jQuery(document).ready( function($) {
$('#link_rel').prop('readonly', true);
$('#linkxfndiv input').bind('click keyup', function() {
var isMe = $('#me').is(':checked'), inputs = '';
$('input.valinp').each( function() {
if (isMe) {
$(this).prop('disabled', true).parent().addClass('disabled');
} else {
$(this).removeAttr('disabled').parent().removeClass('disabled');
if ( $(this).is(':checked') && $(this).val() != '')
inputs += $(this).val() + ' ';
}
});
$('#link_rel').val( (isMe) ? 'me' : inputs.substr(0,inputs.length - 1) );
});
});
| JavaScript |
(function($) {
$(document).ready(function() {
var bgImage = $("#custom-background-image"),
frame;
$('#background-color').wpColorPicker({
change: function( event, ui ) {
bgImage.css('background-color', ui.color.toString());
},
clear: function() {
bgImage.css('background-color', '');
}
});
$('input[name="background-position-x"]').change(function() {
bgImage.css('background-position', $(this).val() + ' top');
});
$('input[name="background-repeat"]').change(function() {
bgImage.css('background-repeat', $(this).val());
});
$('#choose-from-library-link').click( function( event ) {
var $el = $(this);
event.preventDefault();
// If the media frame already exists, reopen it.
if ( frame ) {
frame.open();
return;
}
// Create the media frame.
frame = wp.media.frames.customBackground = wp.media({
// Set the title of the modal.
title: $el.data('choose'),
// Tell the modal to show only images.
library: {
type: 'image'
},
// Customize the submit button.
button: {
// Set the text of the button.
text: $el.data('update'),
// Tell the button not to close the modal, since we're
// going to refresh the page when the image is selected.
close: false
}
});
// When an image is selected, run a callback.
frame.on( 'select', function() {
// Grab the selected attachment.
var attachment = frame.state().get('selection').first();
// Run an AJAX request to set the background image.
$.post( ajaxurl, {
action: 'set-background-image',
attachment_id: attachment.id,
size: 'full'
}).done( function() {
// When the request completes, reload the window.
window.location.reload();
});
});
// Finally, open the modal.
frame.open();
});
});
})(jQuery); | JavaScript |
(function($) {
inlineEditTax = {
init : function() {
var t = this, row = $('#inline-edit');
t.type = $('#the-list').attr('data-wp-lists').substr(5);
t.what = '#'+t.type+'-';
$('.editinline').live('click', function(){
inlineEditTax.edit(this);
return false;
});
// prepare the edit row
row.keyup(function(e) { if(e.which == 27) return inlineEditTax.revert(); });
$('a.cancel', row).click(function() { return inlineEditTax.revert(); });
$('a.save', row).click(function() { return inlineEditTax.save(this); });
$('input, select', row).keydown(function(e) { if(e.which == 13) return inlineEditTax.save(this); });
$('#posts-filter input[type="submit"]').mousedown(function(e){
t.revert();
});
},
toggle : function(el) {
var t = this;
$(t.what+t.getId(el)).css('display') == 'none' ? t.revert() : t.edit(el);
},
edit : function(id) {
var t = this, editRow;
t.revert();
if ( typeof(id) == 'object' )
id = t.getId(id);
editRow = $('#inline-edit').clone(true), rowData = $('#inline_'+id);
$('td', editRow).attr('colspan', $('.widefat:first thead th:visible').length);
if ( $(t.what+id).hasClass('alternate') )
$(editRow).addClass('alternate');
$(t.what+id).hide().after(editRow);
$(':input[name="name"]', editRow).val( $('.name', rowData).text() );
$(':input[name="slug"]', editRow).val( $('.slug', rowData).text() );
$(editRow).attr('id', 'edit-'+id).addClass('inline-editor').show();
$('.ptitle', editRow).eq(0).focus();
return false;
},
save : function(id) {
var params, fields, tax = $('input[name="taxonomy"]').val() || '';
if( typeof(id) == 'object' )
id = this.getId(id);
$('table.widefat .spinner').show();
params = {
action: 'inline-save-tax',
tax_type: this.type,
tax_ID: id,
taxonomy: tax
};
fields = $('#edit-'+id+' :input').serialize();
params = fields + '&' + $.param(params);
// make ajax request
$.post( ajaxurl, params,
function(r) {
var row, new_id;
$('table.widefat .spinner').hide();
if (r) {
if ( -1 != r.indexOf('<tr') ) {
$(inlineEditTax.what+id).remove();
new_id = $(r).attr('id');
$('#edit-'+id).before(r).remove();
row = new_id ? $('#'+new_id) : $(inlineEditTax.what+id);
row.hide().fadeIn();
} else
$('#edit-'+id+' .inline-edit-save .error').html(r).show();
} else
$('#edit-'+id+' .inline-edit-save .error').html(inlineEditL10n.error).show();
}
);
return false;
},
revert : function() {
var id = $('table.widefat tr.inline-editor').attr('id');
if ( id ) {
$('table.widefat .spinner').hide();
$('#'+id).remove();
id = id.substr( id.lastIndexOf('-') + 1 );
$(this.what+id).show();
}
return false;
},
getId : function(o) {
var id = o.tagName == 'TR' ? o.id : $(o).parents('tr').attr('id'), parts = id.split('-');
return parts[parts.length - 1];
}
};
$(document).ready(function(){inlineEditTax.init();});
})(jQuery);
| JavaScript |
jQuery(document).ready(function($) {
$('.delete-tag').live('click', function(e){
var t = $(this), tr = t.parents('tr'), r = true, data;
if ( 'undefined' != showNotice )
r = showNotice.warn();
if ( r ) {
data = t.attr('href').replace(/[^?]*\?/, '').replace(/action=delete/, 'action=delete-tag');
$.post(ajaxurl, data, function(r){
if ( '1' == r ) {
$('#ajax-response').empty();
tr.fadeOut('normal', function(){ tr.remove(); });
// Remove the term from the parent box and tag cloud
$('select#parent option[value="' + data.match(/tag_ID=(\d+)/)[1] + '"]').remove();
$('a.tag-link-' + data.match(/tag_ID=(\d+)/)[1]).remove();
} else if ( '-1' == r ) {
$('#ajax-response').empty().append('<div class="error"><p>' + tagsl10n.noPerm + '</p></div>');
tr.children().css('backgroundColor', '');
} else {
$('#ajax-response').empty().append('<div class="error"><p>' + tagsl10n.broken + '</p></div>');
tr.children().css('backgroundColor', '');
}
});
tr.children().css('backgroundColor', '#f33');
}
return false;
});
$('#submit').click(function(){
var form = $(this).parents('form');
if ( !validateForm( form ) )
return false;
$.post(ajaxurl, $('#addtag').serialize(), function(r){
$('#ajax-response').empty();
var res = wpAjax.parseAjaxResponse(r, 'ajax-response');
if ( ! res || res.errors )
return;
var parent = form.find('select#parent').val();
if ( parent > 0 && $('#tag-' + parent ).length > 0 ) // If the parent exists on this page, insert it below. Else insert it at the top of the list.
$('.tags #tag-' + parent).after( res.responses[0].supplemental['noparents'] ); // As the parent exists, Insert the version with - - - prefixed
else
$('.tags').prepend( res.responses[0].supplemental['parents'] ); // As the parent is not visible, Insert the version with Parent - Child - ThisTerm
$('.tags .no-items').remove();
if ( form.find('select#parent') ) {
// Parents field exists, Add new term to the list.
var term = res.responses[1].supplemental;
// Create an indent for the Parent field
var indent = '';
for ( var i = 0; i < res.responses[1].position; i++ )
indent += ' ';
form.find('select#parent option:selected').after('<option value="' + term['term_id'] + '">' + indent + term['name'] + '</option>');
}
$('input[type="text"]:visible, textarea:visible', form).val('');
});
return false;
});
});
| JavaScript |
var switchEditors = {
switchto: function(el) {
var aid = el.id, l = aid.length, id = aid.substr(0, l - 5), mode = aid.substr(l - 4);
this.go(id, mode);
},
go: function(id, mode) { // mode can be 'html', 'tmce', or 'toggle'; 'html' is used for the "Text" editor tab.
id = id || 'content';
mode = mode || 'toggle';
var t = this, ed = tinyMCE.get(id), wrap_id, txtarea_el, dom = tinymce.DOM;
wrap_id = 'wp-'+id+'-wrap';
txtarea_el = dom.get(id);
if ( 'toggle' == mode ) {
if ( ed && !ed.isHidden() )
mode = 'html';
else
mode = 'tmce';
}
if ( 'tmce' == mode || 'tinymce' == mode ) {
if ( ed && ! ed.isHidden() )
return false;
if ( typeof(QTags) != 'undefined' )
QTags.closeAllTags(id);
if ( tinyMCEPreInit.mceInit[id] && tinyMCEPreInit.mceInit[id].wpautop )
txtarea_el.value = t.wpautop( txtarea_el.value );
if ( ed ) {
ed.show();
} else {
ed = new tinymce.Editor(id, tinyMCEPreInit.mceInit[id]);
ed.render();
}
dom.removeClass(wrap_id, 'html-active');
dom.addClass(wrap_id, 'tmce-active');
setUserSetting('editor', 'tinymce');
} else if ( 'html' == mode ) {
if ( ed && ed.isHidden() )
return false;
if ( ed )
ed.hide();
dom.removeClass(wrap_id, 'tmce-active');
dom.addClass(wrap_id, 'html-active');
setUserSetting('editor', 'html');
}
return false;
},
_wp_Nop : function(content) {
var blocklist1, blocklist2, preserve_linebreaks = false, preserve_br = false;
// Protect pre|script tags
if ( content.indexOf('<pre') != -1 || content.indexOf('<script') != -1 ) {
preserve_linebreaks = true;
content = content.replace(/<(pre|script)[^>]*>[\s\S]+?<\/\1>/g, function(a) {
a = a.replace(/<br ?\/?>(\r\n|\n)?/g, '<wp-temp-lb>');
return a.replace(/<\/?p( [^>]*)?>(\r\n|\n)?/g, '<wp-temp-lb>');
});
}
// keep <br> tags inside captions and remove line breaks
if ( content.indexOf('[caption') != -1 ) {
preserve_br = true;
content = content.replace(/\[caption[\s\S]+?\[\/caption\]/g, function(a) {
return a.replace(/<br([^>]*)>/g, '<wp-temp-br$1>').replace(/[\r\n\t]+/, '');
});
}
// Pretty it up for the source editor
blocklist1 = 'blockquote|ul|ol|li|table|thead|tbody|tfoot|tr|th|td|div|h[1-6]|p|fieldset';
content = content.replace(new RegExp('\\s*</('+blocklist1+')>\\s*', 'g'), '</$1>\n');
content = content.replace(new RegExp('\\s*<((?:'+blocklist1+')(?: [^>]*)?)>', 'g'), '\n<$1>');
// Mark </p> if it has any attributes.
content = content.replace(/(<p [^>]+>.*?)<\/p>/g, '$1</p#>');
// Sepatate <div> containing <p>
content = content.replace(/<div( [^>]*)?>\s*<p>/gi, '<div$1>\n\n');
// Remove <p> and <br />
content = content.replace(/\s*<p>/gi, '');
content = content.replace(/\s*<\/p>\s*/gi, '\n\n');
content = content.replace(/\n[\s\u00a0]+\n/g, '\n\n');
content = content.replace(/\s*<br ?\/?>\s*/gi, '\n');
// Fix some block element newline issues
content = content.replace(/\s*<div/g, '\n<div');
content = content.replace(/<\/div>\s*/g, '</div>\n');
content = content.replace(/\s*\[caption([^\[]+)\[\/caption\]\s*/gi, '\n\n[caption$1[/caption]\n\n');
content = content.replace(/caption\]\n\n+\[caption/g, 'caption]\n\n[caption');
blocklist2 = 'blockquote|ul|ol|li|table|thead|tbody|tfoot|tr|th|td|h[1-6]|pre|fieldset';
content = content.replace(new RegExp('\\s*<((?:'+blocklist2+')(?: [^>]*)?)\\s*>', 'g'), '\n<$1>');
content = content.replace(new RegExp('\\s*</('+blocklist2+')>\\s*', 'g'), '</$1>\n');
content = content.replace(/<li([^>]*)>/g, '\t<li$1>');
if ( content.indexOf('<hr') != -1 ) {
content = content.replace(/\s*<hr( [^>]*)?>\s*/g, '\n\n<hr$1>\n\n');
}
if ( content.indexOf('<object') != -1 ) {
content = content.replace(/<object[\s\S]+?<\/object>/g, function(a){
return a.replace(/[\r\n]+/g, '');
});
}
// Unmark special paragraph closing tags
content = content.replace(/<\/p#>/g, '</p>\n');
content = content.replace(/\s*(<p [^>]+>[\s\S]*?<\/p>)/g, '\n$1');
// Trim whitespace
content = content.replace(/^\s+/, '');
content = content.replace(/[\s\u00a0]+$/, '');
// put back the line breaks in pre|script
if ( preserve_linebreaks )
content = content.replace(/<wp-temp-lb>/g, '\n');
// and the <br> tags in captions
if ( preserve_br )
content = content.replace(/<wp-temp-br([^>]*)>/g, '<br$1>');
return content;
},
_wp_Autop : function(pee) {
var preserve_linebreaks = false, preserve_br = false,
blocklist = 'table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|option|form|map|area|blockquote|address|math|style|p|h[1-6]|hr|fieldset|noscript|samp|legend|section|article|aside|hgroup|header|footer|nav|figure|figcaption|details|menu|summary';
if ( pee.indexOf('<object') != -1 ) {
pee = pee.replace(/<object[\s\S]+?<\/object>/g, function(a){
return a.replace(/[\r\n]+/g, '');
});
}
pee = pee.replace(/<[^<>]+>/g, function(a){
return a.replace(/[\r\n]+/g, ' ');
});
// Protect pre|script tags
if ( pee.indexOf('<pre') != -1 || pee.indexOf('<script') != -1 ) {
preserve_linebreaks = true;
pee = pee.replace(/<(pre|script)[^>]*>[\s\S]+?<\/\1>/g, function(a) {
return a.replace(/(\r\n|\n)/g, '<wp-temp-lb>');
});
}
// keep <br> tags inside captions and convert line breaks
if ( pee.indexOf('[caption') != -1 ) {
preserve_br = true;
pee = pee.replace(/\[caption[\s\S]+?\[\/caption\]/g, function(a) {
// keep existing <br>
a = a.replace(/<br([^>]*)>/g, '<wp-temp-br$1>');
// no line breaks inside HTML tags
a = a.replace(/<[a-zA-Z0-9]+( [^<>]+)?>/g, function(b){
return b.replace(/[\r\n\t]+/, ' ');
});
// convert remaining line breaks to <br>
return a.replace(/\s*\n\s*/g, '<wp-temp-br />');
});
}
pee = pee + '\n\n';
pee = pee.replace(/<br \/>\s*<br \/>/gi, '\n\n');
pee = pee.replace(new RegExp('(<(?:'+blocklist+')(?: [^>]*)?>)', 'gi'), '\n$1');
pee = pee.replace(new RegExp('(</(?:'+blocklist+')>)', 'gi'), '$1\n\n');
pee = pee.replace(/<hr( [^>]*)?>/gi, '<hr$1>\n\n'); // hr is self closing block element
pee = pee.replace(/\r\n|\r/g, '\n');
pee = pee.replace(/\n\s*\n+/g, '\n\n');
pee = pee.replace(/([\s\S]+?)\n\n/g, '<p>$1</p>\n');
pee = pee.replace(/<p>\s*?<\/p>/gi, '');
pee = pee.replace(new RegExp('<p>\\s*(</?(?:'+blocklist+')(?: [^>]*)?>)\\s*</p>', 'gi'), "$1");
pee = pee.replace(/<p>(<li.+?)<\/p>/gi, '$1');
pee = pee.replace(/<p>\s*<blockquote([^>]*)>/gi, '<blockquote$1><p>');
pee = pee.replace(/<\/blockquote>\s*<\/p>/gi, '</p></blockquote>');
pee = pee.replace(new RegExp('<p>\\s*(</?(?:'+blocklist+')(?: [^>]*)?>)', 'gi'), "$1");
pee = pee.replace(new RegExp('(</?(?:'+blocklist+')(?: [^>]*)?>)\\s*</p>', 'gi'), "$1");
pee = pee.replace(/\s*\n/gi, '<br />\n');
pee = pee.replace(new RegExp('(</?(?:'+blocklist+')[^>]*>)\\s*<br />', 'gi'), "$1");
pee = pee.replace(/<br \/>(\s*<\/?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)>)/gi, '$1');
pee = pee.replace(/(?:<p>|<br ?\/?>)*\s*\[caption([^\[]+)\[\/caption\]\s*(?:<\/p>|<br ?\/?>)*/gi, '[caption$1[/caption]');
pee = pee.replace(/(<(?:div|th|td|form|fieldset|dd)[^>]*>)(.*?)<\/p>/g, function(a, b, c) {
if ( c.match(/<p( [^>]*)?>/) )
return a;
return b + '<p>' + c + '</p>';
});
// put back the line breaks in pre|script
if ( preserve_linebreaks )
pee = pee.replace(/<wp-temp-lb>/g, '\n');
if ( preserve_br )
pee = pee.replace(/<wp-temp-br([^>]*)>/g, '<br$1>');
return pee;
},
pre_wpautop : function(content) {
var t = this, o = { o: t, data: content, unfiltered: content },
q = typeof(jQuery) != 'undefined';
if ( q )
jQuery('body').trigger('beforePreWpautop', [o]);
o.data = t._wp_Nop(o.data);
if ( q )
jQuery('body').trigger('afterPreWpautop', [o]);
return o.data;
},
wpautop : function(pee) {
var t = this, o = { o: t, data: pee, unfiltered: pee },
q = typeof(jQuery) != 'undefined';
if ( q )
jQuery('body').trigger('beforeWpautop', [o]);
o.data = t._wp_Autop(o.data);
if ( q )
jQuery('body').trigger('afterWpautop', [o]);
return o.data;
}
}
| JavaScript |
jQuery(document).ready(function($) {
var gallerySortable, gallerySortableInit, w, desc = false;
gallerySortableInit = function() {
gallerySortable = $('#media-items').sortable( {
items: 'div.media-item',
placeholder: 'sorthelper',
axis: 'y',
distance: 2,
handle: 'div.filename',
stop: function(e, ui) {
// When an update has occurred, adjust the order for each item
var all = $('#media-items').sortable('toArray'), len = all.length;
$.each(all, function(i, id) {
var order = desc ? (len - i) : (1 + i);
$('#' + id + ' .menu_order input').val(order);
});
}
} );
}
sortIt = function() {
var all = $('.menu_order_input'), len = all.length;
all.each(function(i){
var order = desc ? (len - i) : (1 + i);
$(this).val(order);
});
}
clearAll = function(c) {
c = c || 0;
$('.menu_order_input').each(function(){
if ( this.value == '0' || c ) this.value = '';
});
}
$('#asc').click(function(){desc = false; sortIt(); return false;});
$('#desc').click(function(){desc = true; sortIt(); return false;});
$('#clear').click(function(){clearAll(1); return false;});
$('#showall').click(function(){
$('#sort-buttons span a').toggle();
$('a.describe-toggle-on').hide();
$('a.describe-toggle-off, table.slidetoggle').show();
$('img.pinkynail').toggle(false);
return false;
});
$('#hideall').click(function(){
$('#sort-buttons span a').toggle();
$('a.describe-toggle-on').show();
$('a.describe-toggle-off, table.slidetoggle').hide();
$('img.pinkynail').toggle(true);
return false;
});
// initialize sortable
gallerySortableInit();
clearAll();
if ( $('#media-items>*').length > 1 ) {
w = wpgallery.getWin();
$('#save-all, #gallery-settings').show();
if ( typeof w.tinyMCE != 'undefined' && w.tinyMCE.activeEditor && ! w.tinyMCE.activeEditor.isHidden() ) {
wpgallery.mcemode = true;
wpgallery.init();
} else {
$('#insert-gallery').show();
}
}
});
jQuery(window).unload( function () { tinymce = tinyMCE = wpgallery = null; } ); // Cleanup
/* gallery settings */
var tinymce = null, tinyMCE, wpgallery;
wpgallery = {
mcemode : false,
editor : {},
dom : {},
is_update : false,
el : {},
I : function(e) {
return document.getElementById(e);
},
init: function() {
var t = this, li, q, i, it, w = t.getWin();
if ( ! t.mcemode ) return;
li = ('' + document.location.search).replace(/^\?/, '').split('&');
q = {};
for (i=0; i<li.length; i++) {
it = li[i].split('=');
q[unescape(it[0])] = unescape(it[1]);
}
if (q.mce_rdomain)
document.domain = q.mce_rdomain;
// Find window & API
tinymce = w.tinymce;
tinyMCE = w.tinyMCE;
t.editor = tinymce.EditorManager.activeEditor;
t.setup();
},
getWin : function() {
return window.dialogArguments || opener || parent || top;
},
setup : function() {
var t = this, a, ed = t.editor, g, columns, link, order, orderby;
if ( ! t.mcemode ) return;
t.el = ed.selection.getNode();
if ( t.el.nodeName != 'IMG' || ! ed.dom.hasClass(t.el, 'wpGallery') ) {
if ( (g = ed.dom.select('img.wpGallery')) && g[0] ) {
t.el = g[0];
} else {
if ( getUserSetting('galfile') == '1' ) t.I('linkto-file').checked = "checked";
if ( getUserSetting('galdesc') == '1' ) t.I('order-desc').checked = "checked";
if ( getUserSetting('galcols') ) t.I('columns').value = getUserSetting('galcols');
if ( getUserSetting('galord') ) t.I('orderby').value = getUserSetting('galord');
jQuery('#insert-gallery').show();
return;
}
}
a = ed.dom.getAttrib(t.el, 'title');
a = ed.dom.decode(a);
if ( a ) {
jQuery('#update-gallery').show();
t.is_update = true;
columns = a.match(/columns=['"]([0-9]+)['"]/);
link = a.match(/link=['"]([^'"]+)['"]/i);
order = a.match(/order=['"]([^'"]+)['"]/i);
orderby = a.match(/orderby=['"]([^'"]+)['"]/i);
if ( link && link[1] ) t.I('linkto-file').checked = "checked";
if ( order && order[1] ) t.I('order-desc').checked = "checked";
if ( columns && columns[1] ) t.I('columns').value = ''+columns[1];
if ( orderby && orderby[1] ) t.I('orderby').value = orderby[1];
} else {
jQuery('#insert-gallery').show();
}
},
update : function() {
var t = this, ed = t.editor, all = '', s;
if ( ! t.mcemode || ! t.is_update ) {
s = '[gallery'+t.getSettings()+']';
t.getWin().send_to_editor(s);
return;
}
if (t.el.nodeName != 'IMG') return;
all = ed.dom.decode(ed.dom.getAttrib(t.el, 'title'));
all = all.replace(/\s*(order|link|columns|orderby)=['"]([^'"]+)['"]/gi, '');
all += t.getSettings();
ed.dom.setAttrib(t.el, 'title', all);
t.getWin().tb_remove();
},
getSettings : function() {
var I = this.I, s = '';
if ( I('linkto-file').checked ) {
s += ' link="file"';
setUserSetting('galfile', '1');
}
if ( I('order-desc').checked ) {
s += ' order="DESC"';
setUserSetting('galdesc', '1');
}
if ( I('columns').value != 3 ) {
s += ' columns="'+I('columns').value+'"';
setUserSetting('galcols', I('columns').value);
}
if ( I('orderby').value != 'menu_order' ) {
s += ' orderby="'+I('orderby').value+'"';
setUserSetting('galord', I('orderby').value);
}
return s;
}
};
| JavaScript |
jQuery(function($){
$( 'body' ).bind( 'click.wp-gallery', function(e){
var target = $( e.target ), id, img_size;
if ( target.hasClass( 'wp-set-header' ) ) {
( window.dialogArguments || opener || parent || top ).location.href = target.data( 'location' );
e.preventDefault();
} else if ( target.hasClass( 'wp-set-background' ) ) {
id = target.data( 'attachment-id' );
img_size = $( 'input[name="attachments[' + id + '][image-size]"]:checked').val();
jQuery.post(ajaxurl, {
action: 'set-background-image',
attachment_id: id,
size: img_size
}, function(){
var win = window.dialogArguments || opener || parent || top;
win.tb_remove();
win.location.reload();
});
e.preventDefault();
}
});
});
| JavaScript |
/* Plugin Browser Thickbox related JS*/
var tb_position;
jQuery(document).ready(function($) {
tb_position = function() {
var tbWindow = $('#TB_window'), width = $(window).width(), H = $(window).height(), W = ( 720 < width ) ? 720 : width, adminbar_height = 0;
if ( $('body.admin-bar').length )
adminbar_height = 28;
if ( tbWindow.size() ) {
tbWindow.width( W - 50 ).height( H - 45 - adminbar_height );
$('#TB_iframeContent').width( W - 50 ).height( H - 75 - adminbar_height );
tbWindow.css({'margin-left': '-' + parseInt((( W - 50 ) / 2),10) + 'px'});
if ( typeof document.body.style.maxWidth != 'undefined' )
tbWindow.css({'top': 20 + adminbar_height + 'px','margin-top':'0'});
};
return $('a.thickbox').each( function() {
var href = $(this).attr('href');
if ( ! href )
return;
href = href.replace(/&width=[0-9]+/g, '');
href = href.replace(/&height=[0-9]+/g, '');
$(this).attr( 'href', href + '&width=' + ( W - 80 ) + '&height=' + ( H - 85 - adminbar_height ) );
});
};
$(window).resize(function(){ tb_position(); });
$('#dashboard_plugins a.thickbox, .plugins a.thickbox').click( function() {
tb_click.call(this);
$('#TB_title').css({'background-color':'#222','color':'#cfcfcf'});
$('#TB_ajaxWindowTitle').html('<strong>' + plugininstallL10n.plugin_information + '</strong> ' + $(this).attr('title') );
return false;
});
/* Plugin install related JS*/
$('#plugin-information #sidemenu a').click( function() {
var tab = $(this).attr('name');
//Flip the tab
$('#plugin-information-header a.current').removeClass('current');
$(this).addClass('current');
//Flip the content.
$('#section-holder div.section').hide(); //Hide 'em all
$('#section-' + tab).show();
return false;
});
$('a.install-now').click( function() {
return confirm( plugininstallL10n.ays );
});
});
| JavaScript |
var postboxes;
(function($) {
postboxes = {
add_postbox_toggles : function(page, args) {
var self = this;
self.init(page, args);
$('.postbox h3, .postbox .handlediv').bind('click.postboxes', function() {
var p = $(this).parent('.postbox'), id = p.attr('id');
if ( 'dashboard_browser_nag' == id )
return;
p.toggleClass('closed');
if ( page != 'press-this' )
self.save_state(page);
if ( id ) {
if ( !p.hasClass('closed') && $.isFunction(postboxes.pbshow) )
self.pbshow(id);
else if ( p.hasClass('closed') && $.isFunction(postboxes.pbhide) )
self.pbhide(id);
}
});
$('.postbox h3 a').click( function(e) {
e.stopPropagation();
});
$('.postbox a.dismiss').bind('click.postboxes', function(e) {
var hide_id = $(this).parents('.postbox').attr('id') + '-hide';
$( '#' + hide_id ).prop('checked', false).triggerHandler('click');
return false;
});
$('.hide-postbox-tog').bind('click.postboxes', function() {
var box = $(this).val();
if ( $(this).prop('checked') ) {
$('#' + box).show();
if ( $.isFunction( postboxes.pbshow ) )
self.pbshow( box );
} else {
$('#' + box).hide();
if ( $.isFunction( postboxes.pbhide ) )
self.pbhide( box );
}
self.save_state(page);
self._mark_area();
});
$('.columns-prefs input[type="radio"]').bind('click.postboxes', function(){
var n = parseInt($(this).val(), 10);
if ( n ) {
self._pb_edit(n);
self.save_order(page);
}
});
},
init : function(page, args) {
var isMobile = $(document.body).hasClass('mobile');
$.extend( this, args || {} );
$('#wpbody-content').css('overflow','hidden');
$('.meta-box-sortables').sortable({
placeholder: 'sortable-placeholder',
connectWith: '.meta-box-sortables',
items: '.postbox',
handle: '.hndle',
cursor: 'move',
delay: ( isMobile ? 200 : 0 ),
distance: 2,
tolerance: 'pointer',
forcePlaceholderSize: true,
helper: 'clone',
opacity: 0.65,
stop: function(e,ui) {
if ( $(this).find('#dashboard_browser_nag').is(':visible') && 'dashboard_browser_nag' != this.firstChild.id ) {
$(this).sortable('cancel');
return;
}
postboxes.save_order(page);
},
receive: function(e,ui) {
if ( 'dashboard_browser_nag' == ui.item[0].id )
$(ui.sender).sortable('cancel');
postboxes._mark_area();
}
});
if ( isMobile ) {
$(document.body).bind('orientationchange.postboxes', function(){ postboxes._pb_change(); });
this._pb_change();
}
this._mark_area();
},
save_state : function(page) {
var closed = $('.postbox').filter('.closed').map(function() { return this.id; }).get().join(','),
hidden = $('.postbox').filter(':hidden').map(function() { return this.id; }).get().join(',');
$.post(ajaxurl, {
action: 'closed-postboxes',
closed: closed,
hidden: hidden,
closedpostboxesnonce: jQuery('#closedpostboxesnonce').val(),
page: page
});
},
save_order : function(page) {
var postVars, page_columns = $('.columns-prefs input:checked').val() || 0;
postVars = {
action: 'meta-box-order',
_ajax_nonce: $('#meta-box-order-nonce').val(),
page_columns: page_columns,
page: page
}
$('.meta-box-sortables').each( function() {
postVars["order[" + this.id.split('-')[0] + "]"] = $(this).sortable( 'toArray' ).join(',');
} );
$.post( ajaxurl, postVars );
},
_mark_area : function() {
var visible = $('div.postbox:visible').length, side = $('#post-body #side-sortables');
$('#dashboard-widgets .meta-box-sortables:visible').each(function(n, el){
var t = $(this);
if ( visible == 1 || t.children('.postbox:visible').length )
t.removeClass('empty-container');
else
t.addClass('empty-container');
});
if ( side.length ) {
if ( side.children('.postbox:visible').length )
side.removeClass('empty-container');
else if ( $('#postbox-container-1').css('width') == '280px' )
side.addClass('empty-container');
}
},
_pb_edit : function(n) {
var el = $('.metabox-holder').get(0);
el.className = el.className.replace(/columns-\d+/, 'columns-' + n);
},
_pb_change : function() {
var check = $( 'label.columns-prefs-1 input[type="radio"]' );
switch ( window.orientation ) {
case 90:
case -90:
if ( !check.length || !check.is(':checked') )
this._pb_edit(2);
break;
case 0:
case 180:
if ( $('#poststuff').length ) {
this._pb_edit(1);
} else {
if ( !check.length || !check.is(':checked') )
this._pb_edit(2);
}
break;
}
},
/* Callbacks */
pbshow : false,
pbhide : false
};
}(jQuery));
| JavaScript |
(function($) {
inlineEditPost = {
init : function(){
var t = this, qeRow = $('#inline-edit'), bulkRow = $('#bulk-edit');
t.type = $('table.widefat').hasClass('pages') ? 'page' : 'post';
t.what = '#post-';
// prepare the edit rows
qeRow.keyup(function(e){
if (e.which == 27)
return inlineEditPost.revert();
});
bulkRow.keyup(function(e){
if (e.which == 27)
return inlineEditPost.revert();
});
$('a.cancel', qeRow).click(function(){
return inlineEditPost.revert();
});
$('a.save', qeRow).click(function(){
return inlineEditPost.save(this);
});
$('td', qeRow).keydown(function(e){
if ( e.which == 13 )
return inlineEditPost.save(this);
});
$('a.cancel', bulkRow).click(function(){
return inlineEditPost.revert();
});
$('#inline-edit .inline-edit-private input[value="private"]').click( function(){
var pw = $('input.inline-edit-password-input');
if ( $(this).prop('checked') ) {
pw.val('').prop('disabled', true);
} else {
pw.prop('disabled', false);
}
});
// add events
$('a.editinline').live('click', function(){
inlineEditPost.edit(this);
return false;
});
$('#bulk-title-div').parents('fieldset').after(
$('#inline-edit fieldset.inline-edit-categories').clone()
).siblings( 'fieldset:last' ).prepend(
$('#inline-edit label.inline-edit-tags').clone()
);
// hiearchical taxonomies expandable?
$('span.catshow').click(function(){
$(this).hide().next().show().parent().next().addClass("cat-hover");
});
$('span.cathide').click(function(){
$(this).hide().prev().show().parent().next().removeClass("cat-hover");
});
$('select[name="_status"] option[value="future"]', bulkRow).remove();
$('#doaction, #doaction2').click(function(e){
var n = $(this).attr('id').substr(2);
if ( $('select[name="'+n+'"]').val() == 'edit' ) {
e.preventDefault();
t.setBulk();
} else if ( $('form#posts-filter tr.inline-editor').length > 0 ) {
t.revert();
}
});
$('#post-query-submit').mousedown(function(e){
t.revert();
$('select[name^="action"]').val('-1');
});
},
toggle : function(el){
var t = this;
$(t.what+t.getId(el)).css('display') == 'none' ? t.revert() : t.edit(el);
},
setBulk : function(){
var te = '', type = this.type, tax, c = true;
this.revert();
$('#bulk-edit td').attr('colspan', $('.widefat:first thead th:visible').length);
$('table.widefat tbody').prepend( $('#bulk-edit') );
$('#bulk-edit').addClass('inline-editor').show();
$('tbody th.check-column input[type="checkbox"]').each(function(i){
if ( $(this).prop('checked') ) {
c = false;
var id = $(this).val(), theTitle;
theTitle = $('#inline_'+id+' .post_title').html() || inlineEditL10n.notitle;
te += '<div id="ttle'+id+'"><a id="_'+id+'" class="ntdelbutton" title="'+inlineEditL10n.ntdeltitle+'">X</a>'+theTitle+'</div>';
}
});
if ( c )
return this.revert();
$('#bulk-titles').html(te);
$('#bulk-titles a').click(function(){
var id = $(this).attr('id').substr(1);
$('table.widefat input[value="' + id + '"]').prop('checked', false);
$('#ttle'+id).remove();
});
// enable autocomplete for tags
if ( 'post' == type ) {
// support multi taxonomies?
tax = 'post_tag';
$('tr.inline-editor textarea[name="tax_input['+tax+']"]').suggest( ajaxurl + '?action=ajax-tag-search&tax=' + tax, { delay: 500, minchars: 2, multiple: true, multipleSep: inlineEditL10n.comma + ' ' } );
}
$('html, body').animate( { scrollTop: 0 }, 'fast' );
},
edit : function(id) {
var t = this, fields, editRow, rowData, status, pageOpt, pageLevel, nextPage, pageLoop = true, nextLevel, cur_format, f;
t.revert();
if ( typeof(id) == 'object' )
id = t.getId(id);
fields = ['post_title', 'post_name', 'post_author', '_status', 'jj', 'mm', 'aa', 'hh', 'mn', 'ss', 'post_password', 'post_format', 'menu_order'];
if ( t.type == 'page' )
fields.push('post_parent', 'page_template');
// add the new blank row
editRow = $('#inline-edit').clone(true);
$('td', editRow).attr('colspan', $('.widefat:first thead th:visible').length);
if ( $(t.what+id).hasClass('alternate') )
$(editRow).addClass('alternate');
$(t.what+id).hide().after(editRow);
// populate the data
rowData = $('#inline_'+id);
if ( !$(':input[name="post_author"] option[value="' + $('.post_author', rowData).text() + '"]', editRow).val() ) {
// author no longer has edit caps, so we need to add them to the list of authors
$(':input[name="post_author"]', editRow).prepend('<option value="' + $('.post_author', rowData).text() + '">' + $('#' + t.type + '-' + id + ' .author').text() + '</option>');
}
if ( $(':input[name="post_author"] option', editRow).length == 1 ) {
$('label.inline-edit-author', editRow).hide();
}
// hide unsupported formats, but leave the current format alone
cur_format = $('.post_format', rowData).text();
$('option.unsupported', editRow).each(function() {
var $this = $(this);
if ( $this.val() != cur_format )
$this.remove();
});
for ( f = 0; f < fields.length; f++ ) {
$(':input[name="' + fields[f] + '"]', editRow).val( $('.'+fields[f], rowData).text() );
}
if ( $('.comment_status', rowData).text() == 'open' )
$('input[name="comment_status"]', editRow).prop("checked", true);
if ( $('.ping_status', rowData).text() == 'open' )
$('input[name="ping_status"]', editRow).prop("checked", true);
if ( $('.sticky', rowData).text() == 'sticky' )
$('input[name="sticky"]', editRow).prop("checked", true);
// hierarchical taxonomies
$('.post_category', rowData).each(function(){
var term_ids = $(this).text();
if ( term_ids ) {
taxname = $(this).attr('id').replace('_'+id, '');
$('ul.'+taxname+'-checklist :checkbox', editRow).val(term_ids.split(','));
}
});
//flat taxonomies
$('.tags_input', rowData).each(function(){
var terms = $(this).text(),
taxname = $(this).attr('id').replace('_' + id, ''),
textarea = $('textarea.tax_input_' + taxname, editRow),
comma = inlineEditL10n.comma;
if ( terms ) {
if ( ',' !== comma )
terms = terms.replace(/,/g, comma);
textarea.val(terms);
}
textarea.suggest( ajaxurl + '?action=ajax-tag-search&tax=' + taxname, { delay: 500, minchars: 2, multiple: true, multipleSep: inlineEditL10n.comma + ' ' } );
});
// handle the post status
status = $('._status', rowData).text();
if ( 'future' != status )
$('select[name="_status"] option[value="future"]', editRow).remove();
if ( 'private' == status ) {
$('input[name="keep_private"]', editRow).prop("checked", true);
$('input.inline-edit-password-input').val('').prop('disabled', true);
}
// remove the current page and children from the parent dropdown
pageOpt = $('select[name="post_parent"] option[value="' + id + '"]', editRow);
if ( pageOpt.length > 0 ) {
pageLevel = pageOpt[0].className.split('-')[1];
nextPage = pageOpt;
while ( pageLoop ) {
nextPage = nextPage.next('option');
if (nextPage.length == 0) break;
nextLevel = nextPage[0].className.split('-')[1];
if ( nextLevel <= pageLevel ) {
pageLoop = false;
} else {
nextPage.remove();
nextPage = pageOpt;
}
}
pageOpt.remove();
}
$(editRow).attr('id', 'edit-'+id).addClass('inline-editor').show();
$('.ptitle', editRow).focus();
return false;
},
save : function(id) {
var params, fields, page = $('.post_status_page').val() || '';
if ( typeof(id) == 'object' )
id = this.getId(id);
$('table.widefat .spinner').show();
params = {
action: 'inline-save',
post_type: typenow,
post_ID: id,
edit_date: 'true',
post_status: page
};
fields = $('#edit-'+id+' :input').serialize();
params = fields + '&' + $.param(params);
// make ajax request
$.post( ajaxurl, params,
function(r) {
$('table.widefat .spinner').hide();
if (r) {
if ( -1 != r.indexOf('<tr') ) {
$(inlineEditPost.what+id).remove();
$('#edit-'+id).before(r).remove();
$(inlineEditPost.what+id).hide().fadeIn();
} else {
r = r.replace( /<.[^<>]*?>/g, '' );
$('#edit-'+id+' .inline-edit-save .error').html(r).show();
}
} else {
$('#edit-'+id+' .inline-edit-save .error').html(inlineEditL10n.error).show();
}
}
, 'html');
return false;
},
revert : function(){
var id = $('table.widefat tr.inline-editor').attr('id');
if ( id ) {
$('table.widefat .spinner').hide();
if ( 'bulk-edit' == id ) {
$('table.widefat #bulk-edit').removeClass('inline-editor').hide();
$('#bulk-titles').html('');
$('#inlineedit').append( $('#bulk-edit') );
} else {
$('#'+id).remove();
id = id.substr( id.lastIndexOf('-') + 1 );
$(this.what+id).show();
}
}
return false;
},
getId : function(o) {
var id = $(o).closest('tr').attr('id'),
parts = id.split('-');
return parts[parts.length - 1];
}
};
$(document).ready(function(){inlineEditPost.init();});
})(jQuery);
| JavaScript |
/**
* Theme Browsing
*
* Controls visibility of theme details on manage and install themes pages.
*/
jQuery( function($) {
$('#availablethemes').on( 'click', '.theme-detail', function (event) {
var theme = $(this).closest('.available-theme'),
details = theme.find('.themedetaildiv');
if ( ! details.length ) {
details = theme.find('.install-theme-info .theme-details');
details = details.clone().addClass('themedetaildiv').appendTo( theme ).hide();
}
details.toggle();
event.preventDefault();
});
});
/**
* Theme Install
*
* Displays theme previews on theme install pages.
*/
jQuery( function($) {
if( ! window.postMessage )
return;
var preview = $('#theme-installer'),
info = preview.find('.install-theme-info'),
panel = preview.find('.wp-full-overlay-main'),
body = $( document.body );
preview.on( 'click', '.close-full-overlay', function( event ) {
preview.fadeOut( 200, function() {
panel.empty();
body.removeClass('theme-installer-active full-overlay-active');
});
event.preventDefault();
});
preview.on( 'click', '.collapse-sidebar', function( event ) {
preview.toggleClass( 'collapsed' ).toggleClass( 'expanded' );
event.preventDefault();
});
$('#availablethemes').on( 'click', '.install-theme-preview', function( event ) {
var src;
info.html( $(this).closest('.installable-theme').find('.install-theme-info').html() );
src = info.find( '.theme-preview-url' ).val();
panel.html( '<iframe src="' + src + '" />');
preview.fadeIn( 200, function() {
body.addClass('theme-installer-active full-overlay-active');
});
event.preventDefault();
});
});
var ThemeViewer;
(function($){
ThemeViewer = function( args ) {
function init() {
$( '#filter-click, #mini-filter-click' ).unbind( 'click' ).click( function() {
$( '#filter-click' ).toggleClass( 'current' );
$( '#filter-box' ).slideToggle();
$( '#current-theme' ).slideToggle( 300 );
return false;
});
$( '#filter-box :checkbox' ).unbind( 'click' ).click( function() {
var count = $( '#filter-box :checked' ).length,
text = $( '#filter-click' ).text();
if ( text.indexOf( '(' ) != -1 )
text = text.substr( 0, text.indexOf( '(' ) );
if ( count == 0 )
$( '#filter-click' ).text( text );
else
$( '#filter-click' ).text( text + ' (' + count + ')' );
});
/* $('#filter-box :submit').unbind( 'click' ).click(function() {
var features = [];
$('#filter-box :checked').each(function() {
features.push($(this).val());
});
listTable.update_rows({'features': features}, true, function() {
$( '#filter-click' ).toggleClass( 'current' );
$( '#filter-box' ).slideToggle();
$( '#current-theme' ).slideToggle( 300 );
});
return false;
}); */
}
// These are the functions we expose
var api = {
init: init
};
return api;
}
})(jQuery);
jQuery( document ).ready( function($) {
theme_viewer = new ThemeViewer();
theme_viewer.init();
});
/**
* Class that provides infinite scroll for Themes admin screens
*
* @since 3.4
*
* @uses ajaxurl
* @uses list_args
* @uses theme_list_args
* @uses $('#_ajax_fetch_list_nonce').val()
* */
var ThemeScroller;
(function($){
ThemeScroller = {
querying: false,
scrollPollingDelay: 500,
failedRetryDelay: 4000,
outListBottomThreshold: 300,
/**
* Initializer
*
* @since 3.4
* @access private
*/
init: function() {
var self = this;
// Get out early if we don't have the required arguments.
if ( typeof ajaxurl === 'undefined' ||
typeof list_args === 'undefined' ||
typeof theme_list_args === 'undefined' ) {
$('.pagination-links').show();
return;
}
// Handle inputs
this.nonce = $('#_ajax_fetch_list_nonce').val();
this.nextPage = ( theme_list_args.paged + 1 );
// Cache jQuery selectors
this.$outList = $('#availablethemes');
this.$spinner = $('div.tablenav.bottom').children( '.spinner' );
this.$window = $(window);
this.$document = $(document);
/**
* If there are more pages to query, then start polling to track
* when user hits the bottom of the current page
*/
if ( theme_list_args.total_pages >= this.nextPage )
this.pollInterval =
setInterval( function() {
return self.poll();
}, this.scrollPollingDelay );
},
/**
* Checks to see if user has scrolled to bottom of page.
* If so, requests another page of content from self.ajax().
*
* @since 3.4
* @access private
*/
poll: function() {
var bottom = this.$document.scrollTop() + this.$window.innerHeight();
if ( this.querying ||
( bottom < this.$outList.height() - this.outListBottomThreshold ) )
return;
this.ajax();
},
/**
* Applies results passed from this.ajax() to $outList
*
* @since 3.4
* @access private
*
* @param results Array with results from this.ajax() query.
*/
process: function( results ) {
if ( results === undefined ) {
clearInterval( this.pollInterval );
return;
}
if ( this.nextPage > theme_list_args.total_pages )
clearInterval( this.pollInterval );
if ( this.nextPage <= ( theme_list_args.total_pages + 1 ) )
this.$outList.append( results.rows );
},
/**
* Queries next page of themes
*
* @since 3.4
* @access private
*/
ajax: function() {
var self = this;
this.querying = true;
var query = {
action: 'fetch-list',
paged: this.nextPage,
s: theme_list_args.search,
tab: theme_list_args.tab,
type: theme_list_args.type,
_ajax_fetch_list_nonce: this.nonce,
'features[]': theme_list_args.features,
'list_args': list_args
};
this.$spinner.show();
$.getJSON( ajaxurl, query )
.done( function( response ) {
self.nextPage++;
self.process( response );
self.$spinner.hide();
self.querying = false;
})
.fail( function() {
self.$spinner.hide();
self.querying = false;
setTimeout( function() { self.ajax(); }, self.failedRetryDelay );
});
}
}
$(document).ready( function($) {
ThemeScroller.init();
});
})(jQuery);
| JavaScript |
(function($){
function check_pass_strength() {
var pass1 = $('#pass1').val(), user = $('#user_login').val(), pass2 = $('#pass2').val(), strength;
$('#pass-strength-result').removeClass('short bad good strong');
if ( ! pass1 ) {
$('#pass-strength-result').html( pwsL10n.empty );
return;
}
strength = passwordStrength(pass1, user, pass2);
switch ( strength ) {
case 2:
$('#pass-strength-result').addClass('bad').html( pwsL10n['bad'] );
break;
case 3:
$('#pass-strength-result').addClass('good').html( pwsL10n['good'] );
break;
case 4:
$('#pass-strength-result').addClass('strong').html( pwsL10n['strong'] );
break;
case 5:
$('#pass-strength-result').addClass('short').html( pwsL10n['mismatch'] );
break;
default:
$('#pass-strength-result').addClass('short').html( pwsL10n['short'] );
}
}
$(document).ready( function() {
var select = $('#display_name');
$('#pass1').val('').keyup( check_pass_strength );
$('#pass2').val('').keyup( check_pass_strength );
$('#pass-strength-result').show();
$('.color-palette').click( function() {
$(this).siblings('input[name="admin_color"]').prop('checked', true);
});
if ( select.length ) {
$('#first_name, #last_name, #nickname').bind( 'blur.user_profile', function() {
var dub = [],
inputs = {
display_nickname : $('#nickname').val() || '',
display_username : $('#user_login').val() || '',
display_firstname : $('#first_name').val() || '',
display_lastname : $('#last_name').val() || ''
};
if ( inputs.display_firstname && inputs.display_lastname ) {
inputs['display_firstlast'] = inputs.display_firstname + ' ' + inputs.display_lastname;
inputs['display_lastfirst'] = inputs.display_lastname + ' ' + inputs.display_firstname;
}
$.each( $('option', select), function( i, el ){
dub.push( el.value );
});
$.each(inputs, function( id, value ) {
if ( ! value )
return;
var val = value.replace(/<\/?[a-z][^>]*>/gi, '');
if ( inputs[id].length && $.inArray( val, dub ) == -1 ) {
dub.push(val);
$('<option />', {
'text': val
}).appendTo( select );
}
});
});
}
});
})(jQuery);
| JavaScript |
jQuery(document).ready(function($) {
var options = false, addAfter, delBefore, delAfter;
if ( document.forms['addcat'].category_parent )
options = document.forms['addcat'].category_parent.options;
addAfter = function( r, settings ) {
var name, id;
name = $("<span>" + $('name', r).text() + "</span>").text();
id = $('cat', r).attr('id');
options[options.length] = new Option(name, id);
}
delAfter = function( r, settings ) {
var id = $('cat', r).attr('id'), o;
for ( o = 0; o < options.length; o++ )
if ( id == options[o].value )
options[o] = null;
}
delBefore = function(s) {
if ( 'undefined' != showNotice )
return showNotice.warn() ? s : false;
return s;
}
if ( options )
$('#the-list').wpList( { addAfter: addAfter, delBefore: delBefore, delAfter: delAfter } );
else
$('#the-list').wpList({ delBefore: delBefore });
$('.delete a[class^="delete"]').live('click', function(){return false;});
});
| JavaScript |
jQuery(document).ready( function($) {
var newCat, noSyncChecks = false, syncChecks, catAddAfter;
$('#link_name').focus();
// postboxes
postboxes.add_postbox_toggles('link');
// category tabs
$('#category-tabs a').click(function(){
var t = $(this).attr('href');
$(this).parent().addClass('tabs').siblings('li').removeClass('tabs');
$('.tabs-panel').hide();
$(t).show();
if ( '#categories-all' == t )
deleteUserSetting('cats');
else
setUserSetting('cats','pop');
return false;
});
if ( getUserSetting('cats') )
$('#category-tabs a[href="#categories-pop"]').click();
// Ajax Cat
newCat = $('#newcat').one( 'focus', function() { $(this).val( '' ).removeClass( 'form-input-tip' ) } );
$('#link-category-add-submit').click( function() { newCat.focus(); } );
syncChecks = function() {
if ( noSyncChecks )
return;
noSyncChecks = true;
var th = $(this), c = th.is(':checked'), id = th.val().toString();
$('#in-link-category-' + id + ', #in-popular-category-' + id).prop( 'checked', c );
noSyncChecks = false;
};
catAddAfter = function( r, s ) {
$(s.what + ' response_data', r).each( function() {
var t = $($(this).text());
t.find( 'label' ).each( function() {
var th = $(this), val = th.find('input').val(), id = th.find('input')[0].id, name = $.trim( th.text() ), o;
$('#' + id).change( syncChecks );
o = $( '<option value="' + parseInt( val, 10 ) + '"></option>' ).text( name );
} );
} );
};
$('#categorychecklist').wpList( {
alt: '',
what: 'link-category',
response: 'category-ajax-response',
addAfter: catAddAfter
} );
$('a[href="#categories-all"]').click(function(){deleteUserSetting('cats');});
$('a[href="#categories-pop"]').click(function(){setUserSetting('cats','pop');});
if ( 'pop' == getUserSetting('cats') )
$('a[href="#categories-pop"]').click();
$('#category-add-toggle').click( function() {
$(this).parents('div:first').toggleClass( 'wp-hidden-children' );
$('#category-tabs a[href="#categories-all"]').click();
$('#newcategory').focus();
return false;
} );
$('.categorychecklist :checkbox').change( syncChecks ).filter( ':checked' ).change();
});
| JavaScript |
var theList, theExtraList, toggleWithKeyboard = false;
(function($) {
var getCount, updateCount, updatePending, dashboardTotals;
setCommentsList = function() {
var totalInput, perPageInput, pageInput, lastConfidentTime = 0, dimAfter, delBefore, updateTotalCount, delAfter, refillTheExtraList;
totalInput = $('input[name="_total"]', '#comments-form');
perPageInput = $('input[name="_per_page"]', '#comments-form');
pageInput = $('input[name="_page"]', '#comments-form');
dimAfter = function( r, settings ) {
var c = $('#' + settings.element), editRow, replyID, replyButton;
editRow = $('#replyrow');
replyID = $('#comment_ID', editRow).val();
replyButton = $('#replybtn', editRow);
if ( c.is('.unapproved') ) {
if ( settings.data.id == replyID )
replyButton.text(adminCommentsL10n.replyApprove);
c.find('div.comment_status').html('0');
} else {
if ( settings.data.id == replyID )
replyButton.text(adminCommentsL10n.reply);
c.find('div.comment_status').html('1');
}
var diff = $('#' + settings.element).is('.' + settings.dimClass) ? 1 : -1;
updatePending( diff );
};
// Send current total, page, per_page and url
delBefore = function( settings, list ) {
var wpListsData = $(settings.target).attr('data-wp-lists'), id, el, n, h, a, author, action = false;
settings.data._total = totalInput.val() || 0;
settings.data._per_page = perPageInput.val() || 0;
settings.data._page = pageInput.val() || 0;
settings.data._url = document.location.href;
settings.data.comment_status = $('input[name="comment_status"]', '#comments-form').val();
if ( wpListsData.indexOf(':trash=1') != -1 )
action = 'trash';
else if ( wpListsData.indexOf(':spam=1') != -1 )
action = 'spam';
if ( action ) {
id = wpListsData.replace(/.*?comment-([0-9]+).*/, '$1');
el = $('#comment-' + id);
note = $('#' + action + '-undo-holder').html();
el.find('.check-column :checkbox').prop('checked', false); // Uncheck the row so as not to be affected by Bulk Edits.
if ( el.siblings('#replyrow').length && commentReply.cid == id )
commentReply.close();
if ( el.is('tr') ) {
n = el.children(':visible').length;
author = $('.author strong', el).text();
h = $('<tr id="undo-' + id + '" class="undo un' + action + '" style="display:none;"><td colspan="' + n + '">' + note + '</td></tr>');
} else {
author = $('.comment-author', el).text();
h = $('<div id="undo-' + id + '" style="display:none;" class="undo un' + action + '">' + note + '</div>');
}
el.before(h);
$('strong', '#undo-' + id).text(author);
a = $('.undo a', '#undo-' + id);
a.attr('href', 'comment.php?action=un' + action + 'comment&c=' + id + '&_wpnonce=' + settings.data._ajax_nonce);
a.attr('data-wp-lists', 'delete:the-comment-list:comment-' + id + '::un' + action + '=1');
a.attr('class', 'vim-z vim-destructive');
$('.avatar', el).clone().prependTo('#undo-' + id + ' .' + action + '-undo-inside');
a.click(function(){
list.wpList.del(this);
$('#undo-' + id).css( {backgroundColor:'#ceb'} ).fadeOut(350, function(){
$(this).remove();
$('#comment-' + id).css('backgroundColor', '').fadeIn(300, function(){ $(this).show() });
});
return false;
});
}
return settings;
};
// Updates the current total (stored in the _total input)
updateTotalCount = function( total, time, setConfidentTime ) {
if ( time < lastConfidentTime )
return;
if ( setConfidentTime )
lastConfidentTime = time;
totalInput.val( total.toString() );
};
dashboardTotals = function(n) {
var dash = $('#dashboard_right_now'), total, appr, totalN, apprN;
n = n || 0;
if ( isNaN(n) || !dash.length )
return;
total = $('span.total-count', dash);
appr = $('span.approved-count', dash);
totalN = getCount(total);
totalN = totalN + n;
apprN = totalN - getCount( $('span.pending-count', dash) ) - getCount( $('span.spam-count', dash) );
updateCount(total, totalN);
updateCount(appr, apprN);
};
getCount = function(el) {
var n = parseInt( el.html().replace(/[^0-9]+/g, ''), 10 );
if ( isNaN(n) )
return 0;
return n;
};
updateCount = function(el, n) {
var n1 = '';
if ( isNaN(n) )
return;
n = n < 1 ? '0' : n.toString();
if ( n.length > 3 ) {
while ( n.length > 3 ) {
n1 = thousandsSeparator + n.substr(n.length - 3) + n1;
n = n.substr(0, n.length - 3);
}
n = n + n1;
}
el.html(n);
};
updatePending = function( diff ) {
$('span.pending-count').each(function() {
var a = $(this), n = getCount(a) + diff;
if ( n < 1 )
n = 0;
a.closest('.awaiting-mod')[ 0 == n ? 'addClass' : 'removeClass' ]('count-0');
updateCount( a, n );
});
dashboardTotals();
};
// In admin-ajax.php, we send back the unix time stamp instead of 1 on success
delAfter = function( r, settings ) {
var total, N, spam, trash, pending,
untrash = $(settings.target).parent().is('span.untrash'),
unspam = $(settings.target).parent().is('span.unspam'),
unapproved = $('#' + settings.element).is('.unapproved');
function getUpdate(s) {
if ( $(settings.target).parent().is('span.' + s) )
return 1;
else if ( $('#' + settings.element).is('.' + s) )
return -1;
return 0;
}
if ( untrash )
trash = -1;
else
trash = getUpdate('trash');
if ( unspam )
spam = -1;
else
spam = getUpdate('spam');
if ( $(settings.target).parent().is('span.unapprove') || ( ( untrash || unspam ) && unapproved ) ) {
// a comment was 'deleted' from another list (e.g. approved, spam, trash) and moved to pending,
// or a trash/spam of a pending comment was undone
pending = 1;
} else if ( unapproved ) {
// a pending comment was trashed/spammed/approved
pending = -1;
}
if ( pending )
updatePending(pending);
$('span.spam-count').each( function() {
var a = $(this), n = getCount(a) + spam;
updateCount(a, n);
});
$('span.trash-count').each( function() {
var a = $(this), n = getCount(a) + trash;
updateCount(a, n);
});
if ( $('#dashboard_right_now').length ) {
N = trash ? -1 * trash : 0;
dashboardTotals(N);
} else {
total = totalInput.val() ? parseInt( totalInput.val(), 10 ) : 0;
if ( $(settings.target).parent().is('span.undo') )
total++;
else
total--;
if ( total < 0 )
total = 0;
if ( ( 'object' == typeof r ) && lastConfidentTime < settings.parsed.responses[0].supplemental.time ) {
total_items_i18n = settings.parsed.responses[0].supplemental.total_items_i18n || '';
if ( total_items_i18n ) {
$('.displaying-num').text( total_items_i18n );
$('.total-pages').text( settings.parsed.responses[0].supplemental.total_pages_i18n );
$('.tablenav-pages').find('.next-page, .last-page').toggleClass('disabled', settings.parsed.responses[0].supplemental.total_pages == $('.current-page').val());
}
updateTotalCount( total, settings.parsed.responses[0].supplemental.time, true );
} else {
updateTotalCount( total, r, false );
}
}
if ( ! theExtraList || theExtraList.size() == 0 || theExtraList.children().size() == 0 || untrash || unspam ) {
return;
}
theList.get(0).wpList.add( theExtraList.children(':eq(0)').remove().clone() );
refillTheExtraList();
};
refillTheExtraList = function(ev) {
var args = $.query.get(), total_pages = $('.total-pages').text(), per_page = $('input[name="_per_page"]', '#comments-form').val();
if (! args.paged)
args.paged = 1;
if (args.paged > total_pages) {
return;
}
if (ev) {
theExtraList.empty();
args.number = Math.min(8, per_page); // see WP_Comments_List_Table::prepare_items() @ class-wp-comments-list-table.php
} else {
args.number = 1;
args.offset = Math.min(8, per_page) - 1; // fetch only the next item on the extra list
}
args.no_placeholder = true;
args.paged ++;
// $.query.get() needs some correction to be sent into an ajax request
if ( true === args.comment_type )
args.comment_type = '';
args = $.extend(args, {
'action': 'fetch-list',
'list_args': list_args,
'_ajax_fetch_list_nonce': $('#_ajax_fetch_list_nonce').val()
});
$.ajax({
url: ajaxurl,
global: false,
dataType: 'json',
data: args,
success: function(response) {
theExtraList.get(0).wpList.add( response.rows );
}
});
};
theExtraList = $('#the-extra-comment-list').wpList( { alt: '', delColor: 'none', addColor: 'none' } );
theList = $('#the-comment-list').wpList( { alt: '', delBefore: delBefore, dimAfter: dimAfter, delAfter: delAfter, addColor: 'none' } )
.bind('wpListDelEnd', function(e, s){
var wpListsData = $(s.target).attr('data-wp-lists'), id = s.element.replace(/[^0-9]+/g, '');
if ( wpListsData.indexOf(':trash=1') != -1 || wpListsData.indexOf(':spam=1') != -1 )
$('#undo-' + id).fadeIn(300, function(){ $(this).show() });
});
};
commentReply = {
cid : '',
act : '',
init : function() {
var row = $('#replyrow');
$('a.cancel', row).click(function() { return commentReply.revert(); });
$('a.save', row).click(function() { return commentReply.send(); });
$('input#author, input#author-email, input#author-url', row).keypress(function(e){
if ( e.which == 13 ) {
commentReply.send();
e.preventDefault();
return false;
}
});
// add events
$('#the-comment-list .column-comment > p').dblclick(function(){
commentReply.toggle($(this).parent());
});
$('#doaction, #doaction2, #post-query-submit').click(function(e){
if ( $('#the-comment-list #replyrow').length > 0 )
commentReply.close();
});
this.comments_listing = $('#comments-form > input[name="comment_status"]').val() || '';
/* $(listTable).bind('beforeChangePage', function(){
commentReply.close();
}); */
},
addEvents : function(r) {
r.each(function() {
$(this).find('.column-comment > p').dblclick(function(){
commentReply.toggle($(this).parent());
});
});
},
toggle : function(el) {
if ( $(el).css('display') != 'none' )
$(el).find('a.vim-q').click();
},
revert : function() {
if ( $('#the-comment-list #replyrow').length < 1 )
return false;
$('#replyrow').fadeOut('fast', function(){
commentReply.close();
});
return false;
},
close : function() {
var c, replyrow = $('#replyrow');
// replyrow is not showing?
if ( replyrow.parent().is('#com-reply') )
return;
if ( this.cid && this.act == 'edit-comment' ) {
c = $('#comment-' + this.cid);
c.fadeIn(300, function(){ c.show() }).css('backgroundColor', '');
}
// reset the Quicktags buttons
if ( typeof QTags != 'undefined' )
QTags.closeAllTags('replycontent');
$('#add-new-comment').css('display', '');
replyrow.hide();
$('#com-reply').append( replyrow );
$('#replycontent').css('height', '').val('');
$('#edithead input').val('');
$('.error', replyrow).html('').hide();
$('.spinner', replyrow).hide();
this.cid = '';
},
open : function(comment_id, post_id, action) {
var t = this, editRow, rowData, act, c = $('#comment-' + comment_id), h = c.height(), replyButton;
t.close();
t.cid = comment_id;
editRow = $('#replyrow');
rowData = $('#inline-'+comment_id);
action = action || 'replyto';
act = 'edit' == action ? 'edit' : 'replyto';
act = t.act = act + '-comment';
$('#action', editRow).val(act);
$('#comment_post_ID', editRow).val(post_id);
$('#comment_ID', editRow).val(comment_id);
if ( h > 120 )
$('#replycontent', editRow).css('height', (35+h) + 'px');
if ( action == 'edit' ) {
$('#author', editRow).val( $('div.author', rowData).text() );
$('#author-email', editRow).val( $('div.author-email', rowData).text() );
$('#author-url', editRow).val( $('div.author-url', rowData).text() );
$('#status', editRow).val( $('div.comment_status', rowData).text() );
$('#replycontent', editRow).val( $('textarea.comment', rowData).val() );
$('#edithead, #savebtn', editRow).show();
$('#replyhead, #replybtn, #addhead, #addbtn', editRow).hide();
c.after( editRow ).fadeOut('fast', function(){
$('#replyrow').fadeIn(300, function(){ $(this).show() });
});
} else if ( action == 'add' ) {
$('#addhead, #addbtn', editRow).show();
$('#replyhead, #replybtn, #edithead, #editbtn', editRow).hide();
$('#the-comment-list').prepend(editRow);
$('#replyrow').fadeIn(300);
} else {
replyButton = $('#replybtn', editRow);
$('#edithead, #savebtn, #addhead, #addbtn', editRow).hide();
$('#replyhead, #replybtn', editRow).show();
c.after(editRow);
if ( c.hasClass('unapproved') ) {
replyButton.text(adminCommentsL10n.replyApprove);
} else {
replyButton.text(adminCommentsL10n.reply);
}
$('#replyrow').fadeIn(300, function(){ $(this).show() });
}
setTimeout(function() {
var rtop, rbottom, scrollTop, vp, scrollBottom;
rtop = $('#replyrow').offset().top;
rbottom = rtop + $('#replyrow').height();
scrollTop = window.pageYOffset || document.documentElement.scrollTop;
vp = document.documentElement.clientHeight || self.innerHeight || 0;
scrollBottom = scrollTop + vp;
if ( scrollBottom - 20 < rbottom )
window.scroll(0, rbottom - vp + 35);
else if ( rtop - 20 < scrollTop )
window.scroll(0, rtop - 35);
$('#replycontent').focus().keyup(function(e){
if ( e.which == 27 )
commentReply.revert(); // close on Escape
});
}, 600);
return false;
},
send : function() {
var post = {};
$('#replysubmit .error').hide();
$('#replysubmit .spinner').show();
$('#replyrow input').not(':button').each(function() {
var t = $(this);
post[ t.attr('name') ] = t.val();
});
post.content = $('#replycontent').val();
post.id = post.comment_post_ID;
post.comments_listing = this.comments_listing;
post.p = $('[name="p"]').val();
if ( $('#comment-' + $('#comment_ID').val()).hasClass('unapproved') )
post.approve_parent = 1;
$.ajax({
type : 'POST',
url : ajaxurl,
data : post,
success : function(x) { commentReply.show(x); },
error : function(r) { commentReply.error(r); }
});
return false;
},
show : function(xml) {
var t = this, r, c, id, bg, pid;
if ( typeof(xml) == 'string' ) {
t.error({'responseText': xml});
return false;
}
r = wpAjax.parseAjaxResponse(xml);
if ( r.errors ) {
t.error({'responseText': wpAjax.broken});
return false;
}
t.revert();
r = r.responses[0];
c = r.data;
id = '#comment-' + r.id;
if ( 'edit-comment' == t.act )
$(id).remove();
if ( r.supplemental.parent_approved ) {
pid = $('#comment-' + r.supplemental.parent_approved);
updatePending( -1 );
if ( this.comments_listing == 'moderated' ) {
pid.animate( { 'backgroundColor':'#CCEEBB' }, 400, function(){
pid.fadeOut();
});
return;
}
}
$(c).hide()
$('#replyrow').after(c);
id = $(id);
t.addEvents(id);
bg = id.hasClass('unapproved') ? '#FFFFE0' : id.closest('.widefat, .postbox').css('backgroundColor');
id.animate( { 'backgroundColor':'#CCEEBB' }, 300 )
.animate( { 'backgroundColor': bg }, 300, function() {
if ( pid && pid.length ) {
pid.animate( { 'backgroundColor':'#CCEEBB' }, 300 )
.animate( { 'backgroundColor': bg }, 300 )
.removeClass('unapproved').addClass('approved')
.find('div.comment_status').html('1');
}
});
},
error : function(r) {
var er = r.statusText;
$('#replysubmit .spinner').hide();
if ( r.responseText )
er = r.responseText.replace( /<.[^<>]*?>/g, '' );
if ( er )
$('#replysubmit .error').html(er).show();
},
addcomment: function(post_id) {
var t = this;
$('#add-new-comment').fadeOut(200, function(){
t.open(0, post_id, 'add');
$('table.comments-box').css('display', '');
$('#no-comments').remove();
});
}
};
$(document).ready(function(){
var make_hotkeys_redirect, edit_comment, toggle_all, make_bulk;
setCommentsList();
commentReply.init();
$(document).delegate('span.delete a.delete', 'click', function(){return false;});
if ( typeof $.table_hotkeys != 'undefined' ) {
make_hotkeys_redirect = function(which) {
return function() {
var first_last, l;
first_last = 'next' == which? 'first' : 'last';
l = $('.tablenav-pages .'+which+'-page:not(.disabled)');
if (l.length)
window.location = l[0].href.replace(/\&hotkeys_highlight_(first|last)=1/g, '')+'&hotkeys_highlight_'+first_last+'=1';
}
};
edit_comment = function(event, current_row) {
window.location = $('span.edit a', current_row).attr('href');
};
toggle_all = function() {
toggleWithKeyboard = true;
$('input:checkbox', '#cb').click().prop('checked', false);
toggleWithKeyboard = false;
};
make_bulk = function(value) {
return function() {
var scope = $('select[name="action"]');
$('option[value="' + value + '"]', scope).prop('selected', true);
$('#doaction').click();
}
};
$.table_hotkeys(
$('table.widefat'),
['a', 'u', 's', 'd', 'r', 'q', 'z', ['e', edit_comment], ['shift+x', toggle_all],
['shift+a', make_bulk('approve')], ['shift+s', make_bulk('spam')],
['shift+d', make_bulk('delete')], ['shift+t', make_bulk('trash')],
['shift+z', make_bulk('untrash')], ['shift+u', make_bulk('unapprove')]],
{ highlight_first: adminCommentsL10n.hotkeys_highlight_first, highlight_last: adminCommentsL10n.hotkeys_highlight_last,
prev_page_link_cb: make_hotkeys_redirect('prev'), next_page_link_cb: make_hotkeys_redirect('next') }
);
}
});
})(jQuery);
| JavaScript |
var autosave, autosaveLast = '', autosavePeriodical, autosaveOldMessage = '', autosaveDelayPreview = false, notSaved = true, blockSave = false, fullscreen, autosaveLockRelease = true;
jQuery(document).ready( function($) {
autosaveLast = ( $('#post #title').val() || '' ) + ( $('#post #content').val() || '' );
autosavePeriodical = $.schedule({time: autosaveL10n.autosaveInterval * 1000, func: function() { autosave(); }, repeat: true, protect: true});
//Disable autosave after the form has been submitted
$("#post").submit(function() {
$.cancel(autosavePeriodical);
autosaveLockRelease = false;
});
$('input[type="submit"], a.submitdelete', '#submitpost').click(function(){
blockSave = true;
window.onbeforeunload = null;
$(':button, :submit', '#submitpost').each(function(){
var t = $(this);
if ( t.hasClass('button-primary') )
t.addClass('button-primary-disabled');
else
t.addClass('button-disabled');
});
if ( $(this).attr('id') == 'publish' )
$('#major-publishing-actions .spinner').show();
else
$('#minor-publishing .spinner').show();
});
window.onbeforeunload = function(){
var mce = typeof(tinymce) != 'undefined' ? tinymce.activeEditor : false, title, content;
if ( mce && !mce.isHidden() ) {
if ( mce.isDirty() )
return autosaveL10n.saveAlert;
} else {
if ( fullscreen && fullscreen.settings.visible ) {
title = $('#wp-fullscreen-title').val() || '';
content = $("#wp_mce_fullscreen").val() || '';
} else {
title = $('#post #title').val() || '';
content = $('#post #content').val() || '';
}
if ( ( title || content ) && title + content != autosaveLast )
return autosaveL10n.saveAlert;
}
};
$(window).unload( function(e) {
if ( ! autosaveLockRelease )
return;
// unload fires (twice) on removing the Thickbox iframe. Make sure we process only the main document unload.
if ( e.target && e.target.nodeName != '#document' )
return;
$.ajax({
type: 'POST',
url: ajaxurl,
async: false,
data: {
action: 'wp-remove-post-lock',
_wpnonce: $('#_wpnonce').val(),
post_ID: $('#post_ID').val(),
active_post_lock: $('#active_post_lock').val()
}
});
} );
// preview
$('#post-preview').click(function(){
if ( $('#auto_draft').val() == '1' && notSaved ) {
autosaveDelayPreview = true;
autosave();
return false;
}
doPreview();
return false;
});
doPreview = function() {
$('input#wp-preview').val('dopreview');
$('form#post').attr('target', 'wp-preview').submit().attr('target', '');
/*
* Workaround for WebKit bug preventing a form submitting twice to the same action.
* https://bugs.webkit.org/show_bug.cgi?id=28633
*/
if ( $.browser.safari ) {
$('form#post').attr('action', function(index, value) {
return value + '?t=' + new Date().getTime();
});
}
$('input#wp-preview').val('');
}
// This code is meant to allow tabbing from Title to Post content.
$('#title').on('keydown.editor-focus', function(e) {
var ed;
if ( e.which != 9 )
return;
if ( !e.ctrlKey && !e.altKey && !e.shiftKey ) {
if ( typeof(tinymce) != 'undefined' )
ed = tinymce.get('content');
if ( ed && !ed.isHidden() ) {
$(this).one('keyup', function(e){
$('#content_tbl td.mceToolbar > a').focus();
});
} else {
$('#content').focus();
}
e.preventDefault();
}
});
// autosave new posts after a title is typed but not if Publish or Save Draft is clicked
if ( '1' == $('#auto_draft').val() ) {
$('#title').blur( function() {
if ( !this.value || $('#auto_draft').val() != '1' )
return;
delayed_autosave();
});
}
});
function autosave_parse_response(response) {
var res = wpAjax.parseAjaxResponse(response, 'autosave'), message = '', postID, sup;
if ( res && res.responses && res.responses.length ) {
message = res.responses[0].data; // The saved message or error.
// someone else is editing: disable autosave, set errors
if ( res.responses[0].supplemental ) {
sup = res.responses[0].supplemental;
if ( 'disable' == sup['disable_autosave'] ) {
autosave = function() {};
autosaveLockRelease = false;
res = { errors: true };
}
if ( sup['active-post-lock'] ) {
jQuery('#active_post_lock').val( sup['active-post-lock'] );
}
if ( sup['alert'] ) {
jQuery('#autosave-alert').remove();
jQuery('#titlediv').after('<div id="autosave-alert" class="error below-h2"><p>' + sup['alert'] + '</p></div>');
}
jQuery.each(sup, function(selector, value) {
if ( selector.match(/^replace-/) ) {
jQuery('#'+selector.replace('replace-', '')).val(value);
}
});
}
// if no errors: add slug UI
if ( !res.errors ) {
postID = parseInt( res.responses[0].id, 10 );
if ( !isNaN(postID) && postID > 0 ) {
autosave_update_slug(postID);
}
}
}
if ( message ) { // update autosave message
jQuery('.autosave-message').html(message);
} else if ( autosaveOldMessage && res ) {
jQuery('.autosave-message').html( autosaveOldMessage );
}
return res;
}
// called when autosaving pre-existing post
function autosave_saved(response) {
blockSave = false;
autosave_parse_response(response); // parse the ajax response
autosave_enable_buttons(); // re-enable disabled form buttons
}
// called when autosaving new post
function autosave_saved_new(response) {
blockSave = false;
var res = autosave_parse_response(response), postID;
if ( res && res.responses.length && !res.errors ) {
// An ID is sent only for real auto-saves, not for autosave=0 "keepalive" saves
postID = parseInt( res.responses[0].id, 10 );
if ( !isNaN(postID) && postID > 0 ) {
notSaved = false;
jQuery('#auto_draft').val('0'); // No longer an auto-draft
}
autosave_enable_buttons();
if ( autosaveDelayPreview ) {
autosaveDelayPreview = false;
doPreview();
}
} else {
autosave_enable_buttons(); // re-enable disabled form buttons
}
}
function autosave_update_slug(post_id) {
// create slug area only if not already there
if ( 'undefined' != makeSlugeditClickable && jQuery.isFunction(makeSlugeditClickable) && !jQuery('#edit-slug-box > *').size() ) {
jQuery.post( ajaxurl, {
action: 'sample-permalink',
post_id: post_id,
new_title: fullscreen && fullscreen.settings.visible ? jQuery('#wp-fullscreen-title').val() : jQuery('#title').val(),
samplepermalinknonce: jQuery('#samplepermalinknonce').val()
},
function(data) {
if ( data !== '-1' ) {
jQuery('#edit-slug-box').html(data);
makeSlugeditClickable();
}
}
);
}
}
function autosave_loading() {
jQuery('.autosave-message').html(autosaveL10n.savingText);
}
function autosave_enable_buttons() {
// delay that a bit to avoid some rare collisions while the DOM is being updated.
setTimeout(function(){
jQuery(':button, :submit', '#submitpost').removeAttr('disabled');
jQuery('.spinner', '#submitpost').hide();
}, 500);
}
function autosave_disable_buttons() {
jQuery(':button, :submit', '#submitpost').prop('disabled', true);
// Re-enable 5 sec later. Just gives autosave a head start to avoid collisions.
setTimeout(autosave_enable_buttons, 5000);
}
function delayed_autosave() {
setTimeout(function(){
if ( blockSave )
return;
autosave();
}, 200);
}
autosave = function() {
// (bool) is rich editor enabled and active
blockSave = true;
var rich = (typeof tinymce != "undefined") && tinymce.activeEditor && !tinymce.activeEditor.isHidden(),
post_data, doAutoSave, ed, origStatus, successCallback;
autosave_disable_buttons();
post_data = {
action: "autosave",
post_ID: jQuery("#post_ID").val() || 0,
autosavenonce: jQuery('#autosavenonce').val(),
post_type: jQuery('#post_type').val() || "",
autosave: 1
};
jQuery('.tags-input').each( function() {
post_data[this.name] = this.value;
} );
// We always send the ajax request in order to keep the post lock fresh.
// This (bool) tells whether or not to write the post to the DB during the ajax request.
doAutoSave = true;
// No autosave while thickbox is open (media buttons)
if ( jQuery("#TB_window").css('display') == 'block' )
doAutoSave = false;
/* Gotta do this up here so we can check the length when tinymce is in use */
if ( rich && doAutoSave ) {
ed = tinymce.activeEditor;
// Don't run while the tinymce spellcheck is on. It resets all found words.
if ( ed.plugins.spellchecker && ed.plugins.spellchecker.active ) {
doAutoSave = false;
} else {
if ( 'mce_fullscreen' == ed.id || 'wp_mce_fullscreen' == ed.id )
tinymce.get('content').setContent(ed.getContent({format : 'raw'}), {format : 'raw'});
tinymce.triggerSave();
}
}
if ( fullscreen && fullscreen.settings.visible ) {
post_data["post_title"] = jQuery('#wp-fullscreen-title').val() || '';
post_data["content"] = jQuery("#wp_mce_fullscreen").val() || '';
} else {
post_data["post_title"] = jQuery("#title").val() || '';
post_data["content"] = jQuery("#content").val() || '';
}
if ( jQuery('#post_name').val() )
post_data["post_name"] = jQuery('#post_name').val();
// Nothing to save or no change.
if ( ( post_data["post_title"].length == 0 && post_data["content"].length == 0 ) || post_data["post_title"] + post_data["content"] == autosaveLast ) {
doAutoSave = false;
}
origStatus = jQuery('#original_post_status').val();
goodcats = ([]);
jQuery("[name='post_category[]']:checked").each( function(i) {
goodcats.push(this.value);
} );
post_data["catslist"] = goodcats.join(",");
if ( jQuery("#comment_status").prop("checked") )
post_data["comment_status"] = 'open';
if ( jQuery("#ping_status").prop("checked") )
post_data["ping_status"] = 'open';
if ( jQuery("#excerpt").size() )
post_data["excerpt"] = jQuery("#excerpt").val();
if ( jQuery("#post_author").size() )
post_data["post_author"] = jQuery("#post_author").val();
if ( jQuery("#parent_id").val() )
post_data["parent_id"] = jQuery("#parent_id").val();
post_data["user_ID"] = jQuery("#user-id").val();
if ( jQuery('#auto_draft').val() == '1' )
post_data["auto_draft"] = '1';
if ( doAutoSave ) {
autosaveLast = post_data["post_title"] + post_data["content"];
jQuery(document).triggerHandler('wpcountwords', [ post_data["content"] ]);
} else {
post_data['autosave'] = 0;
}
if ( post_data["auto_draft"] == '1' ) {
successCallback = autosave_saved_new; // new post
} else {
successCallback = autosave_saved; // pre-existing post
}
autosaveOldMessage = jQuery('#autosave').html();
jQuery.ajax({
data: post_data,
beforeSend: doAutoSave ? autosave_loading : null,
type: "POST",
url: ajaxurl,
success: successCallback
});
}
| JavaScript |
var topWin = window.dialogArguments || opener || parent || top, uploader, uploader_init;
function fileDialogStart() {
jQuery("#media-upload-error").empty();
}
// progress and success handlers for media multi uploads
function fileQueued(fileObj) {
// Get rid of unused form
jQuery('.media-blank').remove();
var items = jQuery('#media-items').children(), postid = post_id || 0;
// Collapse a single item
if ( items.length == 1 ) {
items.removeClass('open').find('.slidetoggle').slideUp(200);
}
// Create a progress bar containing the filename
jQuery('#media-items').append('<div id="media-item-' + fileObj.id + '" class="media-item child-of-' + postid + '"><div class="progress"><div class="percent">0%</div><div class="bar"></div></div><div class="filename original"> ' + fileObj.name + '</div></div>');
// Disable submit
jQuery('#insert-gallery').prop('disabled', true);
}
function uploadStart() {
try {
if ( typeof topWin.tb_remove != 'undefined' )
topWin.jQuery('#TB_overlay').unbind('click', topWin.tb_remove);
} catch(e){}
return true;
}
function uploadProgress(up, file) {
var item = jQuery('#media-item-' + file.id);
jQuery('.bar', item).width( (200 * file.loaded) / file.size );
jQuery('.percent', item).html( file.percent + '%' );
}
// check to see if a large file failed to upload
function fileUploading(up, file) {
var hundredmb = 100 * 1024 * 1024, max = parseInt(up.settings.max_file_size, 10);
if ( max > hundredmb && file.size > hundredmb ) {
setTimeout(function(){
var done;
if ( file.status < 3 && file.loaded == 0 ) { // not uploading
wpFileError(file, pluploadL10n.big_upload_failed.replace('%1$s', '<a class="uploader-html" href="#">').replace('%2$s', '</a>'));
up.stop(); // stops the whole queue
up.removeFile(file);
up.start(); // restart the queue
}
}, 10000); // wait for 10 sec. for the file to start uploading
}
}
function updateMediaForm() {
var items = jQuery('#media-items').children();
// Just one file, no need for collapsible part
if ( items.length == 1 ) {
items.addClass('open').find('.slidetoggle').show();
jQuery('.insert-gallery').hide();
} else if ( items.length > 1 ) {
items.removeClass('open');
// Only show Gallery button when there are at least two files.
jQuery('.insert-gallery').show();
}
// Only show Save buttons when there is at least one file.
if ( items.not('.media-blank').length > 0 )
jQuery('.savebutton').show();
else
jQuery('.savebutton').hide();
}
function uploadSuccess(fileObj, serverData) {
var item = jQuery('#media-item-' + fileObj.id);
// on success serverData should be numeric, fix bug in html4 runtime returning the serverData wrapped in a <pre> tag
serverData = serverData.replace(/^<pre>(\d+)<\/pre>$/, '$1');
// if async-upload returned an error message, place it in the media item div and return
if ( serverData.match(/media-upload-error|error-div/) ) {
item.html(serverData);
return;
} else {
jQuery('.percent', item).html( pluploadL10n.crunching );
}
prepareMediaItem(fileObj, serverData);
updateMediaForm();
// Increment the counter.
if ( post_id && item.hasClass('child-of-' + post_id) )
jQuery('#attachments-count').text(1 * jQuery('#attachments-count').text() + 1);
}
function setResize(arg) {
if ( arg ) {
if ( uploader.features.jpgresize )
uploader.settings['resize'] = { width: resize_width, height: resize_height, quality: 100 };
else
uploader.settings.multipart_params.image_resize = true;
} else {
delete(uploader.settings.resize);
delete(uploader.settings.multipart_params.image_resize);
}
}
function prepareMediaItem(fileObj, serverData) {
var f = ( typeof shortform == 'undefined' ) ? 1 : 2, item = jQuery('#media-item-' + fileObj.id);
if ( f == 2 && shortform > 2 )
f = shortform;
try {
if ( typeof topWin.tb_remove != 'undefined' )
topWin.jQuery('#TB_overlay').click(topWin.tb_remove);
} catch(e){}
if ( isNaN(serverData) || !serverData ) { // Old style: Append the HTML returned by the server -- thumbnail and form inputs
item.append(serverData);
prepareMediaItemInit(fileObj);
} else { // New style: server data is just the attachment ID, fetch the thumbnail and form html from the server
item.load('async-upload.php', {attachment_id:serverData, fetch:f}, function(){prepareMediaItemInit(fileObj);updateMediaForm()});
}
}
function prepareMediaItemInit(fileObj) {
var item = jQuery('#media-item-' + fileObj.id);
// Clone the thumbnail as a "pinkynail" -- a tiny image to the left of the filename
jQuery('.thumbnail', item).clone().attr('class', 'pinkynail toggle').prependTo(item);
// Replace the original filename with the new (unique) one assigned during upload
jQuery('.filename.original', item).replaceWith( jQuery('.filename.new', item) );
// Bind AJAX to the new Delete button
jQuery('a.delete', item).click(function(){
// Tell the server to delete it. TODO: handle exceptions
jQuery.ajax({
url: ajaxurl,
type: 'post',
success: deleteSuccess,
error: deleteError,
id: fileObj.id,
data: {
id : this.id.replace(/[^0-9]/g, ''),
action : 'trash-post',
_ajax_nonce : this.href.replace(/^.*wpnonce=/,'')
}
});
return false;
});
// Bind AJAX to the new Undo button
jQuery('a.undo', item).click(function(){
// Tell the server to untrash it. TODO: handle exceptions
jQuery.ajax({
url: ajaxurl,
type: 'post',
id: fileObj.id,
data: {
id : this.id.replace(/[^0-9]/g,''),
action: 'untrash-post',
_ajax_nonce: this.href.replace(/^.*wpnonce=/,'')
},
success: function(data, textStatus){
var item = jQuery('#media-item-' + fileObj.id);
if ( type = jQuery('#type-of-' + fileObj.id).val() )
jQuery('#' + type + '-counter').text(jQuery('#' + type + '-counter').text()-0+1);
if ( post_id && item.hasClass('child-of-'+post_id) )
jQuery('#attachments-count').text(jQuery('#attachments-count').text()-0+1);
jQuery('.filename .trashnotice', item).remove();
jQuery('.filename .title', item).css('font-weight','normal');
jQuery('a.undo', item).addClass('hidden');
jQuery('.menu_order_input', item).show();
item.css( {backgroundColor:'#ceb'} ).animate( {backgroundColor: '#fff'}, { queue: false, duration: 500, complete: function(){ jQuery(this).css({backgroundColor:''}); } }).removeClass('undo');
}
});
return false;
});
// Open this item if it says to start open (e.g. to display an error)
jQuery('#media-item-' + fileObj.id + '.startopen').removeClass('startopen').addClass('open').find('slidetoggle').fadeIn();
}
// generic error message
function wpQueueError(message) {
jQuery('#media-upload-error').show().html( '<div class="error"><p>' + message + '</p></div>' );
}
// file-specific error messages
function wpFileError(fileObj, message) {
itemAjaxError(fileObj.id, message);
}
function itemAjaxError(id, message) {
var item = jQuery('#media-item-' + id), filename = item.find('.filename').text(), last_err = item.data('last-err');
if ( last_err == id ) // prevent firing an error for the same file twice
return;
item.html('<div class="error-div">'
+ '<a class="dismiss" href="#">' + pluploadL10n.dismiss + '</a>'
+ '<strong>' + pluploadL10n.error_uploading.replace('%s', jQuery.trim(filename)) + '</strong> '
+ message
+ '</div>').data('last-err', id);
}
function deleteSuccess(data, textStatus) {
if ( data == '-1' )
return itemAjaxError(this.id, 'You do not have permission. Has your session expired?');
if ( data == '0' )
return itemAjaxError(this.id, 'Could not be deleted. Has it been deleted already?');
var id = this.id, item = jQuery('#media-item-' + id);
// Decrement the counters.
if ( type = jQuery('#type-of-' + id).val() )
jQuery('#' + type + '-counter').text( jQuery('#' + type + '-counter').text() - 1 );
if ( post_id && item.hasClass('child-of-'+post_id) )
jQuery('#attachments-count').text( jQuery('#attachments-count').text() - 1 );
if ( jQuery('form.type-form #media-items').children().length == 1 && jQuery('.hidden', '#media-items').length > 0 ) {
jQuery('.toggle').toggle();
jQuery('.slidetoggle').slideUp(200).siblings().removeClass('hidden');
}
// Vanish it.
jQuery('.toggle', item).toggle();
jQuery('.slidetoggle', item).slideUp(200).siblings().removeClass('hidden');
item.css( {backgroundColor:'#faa'} ).animate( {backgroundColor:'#f4f4f4'}, {queue:false, duration:500} ).addClass('undo');
jQuery('.filename:empty', item).remove();
jQuery('.filename .title', item).css('font-weight','bold');
jQuery('.filename', item).append('<span class="trashnotice"> ' + pluploadL10n.deleted + ' </span>').siblings('a.toggle').hide();
jQuery('.filename', item).append( jQuery('a.undo', item).removeClass('hidden') );
jQuery('.menu_order_input', item).hide();
return;
}
function deleteError(X, textStatus, errorThrown) {
// TODO
}
function uploadComplete() {
jQuery('#insert-gallery').prop('disabled', false);
}
function switchUploader(s) {
if ( s ) {
deleteUserSetting('uploader');
jQuery('.media-upload-form').removeClass('html-uploader');
if ( typeof(uploader) == 'object' )
uploader.refresh();
} else {
setUserSetting('uploader', '1'); // 1 == html uploader
jQuery('.media-upload-form').addClass('html-uploader');
}
}
function dndHelper(s) {
var d = document.getElementById('dnd-helper');
if ( s ) {
d.style.display = 'block';
} else {
d.style.display = 'none';
}
}
function uploadError(fileObj, errorCode, message, uploader) {
var hundredmb = 100 * 1024 * 1024, max;
switch (errorCode) {
case plupload.FAILED:
wpFileError(fileObj, pluploadL10n.upload_failed);
break;
case plupload.FILE_EXTENSION_ERROR:
wpFileError(fileObj, pluploadL10n.invalid_filetype);
break;
case plupload.FILE_SIZE_ERROR:
uploadSizeError(uploader, fileObj);
break;
case plupload.IMAGE_FORMAT_ERROR:
wpFileError(fileObj, pluploadL10n.not_an_image);
break;
case plupload.IMAGE_MEMORY_ERROR:
wpFileError(fileObj, pluploadL10n.image_memory_exceeded);
break;
case plupload.IMAGE_DIMENSIONS_ERROR:
wpFileError(fileObj, pluploadL10n.image_dimensions_exceeded);
break;
case plupload.GENERIC_ERROR:
wpQueueError(pluploadL10n.upload_failed);
break;
case plupload.IO_ERROR:
max = parseInt(uploader.settings.max_file_size, 10);
if ( max > hundredmb && fileObj.size > hundredmb )
wpFileError(fileObj, pluploadL10n.big_upload_failed.replace('%1$s', '<a class="uploader-html" href="#">').replace('%2$s', '</a>'));
else
wpQueueError(pluploadL10n.io_error);
break;
case plupload.HTTP_ERROR:
wpQueueError(pluploadL10n.http_error);
break;
case plupload.INIT_ERROR:
jQuery('.media-upload-form').addClass('html-uploader');
break;
case plupload.SECURITY_ERROR:
wpQueueError(pluploadL10n.security_error);
break;
/* case plupload.UPLOAD_ERROR.UPLOAD_STOPPED:
case plupload.UPLOAD_ERROR.FILE_CANCELLED:
jQuery('#media-item-' + fileObj.id).remove();
break;*/
default:
wpFileError(fileObj, pluploadL10n.default_error);
}
}
function uploadSizeError( up, file, over100mb ) {
var message;
if ( over100mb )
message = pluploadL10n.big_upload_queued.replace('%s', file.name) + ' ' + pluploadL10n.big_upload_failed.replace('%1$s', '<a class="uploader-html" href="#">').replace('%2$s', '</a>');
else
message = pluploadL10n.file_exceeds_size_limit.replace('%s', file.name);
jQuery('#media-items').append('<div id="media-item-' + file.id + '" class="media-item error"><p>' + message + '</p></div>');
up.removeFile(file);
}
jQuery(document).ready(function($){
$('.media-upload-form').bind('click.uploader', function(e) {
var target = $(e.target), tr, c;
if ( target.is('input[type="radio"]') ) { // remember the last used image size and alignment
tr = target.closest('tr');
if ( tr.hasClass('align') )
setUserSetting('align', target.val());
else if ( tr.hasClass('image-size') )
setUserSetting('imgsize', target.val());
} else if ( target.is('button.button') ) { // remember the last used image link url
c = e.target.className || '';
c = c.match(/url([^ '"]+)/);
if ( c && c[1] ) {
setUserSetting('urlbutton', c[1]);
target.siblings('.urlfield').val( target.data('link-url') );
}
} else if ( target.is('a.dismiss') ) {
target.parents('.media-item').fadeOut(200, function(){
$(this).remove();
});
} else if ( target.is('.upload-flash-bypass a') || target.is('a.uploader-html') ) { // switch uploader to html4
$('#media-items, p.submit, span.big-file-warning').css('display', 'none');
switchUploader(0);
e.preventDefault();
} else if ( target.is('.upload-html-bypass a') ) { // switch uploader to multi-file
$('#media-items, p.submit, span.big-file-warning').css('display', '');
switchUploader(1);
e.preventDefault();
} else if ( target.is('a.describe-toggle-on') ) { // Show
target.parent().addClass('open');
target.siblings('.slidetoggle').fadeIn(250, function(){
var S = $(window).scrollTop(), H = $(window).height(), top = $(this).offset().top, h = $(this).height(), b, B;
if ( H && top && h ) {
b = top + h;
B = S + H;
if ( b > B ) {
if ( b - B < top - S )
window.scrollBy(0, (b - B) + 10);
else
window.scrollBy(0, top - S - 40);
}
}
});
e.preventDefault();
} else if ( target.is('a.describe-toggle-off') ) { // Hide
target.siblings('.slidetoggle').fadeOut(250, function(){
target.parent().removeClass('open');
});
e.preventDefault();
}
});
// init and set the uploader
uploader_init = function() {
uploader = new plupload.Uploader(wpUploaderInit);
$('#image_resize').bind('change', function() {
var arg = $(this).prop('checked');
setResize( arg );
if ( arg )
setUserSetting('upload_resize', '1');
else
deleteUserSetting('upload_resize');
});
uploader.bind('Init', function(up) {
var uploaddiv = $('#plupload-upload-ui');
setResize( getUserSetting('upload_resize', false) );
if ( up.features.dragdrop && ! $(document.body).hasClass('mobile') ) {
uploaddiv.addClass('drag-drop');
$('#drag-drop-area').bind('dragover.wp-uploader', function(){ // dragenter doesn't fire right :(
uploaddiv.addClass('drag-over');
}).bind('dragleave.wp-uploader, drop.wp-uploader', function(){
uploaddiv.removeClass('drag-over');
});
} else {
uploaddiv.removeClass('drag-drop');
$('#drag-drop-area').unbind('.wp-uploader');
}
if ( up.runtime == 'html4' )
$('.upload-flash-bypass').hide();
});
uploader.init();
uploader.bind('FilesAdded', function(up, files) {
var hundredmb = 100 * 1024 * 1024, max = parseInt(up.settings.max_file_size, 10);
$('#media-upload-error').html('');
uploadStart();
plupload.each(files, function(file){
if ( max > hundredmb && file.size > hundredmb && up.runtime != 'html5' )
uploadSizeError( up, file, true );
else
fileQueued(file);
});
up.refresh();
up.start();
});
uploader.bind('BeforeUpload', function(up, file) {
// something
});
uploader.bind('UploadFile', function(up, file) {
fileUploading(up, file);
});
uploader.bind('UploadProgress', function(up, file) {
uploadProgress(up, file);
});
uploader.bind('Error', function(up, err) {
uploadError(err.file, err.code, err.message, up);
up.refresh();
});
uploader.bind('FileUploaded', function(up, file, response) {
uploadSuccess(file, response.response);
});
uploader.bind('UploadComplete', function(up, files) {
uploadComplete();
});
}
if ( typeof(wpUploaderInit) == 'object' )
uploader_init();
});
| JavaScript |
window.wp = window.wp || {};
(function( exports, $ ) {
var Uploader;
if ( typeof _wpPluploadSettings === 'undefined' )
return;
/*
* An object that helps create a WordPress uploader using plupload.
*
* @param options - object - The options passed to the new plupload instance.
* Accepts the following parameters:
* - container - The id of uploader container.
* - browser - The id of button to trigger the file select.
* - dropzone - The id of file drop target.
* - plupload - An object of parameters to pass to the plupload instance.
* - params - An object of parameters to pass to $_POST when uploading the file.
* Extends this.plupload.multipart_params under the hood.
*
* @param attributes - object - Attributes and methods for this specific instance.
*/
Uploader = function( options ) {
var self = this,
elements = {
container: 'container',
browser: 'browse_button',
dropzone: 'drop_element'
},
key, error;
this.supports = {
upload: Uploader.browser.supported
};
this.supported = this.supports.upload;
if ( ! this.supported )
return;
// Use deep extend to ensure that multipart_params and other objects are cloned.
this.plupload = $.extend( true, { multipart_params: {} }, Uploader.defaults );
this.container = document.body; // Set default container.
// Extend the instance with options
//
// Use deep extend to allow options.plupload to override individual
// default plupload keys.
$.extend( true, this, options );
// Proxy all methods so this always refers to the current instance.
for ( key in this ) {
if ( $.isFunction( this[ key ] ) )
this[ key ] = $.proxy( this[ key ], this );
}
// Ensure all elements are jQuery elements and have id attributes
// Then set the proper plupload arguments to the ids.
for ( key in elements ) {
if ( ! this[ key ] )
continue;
this[ key ] = $( this[ key ] ).first();
if ( ! this[ key ].length ) {
delete this[ key ];
continue;
}
if ( ! this[ key ].prop('id') )
this[ key ].prop( 'id', '__wp-uploader-id-' + Uploader.uuid++ );
this.plupload[ elements[ key ] ] = this[ key ].prop('id');
}
// If the uploader has neither a browse button nor a dropzone, bail.
if ( ! ( this.browser && this.browser.length ) && ! ( this.dropzone && this.dropzone.length ) )
return;
this.uploader = new plupload.Uploader( this.plupload );
delete this.plupload;
// Set default params and remove this.params alias.
this.param( this.params || {} );
delete this.params;
error = function( message, data, file ) {
if ( file.attachment )
file.attachment.destroy();
Uploader.errors.unshift({
message: message || pluploadL10n.default_error,
data: data,
file: file
});
self.error( message, data, file );
};
this.uploader.init();
this.supports.dragdrop = this.uploader.features.dragdrop && ! Uploader.browser.mobile;
// Generate drag/drop helper classes.
(function( dropzone, supported ) {
var timer, active;
if ( ! dropzone )
return;
dropzone.toggleClass( 'supports-drag-drop', !! supported );
if ( ! supported )
return dropzone.unbind('.wp-uploader');
// 'dragenter' doesn't fire correctly,
// simulate it with a limited 'dragover'
dropzone.bind( 'dragover.wp-uploader', function(){
if ( timer )
clearTimeout( timer );
if ( active )
return;
dropzone.trigger('dropzone:enter').addClass('drag-over');
active = true;
});
dropzone.bind('dragleave.wp-uploader, drop.wp-uploader', function(){
// Using an instant timer prevents the drag-over class from
// being quickly removed and re-added when elements inside the
// dropzone are repositioned.
//
// See http://core.trac.wordpress.org/ticket/21705
timer = setTimeout( function() {
active = false;
dropzone.trigger('dropzone:leave').removeClass('drag-over');
}, 0 );
});
}( this.dropzone, this.supports.dragdrop ));
if ( this.browser ) {
this.browser.on( 'mouseenter', this.refresh );
} else {
this.uploader.disableBrowse( true );
// If HTML5 mode, hide the auto-created file container.
$('#' + this.uploader.id + '_html5_container').hide();
}
this.uploader.bind( 'FilesAdded', function( up, files ) {
_.each( files, function( file ) {
var attributes, image;
// Ignore failed uploads.
if ( plupload.FAILED === file.status )
return;
// Generate attributes for a new `Attachment` model.
attributes = _.extend({
file: file,
uploading: true,
date: new Date(),
filename: file.name,
menuOrder: 0,
uploadedTo: wp.media.model.settings.post.id
}, _.pick( file, 'loaded', 'size', 'percent' ) );
// Handle early mime type scanning for images.
image = /(?:jpe?g|png|gif)$/i.exec( file.name );
// Did we find an image?
if ( image ) {
attributes.type = 'image';
// `jpeg`, `png` and `gif` are valid subtypes.
// `jpg` is not, so map it to `jpeg`.
attributes.subtype = ( 'jpg' === image[0] ) ? 'jpeg' : image[0];
}
// Create the `Attachment`.
file.attachment = wp.media.model.Attachment.create( attributes );
Uploader.queue.add( file.attachment );
self.added( file.attachment );
});
up.refresh();
up.start();
});
this.uploader.bind( 'UploadProgress', function( up, file ) {
file.attachment.set( _.pick( file, 'loaded', 'percent' ) );
self.progress( file.attachment );
});
this.uploader.bind( 'FileUploaded', function( up, file, response ) {
var complete;
try {
response = JSON.parse( response.response );
} catch ( e ) {
return error( pluploadL10n.default_error, e, file );
}
if ( ! _.isObject( response ) || _.isUndefined( response.success ) )
return error( pluploadL10n.default_error, null, file );
else if ( ! response.success )
return error( response.data && response.data.message, response.data, file );
_.each(['file','loaded','size','percent'], function( key ) {
file.attachment.unset( key );
});
file.attachment.set( _.extend( response.data, { uploading: false }) );
wp.media.model.Attachment.get( response.data.id, file.attachment );
complete = Uploader.queue.all( function( attachment ) {
return ! attachment.get('uploading');
});
if ( complete )
Uploader.queue.reset();
self.success( file.attachment );
});
this.uploader.bind( 'Error', function( up, pluploadError ) {
var message = pluploadL10n.default_error,
key;
// Check for plupload errors.
for ( key in Uploader.errorMap ) {
if ( pluploadError.code === plupload[ key ] ) {
message = Uploader.errorMap[ key ];
if ( _.isFunction( message ) )
message = message( pluploadError.file, pluploadError );
break;
}
}
error( message, pluploadError, pluploadError.file );
up.refresh();
});
this.init();
};
// Adds the 'defaults' and 'browser' properties.
$.extend( Uploader, _wpPluploadSettings );
Uploader.uuid = 0;
Uploader.errorMap = {
'FAILED': pluploadL10n.upload_failed,
'FILE_EXTENSION_ERROR': pluploadL10n.invalid_filetype,
'IMAGE_FORMAT_ERROR': pluploadL10n.not_an_image,
'IMAGE_MEMORY_ERROR': pluploadL10n.image_memory_exceeded,
'IMAGE_DIMENSIONS_ERROR': pluploadL10n.image_dimensions_exceeded,
'GENERIC_ERROR': pluploadL10n.upload_failed,
'IO_ERROR': pluploadL10n.io_error,
'HTTP_ERROR': pluploadL10n.http_error,
'SECURITY_ERROR': pluploadL10n.security_error,
'FILE_SIZE_ERROR': function( file ) {
return pluploadL10n.file_exceeds_size_limit.replace('%s', file.name);
}
};
$.extend( Uploader.prototype, {
/**
* Acts as a shortcut to extending the uploader's multipart_params object.
*
* param( key )
* Returns the value of the key.
*
* param( key, value )
* Sets the value of a key.
*
* param( map )
* Sets values for a map of data.
*/
param: function( key, value ) {
if ( arguments.length === 1 && typeof key === 'string' )
return this.uploader.settings.multipart_params[ key ];
if ( arguments.length > 1 ) {
this.uploader.settings.multipart_params[ key ] = value;
} else {
$.extend( this.uploader.settings.multipart_params, key );
}
},
init: function() {},
error: function() {},
success: function() {},
added: function() {},
progress: function() {},
complete: function() {},
refresh: function() {
var node, attached, container, id;
if ( this.browser ) {
node = this.browser[0];
// Check if the browser node is in the DOM.
while ( node ) {
if ( node === document.body ) {
attached = true;
break;
}
node = node.parentNode;
}
// If the browser node is not attached to the DOM, use a
// temporary container to house it, as the browser button
// shims require the button to exist in the DOM at all times.
if ( ! attached ) {
id = 'wp-uploader-browser-' + this.uploader.id;
container = $( '#' + id );
if ( ! container.length ) {
container = $('<div class="wp-uploader-browser" />').css({
position: 'fixed',
top: '-1000px',
left: '-1000px',
height: 0,
width: 0
}).attr( 'id', 'wp-uploader-browser-' + this.uploader.id ).appendTo('body');
}
container.append( this.browser );
}
}
this.uploader.refresh();
}
});
Uploader.queue = new wp.media.model.Attachments( [], { query: false });
Uploader.errors = new Backbone.Collection();
exports.Uploader = Uploader;
})( wp, jQuery );
| JavaScript |
/**
* Copyright (c) 2006, David Spurr (http://www.defusion.org.uk/)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* * Neither the name of the David Spurr nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* http://www.opensource.org/licenses/bsd-license.php
*
* See scriptaculous.js for full scriptaculous licence
*/
var CropDraggable=Class.create();
Object.extend(Object.extend(CropDraggable.prototype,Draggable.prototype),{initialize:function(_1){
this.options=Object.extend({drawMethod:function(){
}},arguments[1]||{});
this.element=$(_1);
this.handle=this.element;
this.delta=this.currentDelta();
this.dragging=false;
this.eventMouseDown=this.initDrag.bindAsEventListener(this);
Event.observe(this.handle,"mousedown",this.eventMouseDown);
Draggables.register(this);
},draw:function(_2){
var _3=Position.cumulativeOffset(this.element);
var d=this.currentDelta();
_3[0]-=d[0];
_3[1]-=d[1];
var p=[0,1].map(function(i){
return (_2[i]-_3[i]-this.offset[i]);
}.bind(this));
this.options.drawMethod(p);
}});
var Cropper={};
Cropper.Img=Class.create();
Cropper.Img.prototype={initialize:function(_7,_8){
this.options=Object.extend({ratioDim:{x:0,y:0},minWidth:0,minHeight:0,displayOnInit:false,onEndCrop:Prototype.emptyFunction,captureKeys:true},_8||{});
if(this.options.minWidth>0&&this.options.minHeight>0){
this.options.ratioDim.x=this.options.minWidth;
this.options.ratioDim.y=this.options.minHeight;
}
this.img=$(_7);
this.clickCoords={x:0,y:0};
this.dragging=false;
this.resizing=false;
this.isWebKit=/Konqueror|Safari|KHTML/.test(navigator.userAgent);
this.isIE=/MSIE/.test(navigator.userAgent);
this.isOpera8=/Opera\s[1-8]/.test(navigator.userAgent);
this.ratioX=0;
this.ratioY=0;
this.attached=false;
$A(document.getElementsByTagName("script")).each(function(s){
if(s.src.match(/cropper\.js/)){
var _a=s.src.replace(/cropper\.js(.*)?/,"");
var _b=document.createElement("link");
_b.rel="stylesheet";
_b.type="text/css";
_b.href=_a+"cropper.css";
_b.media="screen";
document.getElementsByTagName("head")[0].appendChild(_b);
}
});
if(this.options.ratioDim.x>0&&this.options.ratioDim.y>0){
var _c=this.getGCD(this.options.ratioDim.x,this.options.ratioDim.y);
this.ratioX=this.options.ratioDim.x/_c;
this.ratioY=this.options.ratioDim.y/_c;
}
this.subInitialize();
if(this.img.complete||this.isWebKit){
this.onLoad();
}else{
Event.observe(this.img,"load",this.onLoad.bindAsEventListener(this));
}
},getGCD:function(a,b){return 1;
if(b==0){
return a;
}
return this.getGCD(b,a%b);
},onLoad:function(){
var _f="imgCrop_";
var _10=this.img.parentNode;
var _11="";
if(this.isOpera8){
_11=" opera8";
}
this.imgWrap=Builder.node("div",{"class":_f+"wrap"+_11});
if(this.isIE){
this.north=Builder.node("div",{"class":_f+"overlay "+_f+"north"},[Builder.node("span")]);
this.east=Builder.node("div",{"class":_f+"overlay "+_f+"east"},[Builder.node("span")]);
this.south=Builder.node("div",{"class":_f+"overlay "+_f+"south"},[Builder.node("span")]);
this.west=Builder.node("div",{"class":_f+"overlay "+_f+"west"},[Builder.node("span")]);
var _12=[this.north,this.east,this.south,this.west];
}else{
this.overlay=Builder.node("div",{"class":_f+"overlay"});
var _12=[this.overlay];
}
this.dragArea=Builder.node("div",{"class":_f+"dragArea"},_12);
this.handleN=Builder.node("div",{"class":_f+"handle "+_f+"handleN"});
this.handleNE=Builder.node("div",{"class":_f+"handle "+_f+"handleNE"});
this.handleE=Builder.node("div",{"class":_f+"handle "+_f+"handleE"});
this.handleSE=Builder.node("div",{"class":_f+"handle "+_f+"handleSE"});
this.handleS=Builder.node("div",{"class":_f+"handle "+_f+"handleS"});
this.handleSW=Builder.node("div",{"class":_f+"handle "+_f+"handleSW"});
this.handleW=Builder.node("div",{"class":_f+"handle "+_f+"handleW"});
this.handleNW=Builder.node("div",{"class":_f+"handle "+_f+"handleNW"});
this.selArea=Builder.node("div",{"class":_f+"selArea"},[Builder.node("div",{"class":_f+"marqueeHoriz "+_f+"marqueeNorth"},[Builder.node("span")]),Builder.node("div",{"class":_f+"marqueeVert "+_f+"marqueeEast"},[Builder.node("span")]),Builder.node("div",{"class":_f+"marqueeHoriz "+_f+"marqueeSouth"},[Builder.node("span")]),Builder.node("div",{"class":_f+"marqueeVert "+_f+"marqueeWest"},[Builder.node("span")]),this.handleN,this.handleNE,this.handleE,this.handleSE,this.handleS,this.handleSW,this.handleW,this.handleNW,Builder.node("div",{"class":_f+"clickArea"})]);
Element.setStyle($(this.selArea),{backgroundColor:"transparent",backgroundRepeat:"no-repeat",backgroundPosition:"0 0"});
this.imgWrap.appendChild(this.img);
this.imgWrap.appendChild(this.dragArea);
this.dragArea.appendChild(this.selArea);
this.dragArea.appendChild(Builder.node("div",{"class":_f+"clickArea"}));
_10.appendChild(this.imgWrap);
Event.observe(this.dragArea,"mousedown",this.startDrag.bindAsEventListener(this));
Event.observe(document,"mousemove",this.onDrag.bindAsEventListener(this));
Event.observe(document,"mouseup",this.endCrop.bindAsEventListener(this));
var _13=[this.handleN,this.handleNE,this.handleE,this.handleSE,this.handleS,this.handleSW,this.handleW,this.handleNW];
for(var i=0;i<_13.length;i++){
Event.observe(_13[i],"mousedown",this.startResize.bindAsEventListener(this));
}
if(this.options.captureKeys){
Event.observe(document,"keydown",this.handleKeys.bindAsEventListener(this));
}
new CropDraggable(this.selArea,{drawMethod:this.moveArea.bindAsEventListener(this)});
this.setParams();
},setParams:function(){
this.imgW=this.img.width;
this.imgH=this.img.height;
if(!this.isIE){
Element.setStyle($(this.overlay),{width:this.imgW+"px",height:this.imgH+"px"});
Element.hide($(this.overlay));
Element.setStyle($(this.selArea),{backgroundImage:"url("+this.img.src+")"});
}else{
Element.setStyle($(this.north),{height:0});
Element.setStyle($(this.east),{width:0,height:0});
Element.setStyle($(this.south),{height:0});
Element.setStyle($(this.west),{width:0,height:0});
}
Element.setStyle($(this.imgWrap),{"width":this.imgW+"px","height":this.imgH+"px"});
Element.hide($(this.selArea));
var _15=Position.positionedOffset(this.imgWrap);
this.wrapOffsets={"top":_15[1],"left":_15[0]};
var _16={x1:0,y1:0,x2:0,y2:0};
this.setAreaCoords(_16);
if(this.options.ratioDim.x>0&&this.options.ratioDim.y>0&&this.options.displayOnInit){
_16.x1=Math.ceil((this.imgW-this.options.ratioDim.x)/2);
_16.y1=Math.ceil((this.imgH-this.options.ratioDim.y)/2);
_16.x2=_16.x1+this.options.ratioDim.x;
_16.y2=_16.y1+this.options.ratioDim.y;
Element.show(this.selArea);
this.drawArea();
this.endCrop();
}
this.attached=true;
},remove:function(){
this.attached=false;
this.imgWrap.parentNode.insertBefore(this.img,this.imgWrap);
this.imgWrap.parentNode.removeChild(this.imgWrap);
Event.stopObserving(this.dragArea,"mousedown",this.startDrag.bindAsEventListener(this));
Event.stopObserving(document,"mousemove",this.onDrag.bindAsEventListener(this));
Event.stopObserving(document,"mouseup",this.endCrop.bindAsEventListener(this));
var _17=[this.handleN,this.handleNE,this.handleE,this.handleSE,this.handleS,this.handleSW,this.handleW,this.handleNW];
for(var i=0;i<_17.length;i++){
Event.stopObserving(_17[i],"mousedown",this.startResize.bindAsEventListener(this));
}
if(this.options.captureKeys){
Event.stopObserving(document,"keydown",this.handleKeys.bindAsEventListener(this));
}
},reset:function(){
if(!this.attached){
this.onLoad();
}else{
this.setParams();
}
this.endCrop();
},handleKeys:function(e){
var dir={x:0,y:0};
if(!this.dragging){
switch(e.keyCode){
case (37):
dir.x=-1;
break;
case (38):
dir.y=-1;
break;
case (39):
dir.x=1;
break;
case (40):
dir.y=1;
break;
}
if(dir.x!=0||dir.y!=0){
if(e.shiftKey){
dir.x*=10;
dir.y*=10;
}
this.moveArea([this.areaCoords.x1+dir.x,this.areaCoords.y1+dir.y]);
Event.stop(e);
}
}
},calcW:function(){
return (this.areaCoords.x2-this.areaCoords.x1);
},calcH:function(){
return (this.areaCoords.y2-this.areaCoords.y1);
},moveArea:function(_1b){
this.setAreaCoords({x1:_1b[0],y1:_1b[1],x2:_1b[0]+this.calcW(),y2:_1b[1]+this.calcH()},true);
this.drawArea();
},cloneCoords:function(_1c){
return {x1:_1c.x1,y1:_1c.y1,x2:_1c.x2,y2:_1c.y2};
},setAreaCoords:function(_1d,_1e,_1f,_20,_21){
var _22=typeof _1e!="undefined"?_1e:false;
var _23=typeof _1f!="undefined"?_1f:false;
if(_1e){
var _24=_1d.x2-_1d.x1;
var _25=_1d.y2-_1d.y1;
if(_1d.x1<0){
_1d.x1=0;
_1d.x2=_24;
}
if(_1d.y1<0){
_1d.y1=0;
_1d.y2=_25;
}
if(_1d.x2>this.imgW){
_1d.x2=this.imgW;
_1d.x1=this.imgW-_24;
}
if(_1d.y2>this.imgH){
_1d.y2=this.imgH;
_1d.y1=this.imgH-_25;
}
}else{
if(_1d.x1<0){
_1d.x1=0;
}
if(_1d.y1<0){
_1d.y1=0;
}
if(_1d.x2>this.imgW){
_1d.x2=this.imgW;
}
if(_1d.y2>this.imgH){
_1d.y2=this.imgH;
}
if(typeof (_20)!="undefined"){
if(this.ratioX>0){
this.applyRatio(_1d,{x:this.ratioX,y:this.ratioY},_20,_21);
}else{
if(_23){
this.applyRatio(_1d,{x:1,y:1},_20,_21);
}
}
var _26={a1:_1d.x1,a2:_1d.x2};
var _27={a1:_1d.y1,a2:_1d.y2};
var _28=this.options.minWidth;
var _29=this.options.minHeight;
if((_28==0||_29==0)&&_23){
if(_28>0){
_29=_28;
}else{
if(_29>0){
_28=_29;
}
}
}
this.applyMinDimension(_26,_28,_20.x,{min:0,max:this.imgW});
this.applyMinDimension(_27,_29,_20.y,{min:0,max:this.imgH});
_1d={x1:_26.a1,y1:_27.a1,x2:_26.a2,y2:_27.a2};
}
}
this.areaCoords=_1d;
},applyMinDimension:function(_2a,_2b,_2c,_2d){
if((_2a.a2-_2a.a1)<_2b){
if(_2c==1){
_2a.a2=_2a.a1+_2b;
}else{
_2a.a1=_2a.a2-_2b;
}
if(_2a.a1<_2d.min){
_2a.a1=_2d.min;
_2a.a2=_2b;
}else{
if(_2a.a2>_2d.max){
_2a.a1=_2d.max-_2b;
_2a.a2=_2d.max;
}
}
}
},applyRatio:function(_2e,_2f,_30,_31){
var _32;
if(_31=="N"||_31=="S"){
_32=this.applyRatioToAxis({a1:_2e.y1,b1:_2e.x1,a2:_2e.y2,b2:_2e.x2},{a:_2f.y,b:_2f.x},{a:_30.y,b:_30.x},{min:0,max:this.imgW});
_2e.x1=_32.b1;
_2e.y1=_32.a1;
_2e.x2=_32.b2;
_2e.y2=_32.a2;
}else{
_32=this.applyRatioToAxis({a1:_2e.x1,b1:_2e.y1,a2:_2e.x2,b2:_2e.y2},{a:_2f.x,b:_2f.y},{a:_30.x,b:_30.y},{min:0,max:this.imgH});
_2e.x1=_32.a1;
_2e.y1=_32.b1;
_2e.x2=_32.a2;
_2e.y2=_32.b2;
}
},applyRatioToAxis:function(_33,_34,_35,_36){
var _37=Object.extend(_33,{});
var _38=_37.a2-_37.a1;
var _3a=Math.floor(_38*_34.b/_34.a);
var _3b;
var _3c;
var _3d=null;
if(_35.b==1){
_3b=_37.b1+_3a;
if(_3b>_36.max){
_3b=_36.max;
_3d=_3b-_37.b1;
}
_37.b2=_3b;
}else{
_3b=_37.b2-_3a;
if(_3b<_36.min){
_3b=_36.min;
_3d=_3b+_37.b2;
}
_37.b1=_3b;
}
if(_3d!=null){
_3c=Math.floor(_3d*_34.a/_34.b);
if(_35.a==1){
_37.a2=_37.a1+_3c;
}else{
_37.a1=_37.a1=_37.a2-_3c;
}
}
return _37;
},drawArea:function(){
if(!this.isIE){
Element.show($(this.overlay));
}
var _3e=this.calcW();
var _3f=this.calcH();
var _40=this.areaCoords.x2;
var _41=this.areaCoords.y2;
var _42=this.selArea.style;
_42.left=this.areaCoords.x1+"px";
_42.top=this.areaCoords.y1+"px";
_42.width=_3e+"px";
_42.height=_3f+"px";
var _43=Math.ceil((_3e-6)/2)+"px";
var _44=Math.ceil((_3f-6)/2)+"px";
this.handleN.style.left=_43;
this.handleE.style.top=_44;
this.handleS.style.left=_43;
this.handleW.style.top=_44;
if(this.isIE){
this.north.style.height=this.areaCoords.y1+"px";
var _45=this.east.style;
_45.top=this.areaCoords.y1+"px";
_45.height=_3f+"px";
_45.left=_40+"px";
_45.width=(this.img.width-_40)+"px";
var _46=this.south.style;
_46.top=_41+"px";
_46.height=(this.img.height-_41)+"px";
var _47=this.west.style;
_47.top=this.areaCoords.y1+"px";
_47.height=_3f+"px";
_47.width=this.areaCoords.x1+"px";
}else{
_42.backgroundPosition="-"+this.areaCoords.x1+"px "+"-"+this.areaCoords.y1+"px";
}
this.subDrawArea();
this.forceReRender();
},forceReRender:function(){
if(this.isIE||this.isWebKit){
var n=document.createTextNode(" ");
var d,el,fixEL,i;
if(this.isIE){
fixEl=this.selArea;
}else{
if(this.isWebKit){
fixEl=document.getElementsByClassName("imgCrop_marqueeSouth",this.imgWrap)[0];
d=Builder.node("div","");
d.style.visibility="hidden";
var _4a=["SE","S","SW"];
for(i=0;i<_4a.length;i++){
el=document.getElementsByClassName("imgCrop_handle"+_4a[i],this.selArea)[0];
if(el.childNodes.length){
el.removeChild(el.childNodes[0]);
}
el.appendChild(d);
}
}
}
fixEl.appendChild(n);
fixEl.removeChild(n);
}
},startResize:function(e){
this.startCoords=this.cloneCoords(this.areaCoords);
this.resizing=true;
this.resizeHandle=Element.classNames(Event.element(e)).toString().replace(/([^N|NE|E|SE|S|SW|W|NW])+/,"");
Event.stop(e);
},startDrag:function(e){
Element.show(this.selArea);
this.clickCoords=this.getCurPos(e);
this.setAreaCoords({x1:this.clickCoords.x,y1:this.clickCoords.y,x2:this.clickCoords.x,y2:this.clickCoords.y});
this.dragging=true;
this.onDrag(e);
Event.stop(e);
},getCurPos:function(e){
return curPos={x:Event.pointerX(e)-this.wrapOffsets.left,y:Event.pointerY(e)-this.wrapOffsets.top};
},onDrag:function(e){
var _4f=null;
if(this.dragging||this.resizing){
var _50=this.getCurPos(e);
var _51=this.cloneCoords(this.areaCoords);
var _52={x:1,y:1};
}
if(this.dragging){
if(_50.x<this.clickCoords.x){
_52.x=-1;
}
if(_50.y<this.clickCoords.y){
_52.y=-1;
}
this.transformCoords(_50.x,this.clickCoords.x,_51,"x");
this.transformCoords(_50.y,this.clickCoords.y,_51,"y");
}else{
if(this.resizing){
_4f=this.resizeHandle;
if(_4f.match(/E/)){
this.transformCoords(_50.x,this.startCoords.x1,_51,"x");
if(_50.x<this.startCoords.x1){
_52.x=-1;
}
}else{
if(_4f.match(/W/)){
this.transformCoords(_50.x,this.startCoords.x2,_51,"x");
if(_50.x<this.startCoords.x2){
_52.x=-1;
}
}
}
if(_4f.match(/N/)){
this.transformCoords(_50.y,this.startCoords.y2,_51,"y");
if(_50.y<this.startCoords.y2){
_52.y=-1;
}
}else{
if(_4f.match(/S/)){
this.transformCoords(_50.y,this.startCoords.y1,_51,"y");
if(_50.y<this.startCoords.y1){
_52.y=-1;
}
}
}
}
}
if(this.dragging||this.resizing){
this.setAreaCoords(_51,false,e.shiftKey,_52,_4f);
this.drawArea();
Event.stop(e);
}
},transformCoords:function(_53,_54,_55,_56){
var _57=new Array();
if(_53<_54){
_57[0]=_53;
_57[1]=_54;
}else{
_57[0]=_54;
_57[1]=_53;
}
if(_56=="x"){
_55.x1=_57[0];
_55.x2=_57[1];
}else{
_55.y1=_57[0];
_55.y2=_57[1];
}
},endCrop:function(){
this.dragging=false;
this.resizing=false;
this.options.onEndCrop(this.areaCoords,{width:this.calcW(),height:this.calcH()});
},subInitialize:function(){
},subDrawArea:function(){
}};
Cropper.ImgWithPreview=Class.create();
Object.extend(Object.extend(Cropper.ImgWithPreview.prototype,Cropper.Img.prototype),{subInitialize:function(){
this.hasPreviewImg=false;
if(typeof (this.options.previewWrap)!="undefined"&&this.options.minWidth>0&&this.options.minHeight>0){
this.previewWrap=$(this.options.previewWrap);
this.previewImg=this.img.cloneNode(false);
this.options.displayOnInit=true;
this.hasPreviewImg=true;
Element.addClassName(this.previewWrap,"imgCrop_previewWrap");
Element.setStyle(this.previewWrap,{width:this.options.minWidth+"px",height:this.options.minHeight+"px"});
this.previewWrap.appendChild(this.previewImg);
}
},subDrawArea:function(){
if(this.hasPreviewImg){
var _58=this.calcW();
var _59=this.calcH();
var _5a={x:this.imgW/_58,y:this.imgH/_59};
var _5b={x:_58/this.options.minWidth,y:_59/this.options.minHeight};
var _5c={w:Math.ceil(this.options.minWidth*_5a.x)+"px",h:Math.ceil(this.options.minHeight*_5a.y)+"px",x:"-"+Math.ceil(this.areaCoords.x1/_5b.x)+"px",y:"-"+Math.ceil(this.areaCoords.y1/_5b.y)+"px"};
var _5d=this.previewImg.style;
_5d.width=_5c.w;
_5d.height=_5c.h;
_5d.left=_5c.x;
_5d.top=_5c.y;
}
}});
| JavaScript |
var wpLink;
(function($){
var inputs = {}, rivers = {}, ed, River, Query;
wpLink = {
timeToTriggerRiver: 150,
minRiverAJAXDuration: 200,
riverBottomThreshold: 5,
keySensitivity: 100,
lastSearch: '',
textarea: '',
init : function() {
inputs.dialog = $('#wp-link');
inputs.submit = $('#wp-link-submit');
// URL
inputs.url = $('#url-field');
inputs.nonce = $('#_ajax_linking_nonce');
// Secondary options
inputs.title = $('#link-title-field');
// Advanced Options
inputs.openInNewTab = $('#link-target-checkbox');
inputs.search = $('#search-field');
// Build Rivers
rivers.search = new River( $('#search-results') );
rivers.recent = new River( $('#most-recent-results') );
rivers.elements = $('.query-results', inputs.dialog);
// Bind event handlers
inputs.dialog.keydown( wpLink.keydown );
inputs.dialog.keyup( wpLink.keyup );
inputs.submit.click( function(e){
e.preventDefault();
wpLink.update();
});
$('#wp-link-cancel').click( function(e){
e.preventDefault();
wpLink.close();
});
$('#internal-toggle').click( wpLink.toggleInternalLinking );
rivers.elements.bind('river-select', wpLink.updateFields );
inputs.search.keyup( wpLink.searchInternalLinks );
inputs.dialog.bind('wpdialogrefresh', wpLink.refresh);
inputs.dialog.bind('wpdialogbeforeopen', wpLink.beforeOpen);
inputs.dialog.bind('wpdialogclose', wpLink.onClose);
},
beforeOpen : function() {
wpLink.range = null;
if ( ! wpLink.isMCE() && document.selection ) {
wpLink.textarea.focus();
wpLink.range = document.selection.createRange();
}
},
open : function() {
if ( !wpActiveEditor )
return;
this.textarea = $('#'+wpActiveEditor).get(0);
// Initialize the dialog if necessary (html mode).
if ( ! inputs.dialog.data('wpdialog') ) {
inputs.dialog.wpdialog({
title: wpLinkL10n.title,
width: 480,
height: 'auto',
modal: true,
dialogClass: 'wp-dialog',
zIndex: 300000
});
}
inputs.dialog.wpdialog('open');
},
isMCE : function() {
return tinyMCEPopup && ( ed = tinyMCEPopup.editor ) && ! ed.isHidden();
},
refresh : function() {
// Refresh rivers (clear links, check visibility)
rivers.search.refresh();
rivers.recent.refresh();
if ( wpLink.isMCE() )
wpLink.mceRefresh();
else
wpLink.setDefaultValues();
// Focus the URL field and highlight its contents.
// If this is moved above the selection changes,
// IE will show a flashing cursor over the dialog.
inputs.url.focus()[0].select();
// Load the most recent results if this is the first time opening the panel.
if ( ! rivers.recent.ul.children().length )
rivers.recent.ajax();
},
mceRefresh : function() {
var e;
ed = tinyMCEPopup.editor;
tinyMCEPopup.restoreSelection();
// If link exists, select proper values.
if ( e = ed.dom.getParent(ed.selection.getNode(), 'A') ) {
// Set URL and description.
inputs.url.val( ed.dom.getAttrib(e, 'href') );
inputs.title.val( ed.dom.getAttrib(e, 'title') );
// Set open in new tab.
if ( "_blank" == ed.dom.getAttrib(e, 'target') )
inputs.openInNewTab.prop('checked', true);
// Update save prompt.
inputs.submit.val( wpLinkL10n.update );
// If there's no link, set the default values.
} else {
wpLink.setDefaultValues();
}
tinyMCEPopup.storeSelection();
},
close : function() {
if ( wpLink.isMCE() )
tinyMCEPopup.close();
else
inputs.dialog.wpdialog('close');
},
onClose: function() {
if ( ! wpLink.isMCE() ) {
wpLink.textarea.focus();
if ( wpLink.range ) {
wpLink.range.moveToBookmark( wpLink.range.getBookmark() );
wpLink.range.select();
}
}
},
getAttrs : function() {
return {
href : inputs.url.val(),
title : inputs.title.val(),
target : inputs.openInNewTab.prop('checked') ? '_blank' : ''
};
},
update : function() {
if ( wpLink.isMCE() )
wpLink.mceUpdate();
else
wpLink.htmlUpdate();
},
htmlUpdate : function() {
var attrs, html, begin, end, cursor,
textarea = wpLink.textarea;
if ( ! textarea )
return;
attrs = wpLink.getAttrs();
// If there's no href, return.
if ( ! attrs.href || attrs.href == 'http://' )
return;
// Build HTML
html = '<a href="' + attrs.href + '"';
if ( attrs.title )
html += ' title="' + attrs.title + '"';
if ( attrs.target )
html += ' target="' + attrs.target + '"';
html += '>';
// Insert HTML
if ( document.selection && wpLink.range ) {
// IE
// Note: If no text is selected, IE will not place the cursor
// inside the closing tag.
textarea.focus();
wpLink.range.text = html + wpLink.range.text + '</a>';
wpLink.range.moveToBookmark( wpLink.range.getBookmark() );
wpLink.range.select();
wpLink.range = null;
} else if ( typeof textarea.selectionStart !== 'undefined' ) {
// W3C
begin = textarea.selectionStart;
end = textarea.selectionEnd;
selection = textarea.value.substring( begin, end );
html = html + selection + '</a>';
cursor = begin + html.length;
// If no next is selected, place the cursor inside the closing tag.
if ( begin == end )
cursor -= '</a>'.length;
textarea.value = textarea.value.substring( 0, begin )
+ html
+ textarea.value.substring( end, textarea.value.length );
// Update cursor position
textarea.selectionStart = textarea.selectionEnd = cursor;
}
wpLink.close();
textarea.focus();
},
mceUpdate : function() {
var ed = tinyMCEPopup.editor,
attrs = wpLink.getAttrs(),
e, b;
tinyMCEPopup.restoreSelection();
e = ed.dom.getParent(ed.selection.getNode(), 'A');
// If the values are empty, unlink and return
if ( ! attrs.href || attrs.href == 'http://' ) {
if ( e ) {
tinyMCEPopup.execCommand("mceBeginUndoLevel");
b = ed.selection.getBookmark();
ed.dom.remove(e, 1);
ed.selection.moveToBookmark(b);
tinyMCEPopup.execCommand("mceEndUndoLevel");
wpLink.close();
}
return;
}
tinyMCEPopup.execCommand("mceBeginUndoLevel");
if (e == null) {
ed.getDoc().execCommand("unlink", false, null);
tinyMCEPopup.execCommand("mceInsertLink", false, "#mce_temp_url#", {skip_undo : 1});
tinymce.each(ed.dom.select("a"), function(n) {
if (ed.dom.getAttrib(n, 'href') == '#mce_temp_url#') {
e = n;
ed.dom.setAttribs(e, attrs);
}
});
// Sometimes WebKit lets a user create a link where
// they shouldn't be able to. In this case, CreateLink
// injects "#mce_temp_url#" into their content. Fix it.
if ( $(e).text() == '#mce_temp_url#' ) {
ed.dom.remove(e);
e = null;
}
} else {
ed.dom.setAttribs(e, attrs);
}
// Don't move caret if selection was image
if ( e && (e.childNodes.length != 1 || e.firstChild.nodeName != 'IMG') ) {
ed.focus();
ed.selection.select(e);
ed.selection.collapse(0);
tinyMCEPopup.storeSelection();
}
tinyMCEPopup.execCommand("mceEndUndoLevel");
wpLink.close();
},
updateFields : function( e, li, originalEvent ) {
inputs.url.val( li.children('.item-permalink').val() );
inputs.title.val( li.hasClass('no-title') ? '' : li.children('.item-title').text() );
if ( originalEvent && originalEvent.type == "click" )
inputs.url.focus();
},
setDefaultValues : function() {
// Set URL and description to defaults.
// Leave the new tab setting as-is.
inputs.url.val('http://');
inputs.title.val('');
// Update save prompt.
inputs.submit.val( wpLinkL10n.save );
},
searchInternalLinks : function() {
var t = $(this), waiting,
search = t.val();
if ( search.length > 2 ) {
rivers.recent.hide();
rivers.search.show();
// Don't search if the keypress didn't change the title.
if ( wpLink.lastSearch == search )
return;
wpLink.lastSearch = search;
waiting = t.parent().find('.spinner').show();
rivers.search.change( search );
rivers.search.ajax( function(){ waiting.hide(); });
} else {
rivers.search.hide();
rivers.recent.show();
}
},
next : function() {
rivers.search.next();
rivers.recent.next();
},
prev : function() {
rivers.search.prev();
rivers.recent.prev();
},
keydown : function( event ) {
var fn, key = $.ui.keyCode;
switch( event.which ) {
case key.UP:
fn = 'prev';
case key.DOWN:
fn = fn || 'next';
clearInterval( wpLink.keyInterval );
wpLink[ fn ]();
wpLink.keyInterval = setInterval( wpLink[ fn ], wpLink.keySensitivity );
break;
default:
return;
}
event.preventDefault();
},
keyup: function( event ) {
var key = $.ui.keyCode;
switch( event.which ) {
case key.ESCAPE:
event.stopImmediatePropagation();
if ( ! $(document).triggerHandler( 'wp_CloseOnEscape', [{ event: event, what: 'wplink', cb: wpLink.close }] ) )
wpLink.close();
return false;
break;
case key.UP:
case key.DOWN:
clearInterval( wpLink.keyInterval );
break;
default:
return;
}
event.preventDefault();
},
delayedCallback : function( func, delay ) {
var timeoutTriggered, funcTriggered, funcArgs, funcContext;
if ( ! delay )
return func;
setTimeout( function() {
if ( funcTriggered )
return func.apply( funcContext, funcArgs );
// Otherwise, wait.
timeoutTriggered = true;
}, delay);
return function() {
if ( timeoutTriggered )
return func.apply( this, arguments );
// Otherwise, wait.
funcArgs = arguments;
funcContext = this;
funcTriggered = true;
};
},
toggleInternalLinking : function( event ) {
var panel = $('#search-panel'),
widget = inputs.dialog.wpdialog('widget'),
// We're about to toggle visibility; it's currently the opposite
visible = !panel.is(':visible'),
win = $(window);
$(this).toggleClass('toggle-arrow-active', visible);
inputs.dialog.height('auto');
panel.slideToggle( 300, function() {
setUserSetting('wplink', visible ? '1' : '0');
inputs[ visible ? 'search' : 'url' ].focus();
// Move the box if the box is now expanded, was opened in a collapsed state,
// and if it needs to be moved. (Judged by bottom not being positive or
// bottom being smaller than top.)
var scroll = win.scrollTop(),
top = widget.offset().top,
bottom = top + widget.outerHeight(),
diff = bottom - win.height();
if ( diff > scroll ) {
widget.animate({'top': diff < top ? top - diff : scroll }, 200);
}
});
event.preventDefault();
}
}
River = function( element, search ) {
var self = this;
this.element = element;
this.ul = element.children('ul');
this.waiting = element.find('.river-waiting');
this.change( search );
this.refresh();
element.scroll( function(){ self.maybeLoad(); });
element.delegate('li', 'click', function(e){ self.select( $(this), e ); });
};
$.extend( River.prototype, {
refresh: function() {
this.deselect();
this.visible = this.element.is(':visible');
},
show: function() {
if ( ! this.visible ) {
this.deselect();
this.element.show();
this.visible = true;
}
},
hide: function() {
this.element.hide();
this.visible = false;
},
// Selects a list item and triggers the river-select event.
select: function( li, event ) {
var liHeight, elHeight, liTop, elTop;
if ( li.hasClass('unselectable') || li == this.selected )
return;
this.deselect();
this.selected = li.addClass('selected');
// Make sure the element is visible
liHeight = li.outerHeight();
elHeight = this.element.height();
liTop = li.position().top;
elTop = this.element.scrollTop();
if ( liTop < 0 ) // Make first visible element
this.element.scrollTop( elTop + liTop );
else if ( liTop + liHeight > elHeight ) // Make last visible element
this.element.scrollTop( elTop + liTop - elHeight + liHeight );
// Trigger the river-select event
this.element.trigger('river-select', [ li, event, this ]);
},
deselect: function() {
if ( this.selected )
this.selected.removeClass('selected');
this.selected = false;
},
prev: function() {
if ( ! this.visible )
return;
var to;
if ( this.selected ) {
to = this.selected.prev('li');
if ( to.length )
this.select( to );
}
},
next: function() {
if ( ! this.visible )
return;
var to = this.selected ? this.selected.next('li') : $('li:not(.unselectable):first', this.element);
if ( to.length )
this.select( to );
},
ajax: function( callback ) {
var self = this,
delay = this.query.page == 1 ? 0 : wpLink.minRiverAJAXDuration,
response = wpLink.delayedCallback( function( results, params ) {
self.process( results, params );
if ( callback )
callback( results, params );
}, delay );
this.query.ajax( response );
},
change: function( search ) {
if ( this.query && this._search == search )
return;
this._search = search;
this.query = new Query( search );
this.element.scrollTop(0);
},
process: function( results, params ) {
var list = '', alt = true, classes = '',
firstPage = params.page == 1;
if ( !results ) {
if ( firstPage ) {
list += '<li class="unselectable"><span class="item-title"><em>'
+ wpLinkL10n.noMatchesFound
+ '</em></span></li>';
}
} else {
$.each( results, function() {
classes = alt ? 'alternate' : '';
classes += this['title'] ? '' : ' no-title';
list += classes ? '<li class="' + classes + '">' : '<li>';
list += '<input type="hidden" class="item-permalink" value="' + this['permalink'] + '" />';
list += '<span class="item-title">';
list += this['title'] ? this['title'] : wpLinkL10n.noTitle;
list += '</span><span class="item-info">' + this['info'] + '</span></li>';
alt = ! alt;
});
}
this.ul[ firstPage ? 'html' : 'append' ]( list );
},
maybeLoad: function() {
var self = this,
el = this.element,
bottom = el.scrollTop() + el.height();
if ( ! this.query.ready() || bottom < this.ul.height() - wpLink.riverBottomThreshold )
return;
setTimeout(function() {
var newTop = el.scrollTop(),
newBottom = newTop + el.height();
if ( ! self.query.ready() || newBottom < self.ul.height() - wpLink.riverBottomThreshold )
return;
self.waiting.show();
el.scrollTop( newTop + self.waiting.outerHeight() );
self.ajax( function() { self.waiting.hide(); });
}, wpLink.timeToTriggerRiver );
}
});
Query = function( search ) {
this.page = 1;
this.allLoaded = false;
this.querying = false;
this.search = search;
};
$.extend( Query.prototype, {
ready: function() {
return !( this.querying || this.allLoaded );
},
ajax: function( callback ) {
var self = this,
query = {
action : 'wp-link-ajax',
page : this.page,
'_ajax_linking_nonce' : inputs.nonce.val()
};
if ( this.search )
query.search = this.search;
this.querying = true;
$.post( ajaxurl, query, function(r) {
self.page++;
self.querying = false;
self.allLoaded = !r;
callback( r, query );
}, "json" );
}
});
$(document).ready( wpLink.init );
})(jQuery);
| JavaScript |
window.wp = window.wp || {};
(function( exports, $ ){
var api = wp.customize,
Loader;
$.extend( $.support, {
history: !! ( window.history && history.pushState ),
hashchange: ('onhashchange' in window) && (document.documentMode === undefined || document.documentMode > 7)
});
Loader = $.extend( {}, api.Events, {
initialize: function() {
this.body = $( document.body );
// Ensure the loader is supported.
// Check for settings, postMessage support, and whether we require CORS support.
if ( ! Loader.settings || ! $.support.postMessage || ( ! $.support.cors && Loader.settings.isCrossDomain ) ) {
return;
}
this.window = $( window );
this.element = $( '<div id="customize-container" />' ).appendTo( this.body );
this.bind( 'open', this.overlay.show );
this.bind( 'close', this.overlay.hide );
$('#wpbody').on( 'click', '.load-customize', function( event ) {
event.preventDefault();
// Store a reference to the link that opened the customizer.
Loader.link = $(this);
// Load the theme.
Loader.open( Loader.link.attr('href') );
});
// Add navigation listeners.
if ( $.support.history )
this.window.on( 'popstate', Loader.popstate );
if ( $.support.hashchange ) {
this.window.on( 'hashchange', Loader.hashchange );
this.window.triggerHandler( 'hashchange' );
}
},
popstate: function( e ) {
var state = e.originalEvent.state;
if ( state && state.customize )
Loader.open( state.customize );
else if ( Loader.active )
Loader.close();
},
hashchange: function( e ) {
var hash = window.location.toString().split('#')[1];
if ( hash && 0 === hash.indexOf( 'wp_customize=on' ) )
Loader.open( Loader.settings.url + '?' + hash );
if ( ! hash && ! $.support.history )
Loader.close();
},
open: function( src ) {
var hash;
if ( this.active )
return;
// Load the full page on mobile devices.
if ( Loader.settings.browser.mobile )
return window.location = src;
this.active = true;
this.body.addClass('customize-loading');
this.iframe = $( '<iframe />', { src: src }).appendTo( this.element );
this.iframe.one( 'load', this.loaded );
// Create a postMessage connection with the iframe.
this.messenger = new api.Messenger({
url: src,
channel: 'loader',
targetWindow: this.iframe[0].contentWindow
});
// Wait for the connection from the iframe before sending any postMessage events.
this.messenger.bind( 'ready', function() {
Loader.messenger.send( 'back' );
});
this.messenger.bind( 'close', function() {
if ( $.support.history )
history.back();
else if ( $.support.hashchange )
window.location.hash = '';
else
Loader.close();
});
this.messenger.bind( 'activated', function( location ) {
if ( location )
window.location = location;
});
hash = src.split('?')[1];
// Ensure we don't call pushState if the user hit the forward button.
if ( $.support.history && window.location.href !== src )
history.pushState( { customize: src }, '', src );
else if ( ! $.support.history && $.support.hashchange && hash )
window.location.hash = 'wp_customize=on&' + hash;
this.trigger( 'open' );
},
opened: function() {
Loader.body.addClass( 'customize-active full-overlay-active' );
},
close: function() {
if ( ! this.active )
return;
this.active = false;
this.trigger( 'close' );
// Return focus to link that was originally clicked.
if ( this.link )
this.link.focus();
},
closed: function() {
Loader.iframe.remove();
Loader.messenger.destroy();
Loader.iframe = null;
Loader.messenger = null;
Loader.body.removeClass( 'customize-active full-overlay-active' ).removeClass( 'customize-loading' );
},
loaded: function() {
Loader.body.removeClass('customize-loading');
},
overlay: {
show: function() {
this.element.fadeIn( 200, Loader.opened );
},
hide: function() {
this.element.fadeOut( 200, Loader.closed );
}
}
});
$( function() {
Loader.settings = _wpCustomizeLoaderSettings;
Loader.initialize();
});
// Expose the API to the world.
api.Loader = Loader;
})( wp, jQuery );
| JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.