code
stringlengths
1
2.08M
language
stringclasses
1 value
/** * Creates a new level control. * @constructor * @param {IoMap} iomap the IO map controller. * @param {Array.<string>} levels the levels to create switchers for. */ function LevelControl(iomap, levels) { var that = this; this.iomap_ = iomap; this.el_ = this.initDom_(levels); google.maps.event.addListener(iomap, 'level_changed', function() { that.changeLevel_(iomap.get('level')); }); } /** * Gets the DOM element for the control. * @return {Element} */ LevelControl.prototype.getElement = function() { return this.el_; }; /** * Creates the necessary DOM for the control. * @return {Element} */ LevelControl.prototype.initDom_ = function(levelDefinition) { var controlDiv = document.createElement('DIV'); controlDiv.setAttribute('id', 'levels-wrapper'); var levels = document.createElement('DIV'); levels.setAttribute('id', 'levels'); controlDiv.appendChild(levels); var levelSelect = this.levelSelect_ = document.createElement('DIV'); levelSelect.setAttribute('id', 'level-select'); levels.appendChild(levelSelect); this.levelDivs_ = []; var that = this; for (var i = 0, level; level = levelDefinition[i]; i++) { var div = document.createElement('DIV'); div.innerHTML = 'Level ' + level; div.setAttribute('id', 'level-' + level); div.className = 'level'; levels.appendChild(div); this.levelDivs_.push(div); google.maps.event.addDomListener(div, 'click', function(e) { var id = e.currentTarget.getAttribute('id'); var level = parseInt(id.replace('level-', ''), 10); that.iomap_.setHash('level' + level); }); } controlDiv.index = 1; return controlDiv; }; /** * Changes the highlighted level in the control. * @param {number} level the level number to select. */ LevelControl.prototype.changeLevel_ = function(level) { if (this.currentLevelDiv_) { this.currentLevelDiv_.className = this.currentLevelDiv_.className.replace(' level-selected', ''); } var h = 25; if (window['ioEmbed']) { h = (window.screen.availWidth > 600) ? 34 : 24; } this.levelSelect_.style.top = 9 + ((level - 1) * h) + 'px'; var div = this.levelDivs_[level - 1]; div.className += ' level-selected'; this.currentLevelDiv_ = div; };
JavaScript
/** * @license * * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview SmartMarker. * * @author Chris Broadfoot (cbro@google.com) */ /** * A google.maps.Marker that has some smarts about the zoom levels it should be * shown. * * Options are the same as google.maps.Marker, with the addition of minZoom and * maxZoom. These zoom levels are inclusive. That is, a SmartMarker with * a minZoom and maxZoom of 13 will only be shown at zoom level 13. * @constructor * @extends google.maps.Marker * @param {Object=} opts Same as MarkerOptions, plus minZoom and maxZoom. */ function SmartMarker(opts) { var marker = new google.maps.Marker; // default min/max Zoom - shows the marker all the time. marker.setValues({ 'minZoom': 0, 'maxZoom': Infinity }); // the current listener (if any), triggered on map zoom_changed var mapZoomListener; google.maps.event.addListener(marker, 'map_changed', function() { if (mapZoomListener) { google.maps.event.removeListener(mapZoomListener); } var map = marker.getMap(); if (map) { var listener = SmartMarker.newZoomListener_(marker); mapZoomListener = google.maps.event.addListener(map, 'zoom_changed', listener); // Call the listener straight away. The map may already be initialized, // so it will take user input for zoom_changed to be fired. listener(); } }); marker.setValues(opts); return marker; } window['SmartMarker'] = SmartMarker; /** * Creates a new listener to be triggered on 'zoom_changed' event. * Hides and shows the target Marker based on the map's zoom level. * @param {google.maps.Marker} marker The target marker. * @return Function */ SmartMarker.newZoomListener_ = function(marker) { var map = marker.getMap(); return function() { var zoom = map.getZoom(); var minZoom = Number(marker.get('minZoom')); var maxZoom = Number(marker.get('maxZoom')); marker.setVisible(zoom >= minZoom && zoom <= maxZoom); }; };
JavaScript
// Copyright 2011 Google /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * The Google IO Map * @constructor */ var IoMap = function() { var moscone = new google.maps.LatLng(37.78313383211993, -122.40394949913025); /** @type {Node} */ this.mapDiv_ = document.getElementById(this.MAP_ID); var ioStyle = [ { 'featureType': 'road', stylers: [ { hue: '#00aaff' }, { gamma: 1.67 }, { saturation: -24 }, { lightness: -38 } ] },{ 'featureType': 'road', 'elementType': 'labels', stylers: [ { invert_lightness: true } ] }]; /** @type {boolean} */ this.ready_ = false; /** @type {google.maps.Map} */ this.map_ = new google.maps.Map(this.mapDiv_, { zoom: 18, center: moscone, navigationControl: true, mapTypeControl: false, scaleControl: true, mapTypeId: 'io', streetViewControl: false }); var style = /** @type {*} */(new google.maps.StyledMapType(ioStyle)); this.map_.mapTypes.set('io', /** @type {google.maps.MapType} */(style)); google.maps.event.addListenerOnce(this.map_, 'tilesloaded', function() { if (window['MAP_CONTAINER'] !== undefined) { window['MAP_CONTAINER']['onMapReady'](); } }); /** @type {Array.<Floor>} */ this.floors_ = []; for (var i = 0; i < this.LEVELS_.length; i++) { this.floors_.push(new Floor(this.map_)); } this.addLevelControl_(); this.addMapOverlay_(); this.loadMapContent_(); this.initLocationHashWatcher_(); if (!document.location.hash) { this.showLevel(1, true); } } IoMap.prototype = new google.maps.MVCObject; /** * The id of the Element to add the map to. * * @type {string} * @const */ IoMap.prototype.MAP_ID = 'map-canvas'; /** * The levels of the Moscone Center. * * @type {Array.<string>} * @private */ IoMap.prototype.LEVELS_ = ['1', '2', '3']; /** * Location where the tiles are hosted. * * @type {string} * @private */ IoMap.prototype.BASE_TILE_URL_ = 'http://www.gstatic.com/io2010maps/tiles/5/'; /** * The minimum zoom level to show the overlay. * * @type {number} * @private */ IoMap.prototype.MIN_ZOOM_ = 16; /** * The maximum zoom level to show the overlay. * * @type {number} * @private */ IoMap.prototype.MAX_ZOOM_ = 20; /** * The template for loading tiles. Replace {L} with the level, {Z} with the * zoom level, {X} and {Y} with respective tile coordinates. * * @type {string} * @private */ IoMap.prototype.TILE_TEMPLATE_URL_ = IoMap.prototype.BASE_TILE_URL_ + 'L{L}_{Z}_{X}_{Y}.png'; /** * @type {string} * @private */ IoMap.prototype.SIMPLE_TILE_TEMPLATE_URL_ = IoMap.prototype.BASE_TILE_URL_ + '{Z}_{X}_{Y}.png'; /** * The extent of the overlay at certain zoom levels. * * @type {Object.<string, Array.<Array.<number>>>} * @private */ IoMap.prototype.RESOLUTION_BOUNDS_ = { 16: [[10484, 10485], [25328, 25329]], 17: [[20969, 20970], [50657, 50658]], 18: [[41939, 41940], [101315, 101317]], 19: [[83878, 83881], [202631, 202634]], 20: [[167757, 167763], [405263, 405269]] }; /** * The previous hash to compare against. * * @type {string?} * @private */ IoMap.prototype.prevHash_ = null; /** * Initialise the location hash watcher. * * @private */ IoMap.prototype.initLocationHashWatcher_ = function() { var that = this; if ('onhashchange' in window) { window.addEventListener('hashchange', function() { that.parseHash_(); }, true); } else { var that = this window.setInterval(function() { that.parseHash_(); }, 100); } this.parseHash_(); }; /** * Called from Android. * * @param {Number} x A percentage to pan left by. */ IoMap.prototype.panLeft = function(x) { var div = this.map_.getDiv(); var left = div.clientWidth * x; this.map_.panBy(left, 0); }; IoMap.prototype['panLeft'] = IoMap.prototype.panLeft; /** * Adds the level switcher to the top left of the map. * * @private */ IoMap.prototype.addLevelControl_ = function() { var control = new LevelControl(this, this.LEVELS_).getElement(); this.map_.controls[google.maps.ControlPosition.TOP_LEFT].push(control); }; /** * Shows a floor based on the content of location.hash. * * @private */ IoMap.prototype.parseHash_ = function() { var hash = document.location.hash; if (hash == this.prevHash_) { return; } this.prevHash_ = hash; var level = 1; if (hash) { var match = hash.match(/level(\d)(?:\:([\w-]+))?/); if (match && match[1]) { level = parseInt(match[1], 10); } } this.showLevel(level, true); }; /** * Updates location.hash based on the currently shown floor. * * @param {string?} opt_hash */ IoMap.prototype.setHash = function(opt_hash) { var hash = document.location.hash.substring(1); if (hash == opt_hash) { return; } if (opt_hash) { document.location.hash = opt_hash; } else { document.location.hash = 'level' + this.get('level'); } }; IoMap.prototype['setHash'] = IoMap.prototype.setHash; /** * Called from spreadsheets. */ IoMap.prototype.loadSandboxCallback = function(json) { var updated = json['feed']['updated']['$t']; var contentItems = []; var ids = {}; var entries = json['feed']['entry']; for (var i = 0, entry; entry = entries[i]; i++) { var item = {}; item.companyName = entry['gsx$companyname']['$t']; item.companyUrl = entry['gsx$companyurl']['$t']; var p = entry['gsx$companypod']['$t']; item.pod = p; p = p.toLowerCase().replace(/\s+/, ''); item.sessionRoom = p; contentItems.push(item); }; this.sandboxItems_ = contentItems; this.ready_ = true; this.addMapContent_(); }; /** * Called from spreadsheets. * * @param {Object} json The json feed from the spreadsheet. */ IoMap.prototype.loadSessionsCallback = function(json) { var updated = json['feed']['updated']['$t']; var contentItems = []; var ids = {}; var entries = json['feed']['entry']; for (var i = 0, entry; entry = entries[i]; i++) { var item = {}; item.sessionDate = entry['gsx$sessiondate']['$t']; item.sessionAbstract = entry['gsx$sessionabstract']['$t']; item.sessionHashtag = entry['gsx$sessionhashtag']['$t']; item.sessionLevel = entry['gsx$sessionlevel']['$t']; item.sessionTitle = entry['gsx$sessiontitle']['$t']; item.sessionTrack = entry['gsx$sessiontrack']['$t']; item.sessionUrl = entry['gsx$sessionurl']['$t']; item.sessionYoutubeUrl = entry['gsx$sessionyoutubeurl']['$t']; item.sessionTime = entry['gsx$sessiontime']['$t']; item.sessionRoom = entry['gsx$sessionroom']['$t']; item.sessionTags = entry['gsx$sessiontags']['$t']; item.sessionSpeakers = entry['gsx$sessionspeakers']['$t']; if (item.sessionDate.indexOf('10') != -1) { item.sessionDay = 10; } else { item.sessionDay = 11; } var timeParts = item.sessionTime.split('-'); item.sessionStart = this.convertTo24Hour_(timeParts[0]); item.sessionEnd = this.convertTo24Hour_(timeParts[1]); contentItems.push(item); } this.sessionItems_ = contentItems; }; /** * Converts the time in the spread sheet to 24 hour time. * * @param {string} time The time like 10:42am. */ IoMap.prototype.convertTo24Hour_ = function(time) { var pm = time.indexOf('pm') != -1; time = time.replace(/[am|pm]/ig, ''); if (pm) { var bits = time.split(':'); var hr = parseInt(bits[0], 10); if (hr < 12) { time = (hr + 12) + ':' + bits[1]; } } return time; }; /** * Loads the map content from Google Spreadsheets. * * @private */ IoMap.prototype.loadMapContent_ = function() { // Initiate a JSONP request. var that = this; // Add a exposed call back function window['loadSessionsCallback'] = function(json) { that.loadSessionsCallback(json); } // Add a exposed call back function window['loadSandboxCallback'] = function(json) { that.loadSandboxCallback(json); } var key = 'tmaLiaNqIWYYtuuhmIyG0uQ'; var worksheetIDs = { sessions: 'od6', sandbox: 'od4' }; var jsonpUrl = 'http://spreadsheets.google.com/feeds/list/' + key + '/' + worksheetIDs.sessions + '/public/values' + '?alt=json-in-script&callback=loadSessionsCallback'; var script = document.createElement('script'); script.setAttribute('src', jsonpUrl); script.setAttribute('type', 'text/javascript'); document.documentElement.firstChild.appendChild(script); var jsonpUrl = 'http://spreadsheets.google.com/feeds/list/' + key + '/' + worksheetIDs.sandbox + '/public/values' + '?alt=json-in-script&callback=loadSandboxCallback'; var script = document.createElement('script'); script.setAttribute('src', jsonpUrl); script.setAttribute('type', 'text/javascript'); document.documentElement.firstChild.appendChild(script); }; /** * Called from Android. * * @param {string} roomId The id of the room to load. */ IoMap.prototype.showLocationById = function(roomId) { var locations = this.LOCATIONS_; for (var level in locations) { var levelId = level.replace('LEVEL', ''); for (var loc in locations[level]) { var room = locations[level][loc]; if (loc == roomId) { var pos = new google.maps.LatLng(room.lat, room.lng); this.map_.panTo(pos); this.map_.setZoom(19); this.showLevel(levelId); if (room.marker_) { room.marker_.setAnimation(google.maps.Animation.BOUNCE); // Disable the animation after 5 seconds. window.setTimeout(function() { room.marker_.setAnimation(); }, 5000); } return; } } } }; IoMap.prototype['showLocationById'] = IoMap.prototype.showLocationById; /** * Called when the level is changed. Hides and shows floors. */ IoMap.prototype['level_changed'] = function() { var level = this.get('level'); if (this.infoWindow_) { this.infoWindow_.setMap(null); } for (var i = 1, floor; floor = this.floors_[i - 1]; i++) { if (i == level) { floor.show(); } else { floor.hide(); } } this.setHash('level' + level); }; /** * Shows a particular floor. * * @param {string} level The level to show. * @param {boolean=} opt_force if true, changes the floor even if it's already * the current floor. */ IoMap.prototype.showLevel = function(level, opt_force) { if (!opt_force && level == this.get('level')) { return; } this.set('level', level); }; IoMap.prototype['showLevel'] = IoMap.prototype.showLevel; /** * Create a marker with the content item's correct icon. * * @param {Object} item The content item for the marker. * @return {google.maps.Marker} The new marker. * @private */ IoMap.prototype.createContentMarker_ = function(item) { if (!item.icon) { item.icon = 'generic'; } var image; var shadow; switch(item.icon) { case 'generic': case 'info': case 'media': var image = new google.maps.MarkerImage( 'marker-' + item.icon + '.png', new google.maps.Size(30, 28), new google.maps.Point(0, 0), new google.maps.Point(13, 26)); var shadow = new google.maps.MarkerImage( 'marker-shadow.png', new google.maps.Size(30, 28), new google.maps.Point(0,0), new google.maps.Point(13, 26)); break; case 'toilets': var image = new google.maps.MarkerImage( item.icon + '.png', new google.maps.Size(35, 35), new google.maps.Point(0, 0), new google.maps.Point(17, 17)); break; case 'elevator': var image = new google.maps.MarkerImage( item.icon + '.png', new google.maps.Size(48, 26), new google.maps.Point(0, 0), new google.maps.Point(24, 13)); break; } var inactive = item.type == 'inactive'; var latLng = new google.maps.LatLng(item.lat, item.lng); var marker = new SmartMarker({ position: latLng, shadow: shadow, icon: image, title: item.title, minZoom: inactive ? 19 : 18, clickable: !inactive }); marker['type_'] = item.type; if (!inactive) { var that = this; google.maps.event.addListener(marker, 'click', function() { that.openContentInfo_(item); }); } return marker; }; /** * Create a label with the content item's title atribute, if it exists. * * @param {Object} item The content item for the marker. * @return {MapLabel?} The new label. * @private */ IoMap.prototype.createContentLabel_ = function(item) { if (!item.title || item.suppressLabel) { return null; } var latLng = new google.maps.LatLng(item.lat, item.lng); return new MapLabel({ 'text': item.title, 'position': latLng, 'minZoom': item.labelMinZoom || 18, 'align': item.labelAlign || 'center', 'fontColor': item.labelColor, 'fontSize': item.labelSize || 12 }); } /** * Open a info window a content item. * * @param {Object} item A content item with content and a marker. */ IoMap.prototype.openContentInfo_ = function(item) { if (window['MAP_CONTAINER'] !== undefined) { window['MAP_CONTAINER']['openContentInfo'](item.room); return; } var sessionBase = 'http://www.google.com/events/io/2011/sessions.html'; var now = new Date(); var may11 = new Date('May 11, 2011'); var day = now < may11 ? 10 : 11; var type = item.type; var id = item.id; var title = item.title; var content = ['<div class="infowindow">']; var sessions = []; var empty = true; if (item.type == 'session') { if (day == 10) { content.push('<h3>' + title + ' - Tuesday May 10</h3>'); } else { content.push('<h3>' + title + ' - Wednesday May 11</h3>'); } for (var i = 0, session; session = this.sessionItems_[i]; i++) { if (session.sessionRoom == item.room && session.sessionDay == day) { sessions.push(session); empty = false; } } sessions.sort(this.sortSessions_); for (var i = 0, session; session = sessions[i]; i++) { content.push('<div class="session"><div class="session-time">' + session.sessionTime + '</div><div class="session-title"><a href="' + session.sessionUrl + '">' + session.sessionTitle + '</a></div></div>'); } } if (item.type == 'sandbox') { var sandboxName; for (var i = 0, sandbox; sandbox = this.sandboxItems_[i]; i++) { if (sandbox.sessionRoom == item.room) { if (!sandboxName) { sandboxName = sandbox.pod; content.push('<h3>' + sandbox.pod + '</h3>'); content.push('<div class="sandbox">'); } content.push('<div class="sandbox-items"><a href="http://' + sandbox.companyUrl + '">' + sandbox.companyName + '</a></div>'); empty = false; } } content.push('</div>'); empty = false; } if (empty) { return; } content.push('</div>'); var pos = new google.maps.LatLng(item.lat, item.lng); if (!this.infoWindow_) { this.infoWindow_ = new google.maps.InfoWindow(); } this.infoWindow_.setContent(content.join('')); this.infoWindow_.setPosition(pos); this.infoWindow_.open(this.map_); }; /** * A custom sort function to sort the sessions by start time. * * @param {string} a SessionA<enter description here>. * @param {string} b SessionB. * @return {boolean} True if sessionA is after sessionB. */ IoMap.prototype.sortSessions_ = function(a, b) { var aStart = parseInt(a.sessionStart.replace(':', ''), 10); var bStart = parseInt(b.sessionStart.replace(':', ''), 10); return aStart > bStart; }; /** * Adds all overlays (markers, labels) to the map. */ IoMap.prototype.addMapContent_ = function() { if (!this.ready_) { return; } for (var i = 0, level; level = this.LEVELS_[i]; i++) { var floor = this.floors_[i]; var locations = this.LOCATIONS_['LEVEL' + level]; for (var roomId in locations) { var room = locations[roomId]; if (room.room == undefined) { room.room = roomId; } if (room.type != 'label') { var marker = this.createContentMarker_(room); floor.addOverlay(marker); room.marker_ = marker; } var label = this.createContentLabel_(room); floor.addOverlay(label); } } }; /** * Gets the correct tile url for the coordinates and zoom. * * @param {google.maps.Point} coord The coordinate of the tile. * @param {Number} zoom The current zoom level. * @return {string} The url to the tile. */ IoMap.prototype.getTileUrl = function(coord, zoom) { // Ensure that the requested resolution exists for this tile layer. if (this.MIN_ZOOM_ > zoom || zoom > this.MAX_ZOOM_) { return ''; } // Ensure that the requested tile x,y exists. if ((this.RESOLUTION_BOUNDS_[zoom][0][0] > coord.x || coord.x > this.RESOLUTION_BOUNDS_[zoom][0][1]) || (this.RESOLUTION_BOUNDS_[zoom][1][0] > coord.y || coord.y > this.RESOLUTION_BOUNDS_[zoom][1][1])) { return ''; } var template = this.TILE_TEMPLATE_URL_; if (16 <= zoom && zoom <= 17) { template = this.SIMPLE_TILE_TEMPLATE_URL_; } return template .replace('{L}', /** @type string */(this.get('level'))) .replace('{Z}', /** @type string */(zoom)) .replace('{X}', /** @type string */(coord.x)) .replace('{Y}', /** @type string */(coord.y)); }; /** * Add the floor overlay to the map. * * @private */ IoMap.prototype.addMapOverlay_ = function() { var that = this; var overlay = new google.maps.ImageMapType({ getTileUrl: function(coord, zoom) { return that.getTileUrl(coord, zoom); }, tileSize: new google.maps.Size(256, 256) }); google.maps.event.addListener(this, 'level_changed', function() { var overlays = that.map_.overlayMapTypes; if (overlays.length) { overlays.removeAt(0); } overlays.push(overlay); }); }; /** * All the features of the map. * @type {Object.<string, Object.<string, Object.<string, *>>>} */ IoMap.prototype.LOCATIONS_ = { 'LEVEL1': { 'northentrance': { lat: 37.78381535905965, lng: -122.40362226963043, title: 'Entrance', type: 'label', labelColor: '#006600', labelAlign: 'left', labelSize: 10 }, 'eastentrance': { lat: 37.78328434094279, lng: -122.40319311618805, title: 'Entrance', type: 'label', labelColor: '#006600', labelAlign: 'left', labelSize: 10 }, 'lunchroom': { lat: 37.783112633669575, lng: -122.40407556295395, title: 'Lunch Room' }, 'restroom1a': { lat: 37.78372420652042, lng: -122.40396961569786, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'elevator1a': { lat: 37.783669090977035, lng: -122.40389987826347, icon: 'elevator', type: 'inactive', title: 'Elevators', suppressLabel: true }, 'gearpickup': { lat: 37.78367863020862, lng: -122.4037617444992, title: 'Gear Pickup', type: 'label' }, 'checkin': { lat: 37.78334369645064, lng: -122.40335404872894, title: 'Check In', type: 'label' }, 'escalators1': { lat: 37.78353872135503, lng: -122.40336209535599, title: 'Escalators', type: 'label', labelAlign: 'left' } }, 'LEVEL2': { 'escalators2': { lat: 37.78353872135503, lng: -122.40336209535599, title: 'Escalators', type: 'label', labelAlign: 'left', labelMinZoom: 19 }, 'press': { lat: 37.78316774962791, lng: -122.40360751748085, title: 'Press Room', type: 'label' }, 'restroom2a': { lat: 37.7835334217721, lng: -122.40386635065079, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'restroom2b': { lat: 37.78250317562106, lng: -122.40423113107681, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'elevator2a': { lat: 37.783669090977035, lng: -122.40389987826347, icon: 'elevator', type: 'inactive', title: 'Elevators', suppressLabel: true }, '1': { lat: 37.78346240732338, lng: -122.40415401756763, icon: 'media', title: 'Room 1', type: 'session', room: '1' }, '2': { lat: 37.78335005596647, lng: -122.40431495010853, icon: 'media', title: 'Room 2', type: 'session', room: '2' }, '3': { lat: 37.783215446097124, lng: -122.404490634799, icon: 'media', title: 'Room 3', type: 'session', room: '3' }, '4': { lat: 37.78332461789977, lng: -122.40381203591824, icon: 'media', title: 'Room 4', type: 'session', room: '4' }, '5': { lat: 37.783186828219335, lng: -122.4039850383997, icon: 'media', title: 'Room 5', type: 'session', room: '5' }, '6': { lat: 37.783013000871364, lng: -122.40420497953892, icon: 'media', title: 'Room 6', type: 'session', room: '6' }, '7': { lat: 37.7828783903882, lng: -122.40438133478165, icon: 'media', title: 'Room 7', type: 'session', room: '7' }, '8': { lat: 37.78305009820564, lng: -122.40378588438034, icon: 'media', title: 'Room 8', type: 'session', room: '8' }, '9': { lat: 37.78286673120095, lng: -122.40402393043041, icon: 'media', title: 'Room 9', type: 'session', room: '9' }, '10': { lat: 37.782719401312626, lng: -122.40420028567314, icon: 'media', title: 'Room 10', type: 'session', room: '10' }, 'appengine': { lat: 37.783362774996625, lng: -122.40335941314697, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'App Engine' }, 'chrome': { lat: 37.783730566003555, lng: -122.40378990769386, type: 'sandbox', icon: 'generic', title: 'Chrome' }, 'googleapps': { lat: 37.783303419504094, lng: -122.40320384502411, type: 'sandbox', icon: 'generic', labelMinZoom: 19, title: 'Apps' }, 'geo': { lat: 37.783365954753805, lng: -122.40314483642578, type: 'sandbox', icon: 'generic', labelMinZoom: 19, title: 'Geo' }, 'accessibility': { lat: 37.783414711013485, lng: -122.40342646837234, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'Accessibility' }, 'developertools': { lat: 37.783457107734876, lng: -122.40347877144814, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'Dev Tools' }, 'commerce': { lat: 37.78349102509448, lng: -122.40351900458336, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'Commerce' }, 'youtube': { lat: 37.783537661438515, lng: -122.40358605980873, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'YouTube' }, 'officehoursfloor2a': { lat: 37.78249045644304, lng: -122.40410104393959, title: 'Office Hours', type: 'label' }, 'officehoursfloor2': { lat: 37.78266852473624, lng: -122.40387573838234, title: 'Office Hours', type: 'label' }, 'officehoursfloor2b': { lat: 37.782844472747406, lng: -122.40365579724312, title: 'Office Hours', type: 'label' } }, 'LEVEL3': { 'escalators3': { lat: 37.78353872135503, lng: -122.40336209535599, title: 'Escalators', type: 'label', labelAlign: 'left' }, 'restroom3a': { lat: 37.78372420652042, lng: -122.40396961569786, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'restroom3b': { lat: 37.78250317562106, lng: -122.40423113107681, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'elevator3a': { lat: 37.783669090977035, lng: -122.40389987826347, icon: 'elevator', type: 'inactive', title: 'Elevators', suppressLabel: true }, 'keynote': { lat: 37.783250423488326, lng: -122.40417748689651, icon: 'media', title: 'Keynote', type: 'label' }, '11': { lat: 37.78283069370135, lng: -122.40408763289452, icon: 'media', title: 'Room 11', type: 'session', room: '11' }, 'googletv': { lat: 37.7837125474666, lng: -122.40362092852592, type: 'sandbox', icon: 'generic', title: 'Google TV' }, 'android': { lat: 37.783530242022124, lng: -122.40358874201775, type: 'sandbox', icon: 'generic', title: 'Android' }, 'officehoursfloor3': { lat: 37.782843412820846, lng: -122.40365579724312, title: 'Office Hours', type: 'label' }, 'officehoursfloor3a': { lat: 37.78267170452323, lng: -122.40387842059135, title: 'Office Hours', type: 'label' } } }; google.maps.event.addDomListener(window, 'load', function() { window['IoMap'] = new IoMap(); });
JavaScript
function upload(){ getFS(function(fs){ fs.root.getFile('items.dat', {create:true}, function(fileEntry) { fileEntry.file(function(file) { var reader = new FileReader(); reader.onloadend = function(e) { var data = encrypt(this.result); $.post("http://cs.uwindsor.ca/~drouill8/311app/upload.php", {data:data}, function(data) { console.log("xhr response: "+data); }); } reader.readAsText(file); }); }); }); } getFS(function(fs){ var ul = $('#items')[0]; for (var i = 0; i < items.length; ++i) { var d = document.createElement('li'); d.innerText = items[i].name; /*Add css class based on JSON*/ for(var c in items[i].colrs) { d.classList.add(c); d.innerHTML += '<img src="circle_' + c + '.png" alt="blue" />'; } d.id = i; d.addEventListener("click",function(e) { that = this; fs.root.getFile('items.dat', {create: true}, function(fileEntry) { fileEntry.createWriter(function(fileWriter) { fileWriter.seek(fileWriter.length); var bb = new window.WebKitBlobBuilder(); var item = items[that.id]; var purch = new Purchase(item.id,item.name,item.colrs); var money = parseFloat(localStorage.getItem("money")) + item.price; var receipts = parseInt(localStorage.getItem("receipts")) + 1; money = money.toFixed(2); localStorage.setItem("receipts",receipts); localStorage.setItem("money",money); $('#receipts')[0].innerText = localStorage.getItem("receipts"); $('#money')[0].innerText = "$" + localStorage.getItem("money"); bb.append(JSON.stringify(purch)+"\n"); fileWriter.write(bb.getBlob('text/plain')); upload(); }, errorHandler); }, errorHandler); },false); ul.appendChild(d); } //Add icon based on css class /*$('.yellow').append('<li><img src="circle_yellow.png" alt="yellow" /></li>'); $('.green').append('<li><img src="circle_green.png" alt="green" /></li>'); $('.blue').append('<li><img src="circle_blue.png" alt="blue" /></li>'); $('.orange').append('<li><img src="circle_orange.png" alt="orange" /></li>'); $('.red').append('<li><img src="circle_red.png" alt="red" /></li>');*/ }); getFS(function(fs){ var clear = $("#clearLog")[0]; clear.addEventListener("click", function() { fs.root.getFile('items.dat', {create:true}, function(fe) { fe.remove(function() { console.log("File Deleted"); },errorHandler); }, errorHandler); localStorage.setItem("receipts",0); localStorage.setItem("money",0); $('#receipts')[0].innerText = localStorage.getItem("receipts"); $('#money')[0].innerText = "$" + localStorage.getItem("money"); },false); }); $('#validReset')[0].addEventListener("click",function(){ localStorage.setItem("receipts",0); localStorage.setItem("money",0); $('#receipts')[0].innerText = localStorage.getItem("receipts"); $('#money')[0].innerText = "$" + localStorage.getItem("money"); },false); if(localStorage.getItem("receipts") == null) { localStorage.setItem("receipts",0); } if(localStorage.getItem("money") == null) { localStorage.setItem("money",0); } $('#receipts')[0].innerText = localStorage.getItem("receipts"); $('#money')[0].innerText = "$" + localStorage.getItem("money"); $('#to').datetimepicker({ampm:true}); $('#from').datetimepicker({ampm:true});
JavaScript
function getLogTR(purch) { var tr = document.createElement('tr'); var td_name = document.createElement('td'); var td_colr = document.createElement('td'); var td_date = document.createElement('td'); var date = new Date(purch.d); td_name.innerText = purch.name; td_colr.innerText = getColr(purch.colr); td_date.innerText = getDate(date) + " " + getTime(date); tr.appendChild(td_name); tr.appendChild(td_colr); tr.appendChild(td_date); return tr; } getFS(function(fs) { var table = $("#items")[0]; fs.root.getFile('items.dat', {create:true}, function(fileEntry) { fileEntry.file(function(file) { var reader = new FileReader(); reader.onloadend = function(e) { var purchs = this.result.split('\n'); for (var i in purchs){ if ( purchs[i] != '' ) { var purch = JSON.parse(purchs[i]); table.appendChild(getLogTR(purch)); } } }; reader.readAsText(file); }, errorHandler); }, errorHandler); });
JavaScript
function getRange() { var from_str = $.getUrlVar('from').replace('+',' '); var to_str = $.getUrlVar('to').replace('+',' '); if (from_str == "") var from_date = new Date(0); else var from_date = new Date(from_str+" GMT-0500 (EST)"); if (to_str == "") var to_date = new Date("Dec 31 2500 23:59:00 GMT-0500 (EST)"); else { var to_date = new Date(to_str+" GMT-0500 (EST)"); to_date.setMinutes(to_date.getMinutes()+1); } return [from_date,to_date]; } function allMostColors(color_count) { var max_color = color_count['red']; for (var c in color_count) { if ( color_count[c] > max_color ) { max_color = color_count[c]; } } var max_colors = []; for (var c in color_count) { if ( color_count[c] == max_color) { max_colors.push(c); } } return max_colors; } function allLeastPurchs(purch_count) { var min_purch = purch_count[0]; for (var p in purch_count) { if ( purch_count[p] < min_purch ) { min_purch = purch_count[p]; } } var min_purchs = []; for (var p in purch_count) { if ( purch_count[p] == min_purch ) { min_purchs.push(p); } } return min_purchs; } function plotGraph(color_count) { var color_data = []; for (var c in color_count) { color_data.push({label:c,data:color_count[c],color:color_names[c]}); } $.plot($("#default"), color_data, { series: { pie: { show: true, radius: 1, label: { show: true, radius: 3/4, formatter: function(label, series){ return '<div style="font-weight:bold;font-size:13pt;text-align:center;padding:2px;color:black;">'+label+'<br/>'+Math.round(series.percent)+'%</div>'; }, background: { opacity: 0 } } } }, legend: { show: false } }); } getFS(function(fs) { var range = getRange(); var from_date = range[0]; var to_date = range[1]; var table = $("#items")[0]; var rngTag = $("#range")[0]; rngTag.innerText = "from " + getDate(from_date) + " " + getTime(from_date) + " to " + getDate(to_date) + " " +getTime(to_date); fs.root.getFile('items.dat', {create:true}, function(fileEntry) { fileEntry.file(function(file) { var reader = new FileReader(); reader.onloadend = function(e) { var purch_count = []; for (var i = 0; i < max_id+1; i++) { purch_count.push(0); } var color_count = {}; for (var i in color_names) { color_count[i] = 0; } var purchs = this.result.split('\n'); for (var i in purchs){ if ( purchs[i] != '' ) { var purch = JSON.parse(purchs[i]); var date = new Date(purch.d); if ( date <= to_date && date >= from_date ) { ++purch_count[purch.id]; for (var i in purch.colr){ color_count[i] += 1; } } } } var max_colors = allMostColors(color_count); var min_purchs = allLeastPurchs(purch_count); var specials = []; for (p in min_purchs) { for (c in max_colors) { var itm = items[min_purchs[p]]; var clr = max_colors[c]; if (itm.colrs[clr] != undefined){ specials.push(itm); break; } } } var ulSpcl = $('#specials')[0]; for (sp in specials) { var li = document.createElement("li"); li.innerText = specials[sp].name; ulSpcl.appendChild(li); } plotGraph(color_count); }; reader.readAsText(file); }, errorHandler); }, errorHandler); });
JavaScript
function errorHandler(e) { var msg = ''; switch (e.code) { case FileError.QUOTA_EXCEEDED_ERR: msg = 'QUOTA_EXCEEDED_ERR'; break; case FileError.NOT_FOUND_ERR: msg = 'NOT_FOUND_ERR'; break; case FileError.SECURITY_ERR: msg = 'SECURITY_ERR'; break; case FileError.INVALID_MODIFICATION_ERR: msg = 'INVALID_MODIFICATION_ERR'; break; case FileError.INVALID_STATE_ERR: msg = 'INVALID_STATE_ERR'; break; default: msg = 'Unknown Error'; break; }; console.log('Error: ' + msg); } function pad(n,c,l) { a = ""+n; while ( a.length < l ) a = c+a; return a; } function getTime(d) { t = ""; if ( d.getHours() < 13 ) t += d.getHours(); else t += (d.getHours()-12); t += ":" + pad(d.getMinutes(),"0",2); if ( d.getHours() < 13 ) t += 'am'; else t += 'pm'; return t; } function getDate(d) { t = ""; t += pad(d.getMonth()+1,"0",2); t += "/"; t += pad(d.getDate(),"0",2); t += "/"; t += d.getFullYear(); return t; } function getColr(c) { var out = ''; var q = [] for (var i in c) q.push(i); return q.join(', '); } function Purchase (id,name,colr,time) { this.id = id; this.d = new Date(); this.name = name; this.colr = colr; } function Item(id,price,name,colrs) { this.price = price; this.id = id; this.name = name; this.colrs = colrs; } function getFS(callback) { window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem; window.requestFileSystem(window.PERSISTENT, 5*1024*1024,function(fileSys) { callback(fileSys); },errorHandler); } function encrypt(str) { var key = "lkajbvkjaebrfjalskjdfhaklsdfhlaksjhdfjcnlakrnvkljashdkfjhalskdjnlakwefqwehfak"; var res = ""; for (var i in str) { res += String.fromCharCode(str.charCodeAt(i)^key.charCodeAt(i%key.length)) } return res; } $.extend( { getUrlVar: function(q,s){ s = s ? s : window.location.search; var re = new RegExp('&'+q+'(?:=([^&]*))?(?=&|$)','i'); return (s=s.replace(/^\?/,'&').match(re)) ? (typeof s[1] == 'undefined' ? '' : decodeURIComponent(s[1])) : ''; } }); color_names = { red:"#EE1D23", yellow:"#F2EB0B", green:"#11AE4B", pink:"#F59496", other:"#3DA9C4", } var max_id = -1; var items = []; items.push(new Item(++max_id,5.99,"Beef and Barley Stew",{red:1})); items.push(new Item(++max_id,7.49,"Potato Wedges",{red:1,green:1,yellow:1})); items.push(new Item(++max_id,3.99,"Stuffed Pork Loin",{red:1})); items.push(new Item(++max_id,5.49,"Beef Fajitas",{red:1,yellow:1,pink:1})); items.push(new Item(++max_id,6.99,"Stuffed Peppers",{red:1,green:1})); items.push(new Item(++max_id,2.49,"Healthy Caesar Salad",{red:1,green:1,pink:1})); items.push(new Item(++max_id,4.99,"Balsamic Glazed Brussels Sprouts",{green:1,yellow:1})); items.push(new Item(++max_id,9.49,"Baked Stuffed Tomatoes",{green:1})); items.push(new Item(++max_id,5.99,"Mixed Veggie Casserole",{green:1,yellow:1})); items.push(new Item(++max_id,6.49,"Mushroom Chili",{green:1,})); items.push(new Item(++max_id,3.99,"Eggplant Lasagna",{green:1,yellow:1,pink:1})); items.push(new Item(++max_id,1.49,"Garlic-Stuffed Sirloin Steak",{yellow:1})); items.push(new Item(++max_id,2.99,"Fruit salad with mojito dressing",{green:1,yellow:1})); items.push(new Item(++max_id,3.49,"Blueberry-lemon country cobbler",{yellow:1})); items.push(new Item(++max_id,4.99,"Grilled Cajun Bass",{red:1, yellow:1})); items.push(new Item(++max_id,5.49,"Shrimp and Veggie Creole Kebabs",{pink:1})); items.push(new Item(++max_id,6.99,"Turkey Mock Tacos",{pink:1})); items.push(new Item(++max_id,3.49,"Herbed Chicken Pasta Salad",{yellow:1,pink:1})); items.push(new Item(++max_id,4.99,"Chicken Fried Rice",{pink:1})); items.push(new Item(++max_id,9.49,"Banana Split ontop of a Pie",{other:1})); items.push(new Item(++max_id,0.99,"Glue",{other:1}));
JavaScript
/* * jQuery timepicker addon * By: Trent Richardson [http://trentrichardson.com] * Version 0.9.7 * Last Modified: 10/02/2011 * * Copyright 2011 Trent Richardson * Dual licensed under the MIT and GPL licenses. * http://trentrichardson.com/Impromptu/GPL-LICENSE.txt * http://trentrichardson.com/Impromptu/MIT-LICENSE.txt * * HERES THE CSS: * .ui-timepicker-div .ui-widget-header { margin-bottom: 8px; } * .ui-timepicker-div dl { text-align: left; } * .ui-timepicker-div dl dt { height: 25px; } * .ui-timepicker-div dl dd { margin: -25px 10px 10px 65px; } * .ui-timepicker-div td { font-size: 90%; } * .ui-tpicker-grid-label { background: none; border: none; margin: 0; padding: 0; } */ (function($) { $.extend($.ui, { timepicker: { version: "0.9.7" } }); /* Time picker manager. Use the singleton instance of this class, $.timepicker, to interact with the time picker. Settings for (groups of) time pickers are maintained in an instance object, allowing multiple different settings on the same page. */ function Timepicker() { this.regional = []; // Available regional settings, indexed by language code this.regional[''] = { // Default regional settings currentText: 'Now', closeText: 'Done', ampm: false, amNames: ['AM', 'A'], pmNames: ['PM', 'P'], timeFormat: 'hh:mm tt', timeSuffix: '', timeOnlyTitle: 'Choose Time', timeText: 'Time', hourText: 'Hour', minuteText: 'Minute', secondText: 'Second', millisecText: 'Millisecond', timezoneText: 'Time Zone' }; this._defaults = { // Global defaults for all the datetime picker instances showButtonPanel: true, timeOnly: false, showHour: true, showMinute: true, showSecond: false, showMillisec: false, showTimezone: false, showTime: true, stepHour: 0.05, stepMinute: 0.05, stepSecond: 0.05, stepMillisec: 0.5, hour: 0, minute: 0, second: 0, millisec: 0, timezone: '+0000', hourMin: 0, minuteMin: 0, secondMin: 0, millisecMin: 0, hourMax: 23, minuteMax: 59, secondMax: 59, millisecMax: 999, minDateTime: null, maxDateTime: null, onSelect: null, hourGrid: 0, minuteGrid: 0, secondGrid: 0, millisecGrid: 0, alwaysSetTime: true, separator: ' ', altFieldTimeOnly: true, showTimepicker: true, timezoneIso8609: false, timezoneList: null }; $.extend(this._defaults, this.regional['']); } $.extend(Timepicker.prototype, { $input: null, $altInput: null, $timeObj: null, inst: null, hour_slider: null, minute_slider: null, second_slider: null, millisec_slider: null, timezone_select: null, hour: 0, minute: 0, second: 0, millisec: 0, timezone: '+0000', hourMinOriginal: null, minuteMinOriginal: null, secondMinOriginal: null, millisecMinOriginal: null, hourMaxOriginal: null, minuteMaxOriginal: null, secondMaxOriginal: null, millisecMaxOriginal: null, ampm: '', formattedDate: '', formattedTime: '', formattedDateTime: '', timezoneList: null, /* Override the default settings for all instances of the time picker. @param settings object - the new settings to use as defaults (anonymous object) @return the manager object */ setDefaults: function(settings) { extendRemove(this._defaults, settings || {}); return this; }, //######################################################################## // Create a new Timepicker instance //######################################################################## _newInst: function($input, o) { var tp_inst = new Timepicker(), inlineSettings = {}; for (var attrName in this._defaults) { var attrValue = $input.attr('time:' + attrName); if (attrValue) { try { inlineSettings[attrName] = eval(attrValue); } catch (err) { inlineSettings[attrName] = attrValue; } } } tp_inst._defaults = $.extend({}, this._defaults, inlineSettings, o, { beforeShow: function(input, dp_inst) { if ($.isFunction(o.beforeShow)) o.beforeShow(input, dp_inst, tp_inst); }, onChangeMonthYear: function(year, month, dp_inst) { // Update the time as well : this prevents the time from disappearing from the $input field. tp_inst._updateDateTime(dp_inst); if ($.isFunction(o.onChangeMonthYear)) o.onChangeMonthYear.call($input[0], year, month, dp_inst, tp_inst); }, onClose: function(dateText, dp_inst) { if (tp_inst.timeDefined === true && $input.val() != '') tp_inst._updateDateTime(dp_inst); if ($.isFunction(o.onClose)) o.onClose.call($input[0], dateText, dp_inst, tp_inst); }, timepicker: tp_inst // add timepicker as a property of datepicker: $.datepicker._get(dp_inst, 'timepicker'); }); tp_inst.amNames = $.map(tp_inst._defaults.amNames, function(val) { return val.toUpperCase() }); tp_inst.pmNames = $.map(tp_inst._defaults.pmNames, function(val) { return val.toUpperCase() }); if (tp_inst._defaults.timezoneList === null) { var timezoneList = []; for (var i = -11; i <= 12; i++) timezoneList.push((i >= 0 ? '+' : '-') + ('0' + Math.abs(i).toString()).slice(-2) + '00'); if (tp_inst._defaults.timezoneIso8609) timezoneList = $.map(timezoneList, function(val) { return val == '+0000' ? 'Z' : (val.substring(0, 3) + ':' + val.substring(3)); }); tp_inst._defaults.timezoneList = timezoneList; } tp_inst.hour = tp_inst._defaults.hour; tp_inst.minute = tp_inst._defaults.minute; tp_inst.second = tp_inst._defaults.second; tp_inst.millisec = tp_inst._defaults.millisec; tp_inst.ampm = ''; tp_inst.$input = $input; if (o.altField) tp_inst.$altInput = $(o.altField) .css({ cursor: 'pointer' }) .focus(function(){ $input.trigger("focus"); }); if(tp_inst._defaults.minDate==0 || tp_inst._defaults.minDateTime==0) { tp_inst._defaults.minDate=new Date(); } if(tp_inst._defaults.maxDate==0 || tp_inst._defaults.maxDateTime==0) { tp_inst._defaults.maxDate=new Date(); } // datepicker needs minDate/maxDate, timepicker needs minDateTime/maxDateTime.. if(tp_inst._defaults.minDate !== undefined && tp_inst._defaults.minDate instanceof Date) tp_inst._defaults.minDateTime = new Date(tp_inst._defaults.minDate.getTime()); if(tp_inst._defaults.minDateTime !== undefined && tp_inst._defaults.minDateTime instanceof Date) tp_inst._defaults.minDate = new Date(tp_inst._defaults.minDateTime.getTime()); if(tp_inst._defaults.maxDate !== undefined && tp_inst._defaults.maxDate instanceof Date) tp_inst._defaults.maxDateTime = new Date(tp_inst._defaults.maxDate.getTime()); if(tp_inst._defaults.maxDateTime !== undefined && tp_inst._defaults.maxDateTime instanceof Date) tp_inst._defaults.maxDate = new Date(tp_inst._defaults.maxDateTime.getTime()); return tp_inst; }, //######################################################################## // add our sliders to the calendar //######################################################################## _addTimePicker: function(dp_inst) { var currDT = (this.$altInput && this._defaults.altFieldTimeOnly) ? this.$input.val() + ' ' + this.$altInput.val() : this.$input.val(); this.timeDefined = this._parseTime(currDT); this._limitMinMaxDateTime(dp_inst, false); this._injectTimePicker(); }, //######################################################################## // parse the time string from input value or _setTime //######################################################################## _parseTime: function(timeString, withDate) { var regstr = this._defaults.timeFormat.toString() .replace(/h{1,2}/ig, '(\\d?\\d)') .replace(/m{1,2}/ig, '(\\d?\\d)') .replace(/s{1,2}/ig, '(\\d?\\d)') .replace(/l{1}/ig, '(\\d?\\d?\\d)') .replace(/t{1,2}/ig, this._getPatternAmpm()) .replace(/z{1}/ig, '(z|[-+]\\d\\d:?\\d\\d)?') .replace(/\s/g, '\\s?') + this._defaults.timeSuffix + '$', order = this._getFormatPositions(), ampm = '', treg; if (!this.inst) this.inst = $.datepicker._getInst(this.$input[0]); if (withDate || !this._defaults.timeOnly) { // the time should come after x number of characters and a space. // x = at least the length of text specified by the date format var dp_dateFormat = $.datepicker._get(this.inst, 'dateFormat'); // escape special regex characters in the seperator var specials = new RegExp("[.*+?|()\\[\\]{}\\\\]", "g"); regstr = '.{' + dp_dateFormat.length + ',}' + this._defaults.separator.replace(specials, "\\$&") + regstr; } treg = timeString.match(new RegExp(regstr, 'i')); if (treg) { if (order.t !== -1) { if (treg[order.t] === undefined || treg[order.t].length === 0) { ampm = ''; this.ampm = ''; } else { ampm = $.inArray(treg[order.t].toUpperCase(), this.amNames) !== -1 ? 'AM' : 'PM'; this.ampm = this._defaults[ampm == 'AM' ? 'amNames' : 'pmNames'][0]; } } if (order.h !== -1) { if (ampm == 'AM' && treg[order.h] == '12') this.hour = 0; // 12am = 0 hour else if (ampm == 'PM' && treg[order.h] != '12') this.hour = (parseFloat(treg[order.h]) + 12).toFixed(0); // 12pm = 12 hour, any other pm = hour + 12 else this.hour = Number(treg[order.h]); } if (order.m !== -1) this.minute = Number(treg[order.m]); if (order.s !== -1) this.second = Number(treg[order.s]); if (order.l !== -1) this.millisec = Number(treg[order.l]); if (order.z !== -1 && treg[order.z] !== undefined) { var tz = treg[order.z].toUpperCase(); switch (tz.length) { case 1: // Z tz = this._defaults.timezoneIso8609 ? 'Z' : '+0000'; break; case 5: // +hhmm if (this._defaults.timezoneIso8609) tz = tz.substring(1) == '0000' ? 'Z' : tz.substring(0, 3) + ':' + tz.substring(3); break; case 6: // +hh:mm if (!this._defaults.timezoneIso8609) tz = tz == 'Z' || tz.substring(1) == '00:00' ? '+0000' : tz.replace(/:/, ''); else if (tz.substring(1) == '00:00') tz = 'Z'; break; } this.timezone = tz; } return true; } return false; }, //######################################################################## // pattern for standard and localized AM/PM markers //######################################################################## _getPatternAmpm: function() { var markers = []; o = this._defaults; if (o.amNames) $.merge(markers, o.amNames); if (o.pmNames) $.merge(markers, o.pmNames); markers = $.map(markers, function(val) { return val.replace(/[.*+?|()\[\]{}\\]/g, '\\$&') }); return '(' + markers.join('|') + ')?'; }, //######################################################################## // figure out position of time elements.. cause js cant do named captures //######################################################################## _getFormatPositions: function() { var finds = this._defaults.timeFormat.toLowerCase().match(/(h{1,2}|m{1,2}|s{1,2}|l{1}|t{1,2}|z)/g), orders = { h: -1, m: -1, s: -1, l: -1, t: -1, z: -1 }; if (finds) for (var i = 0; i < finds.length; i++) if (orders[finds[i].toString().charAt(0)] == -1) orders[finds[i].toString().charAt(0)] = i + 1; return orders; }, //######################################################################## // generate and inject html for timepicker into ui datepicker //######################################################################## _injectTimePicker: function() { var $dp = this.inst.dpDiv, o = this._defaults, tp_inst = this, // Added by Peter Medeiros: // - Figure out what the hour/minute/second max should be based on the step values. // - Example: if stepMinute is 15, then minMax is 45. hourMax = (o.hourMax - ((o.hourMax - o.hourMin) % o.stepHour)).toFixed(0), minMax = (o.minuteMax - ((o.minuteMax - o.minuteMin) % o.stepMinute)).toFixed(0), secMax = (o.secondMax - ((o.secondMax - o.secondMin) % o.stepSecond)).toFixed(0), millisecMax = (o.millisecMax - ((o.millisecMax - o.millisecMin) % o.stepMillisec)).toFixed(0), dp_id = this.inst.id.toString().replace(/([^A-Za-z0-9_])/g, ''); // Prevent displaying twice //if ($dp.find("div#ui-timepicker-div-"+ dp_id).length === 0) { if ($dp.find("div#ui-timepicker-div-"+ dp_id).length === 0 && o.showTimepicker) { var noDisplay = ' style="display:none;"', html = '<div class="ui-timepicker-div" id="ui-timepicker-div-' + dp_id + '"><dl>' + '<dt class="ui_tpicker_time_label" id="ui_tpicker_time_label_' + dp_id + '"' + ((o.showTime) ? '' : noDisplay) + '>' + o.timeText + '</dt>' + '<dd class="ui_tpicker_time" id="ui_tpicker_time_' + dp_id + '"' + ((o.showTime) ? '' : noDisplay) + '></dd>' + '<dt class="ui_tpicker_hour_label" id="ui_tpicker_hour_label_' + dp_id + '"' + ((o.showHour) ? '' : noDisplay) + '>' + o.hourText + '</dt>', hourGridSize = 0, minuteGridSize = 0, secondGridSize = 0, millisecGridSize = 0, size; // Hours if (o.showHour && o.hourGrid > 0) { html += '<dd class="ui_tpicker_hour">' + '<div id="ui_tpicker_hour_' + dp_id + '"' + ((o.showHour) ? '' : noDisplay) + '></div>' + '<div style="padding-left: 1px"><table class="ui-tpicker-grid-label"><tr>'; for (var h = o.hourMin; h <= hourMax; h += parseInt(o.hourGrid,10)) { hourGridSize++; var tmph = (o.ampm && h > 12) ? h-12 : h; if (tmph < 10) tmph = '0' + tmph; if (o.ampm) { if (h == 0) tmph = 12 +'a'; else if (h < 12) tmph += 'a'; else tmph += 'p'; } html += '<td>' + tmph + '</td>'; } html += '</tr></table></div>' + '</dd>'; } else html += '<dd class="ui_tpicker_hour" id="ui_tpicker_hour_' + dp_id + '"' + ((o.showHour) ? '' : noDisplay) + '></dd>'; html += '<dt class="ui_tpicker_minute_label" id="ui_tpicker_minute_label_' + dp_id + '"' + ((o.showMinute) ? '' : noDisplay) + '>' + o.minuteText + '</dt>'; // Minutes if (o.showMinute && o.minuteGrid > 0) { html += '<dd class="ui_tpicker_minute ui_tpicker_minute_' + o.minuteGrid + '">' + '<div id="ui_tpicker_minute_' + dp_id + '"' + ((o.showMinute) ? '' : noDisplay) + '></div>' + '<div style="padding-left: 1px"><table class="ui-tpicker-grid-label"><tr>'; for (var m = o.minuteMin; m <= minMax; m += parseInt(o.minuteGrid,10)) { minuteGridSize++; html += '<td>' + ((m < 10) ? '0' : '') + m + '</td>'; } html += '</tr></table></div>' + '</dd>'; } else html += '<dd class="ui_tpicker_minute" id="ui_tpicker_minute_' + dp_id + '"' + ((o.showMinute) ? '' : noDisplay) + '></dd>'; // Seconds html += '<dt class="ui_tpicker_second_label" id="ui_tpicker_second_label_' + dp_id + '"' + ((o.showSecond) ? '' : noDisplay) + '>' + o.secondText + '</dt>'; if (o.showSecond && o.secondGrid > 0) { html += '<dd class="ui_tpicker_second ui_tpicker_second_' + o.secondGrid + '">' + '<div id="ui_tpicker_second_' + dp_id + '"' + ((o.showSecond) ? '' : noDisplay) + '></div>' + '<div style="padding-left: 1px"><table><tr>'; for (var s = o.secondMin; s <= secMax; s += parseInt(o.secondGrid,10)) { secondGridSize++; html += '<td>' + ((s < 10) ? '0' : '') + s + '</td>'; } html += '</tr></table></div>' + '</dd>'; } else html += '<dd class="ui_tpicker_second" id="ui_tpicker_second_' + dp_id + '"' + ((o.showSecond) ? '' : noDisplay) + '></dd>'; // Milliseconds html += '<dt class="ui_tpicker_millisec_label" id="ui_tpicker_millisec_label_' + dp_id + '"' + ((o.showMillisec) ? '' : noDisplay) + '>' + o.millisecText + '</dt>'; if (o.showMillisec && o.millisecGrid > 0) { html += '<dd class="ui_tpicker_millisec ui_tpicker_millisec_' + o.millisecGrid + '">' + '<div id="ui_tpicker_millisec_' + dp_id + '"' + ((o.showMillisec) ? '' : noDisplay) + '></div>' + '<div style="padding-left: 1px"><table><tr>'; for (var l = o.millisecMin; l <= millisecMax; l += parseInt(o.millisecGrid,10)) { millisecGridSize++; html += '<td>' + ((l < 10) ? '0' : '') + s + '</td>'; } html += '</tr></table></div>' + '</dd>'; } else html += '<dd class="ui_tpicker_millisec" id="ui_tpicker_millisec_' + dp_id + '"' + ((o.showMillisec) ? '' : noDisplay) + '></dd>'; // Timezone html += '<dt class="ui_tpicker_timezone_label" id="ui_tpicker_timezone_label_' + dp_id + '"' + ((o.showTimezone) ? '' : noDisplay) + '>' + o.timezoneText + '</dt>'; html += '<dd class="ui_tpicker_timezone" id="ui_tpicker_timezone_' + dp_id + '"' + ((o.showTimezone) ? '' : noDisplay) + '></dd>'; html += '</dl></div>'; $tp = $(html); // if we only want time picker... if (o.timeOnly === true) { $tp.prepend( '<div class="ui-widget-header ui-helper-clearfix ui-corner-all">' + '<div class="ui-datepicker-title">' + o.timeOnlyTitle + '</div>' + '</div>'); $dp.find('.ui-datepicker-header, .ui-datepicker-calendar').hide(); } this.hour_slider = $tp.find('#ui_tpicker_hour_'+ dp_id).slider({ orientation: "horizontal", value: this.hour, min: o.hourMin, max: hourMax, step: o.stepHour, slide: function(event, ui) { tp_inst.hour_slider.slider( "option", "value", ui.value); tp_inst._onTimeChange(); } }); // Updated by Peter Medeiros: // - Pass in Event and UI instance into slide function this.minute_slider = $tp.find('#ui_tpicker_minute_'+ dp_id).slider({ orientation: "horizontal", value: this.minute, min: o.minuteMin, max: minMax, step: o.stepMinute, slide: function(event, ui) { // update the global minute slider instance value with the current slider value tp_inst.minute_slider.slider( "option", "value", ui.value); tp_inst._onTimeChange(); } }); this.second_slider = $tp.find('#ui_tpicker_second_'+ dp_id).slider({ orientation: "horizontal", value: this.second, min: o.secondMin, max: secMax, step: o.stepSecond, slide: function(event, ui) { tp_inst.second_slider.slider( "option", "value", ui.value); tp_inst._onTimeChange(); } }); this.millisec_slider = $tp.find('#ui_tpicker_millisec_'+ dp_id).slider({ orientation: "horizontal", value: this.millisec, min: o.millisecMin, max: millisecMax, step: o.stepMillisec, slide: function(event, ui) { tp_inst.millisec_slider.slider( "option", "value", ui.value); tp_inst._onTimeChange(); } }); this.timezone_select = $tp.find('#ui_tpicker_timezone_'+ dp_id).append('<select></select>').find("select"); $.fn.append.apply(this.timezone_select, $.map(o.timezoneList, function(val, idx) { return $("<option />") .val(typeof val == "object" ? val.value : val) .text(typeof val == "object" ? val.label : val); }) ); this.timezone_select.val((typeof this.timezone != "undefined" && this.timezone != null && this.timezone != "") ? this.timezone : o.timezone); this.timezone_select.change(function() { tp_inst._onTimeChange(); }); // Add grid functionality if (o.showHour && o.hourGrid > 0) { size = 100 * hourGridSize * o.hourGrid / (hourMax - o.hourMin); $tp.find(".ui_tpicker_hour table").css({ width: size + "%", marginLeft: (size / (-2 * hourGridSize)) + "%", borderCollapse: 'collapse' }).find("td").each( function(index) { $(this).click(function() { var h = $(this).html(); if(o.ampm) { var ap = h.substring(2).toLowerCase(), aph = parseInt(h.substring(0,2), 10); if (ap == 'a') { if (aph == 12) h = 0; else h = aph; } else if (aph == 12) h = 12; else h = aph + 12; } tp_inst.hour_slider.slider("option", "value", h); tp_inst._onTimeChange(); tp_inst._onSelectHandler(); }).css({ cursor: 'pointer', width: (100 / hourGridSize) + '%', textAlign: 'center', overflow: 'hidden' }); }); } if (o.showMinute && o.minuteGrid > 0) { size = 100 * minuteGridSize * o.minuteGrid / (minMax - o.minuteMin); $tp.find(".ui_tpicker_minute table").css({ width: size + "%", marginLeft: (size / (-2 * minuteGridSize)) + "%", borderCollapse: 'collapse' }).find("td").each(function(index) { $(this).click(function() { tp_inst.minute_slider.slider("option", "value", $(this).html()); tp_inst._onTimeChange(); tp_inst._onSelectHandler(); }).css({ cursor: 'pointer', width: (100 / minuteGridSize) + '%', textAlign: 'center', overflow: 'hidden' }); }); } if (o.showSecond && o.secondGrid > 0) { $tp.find(".ui_tpicker_second table").css({ width: size + "%", marginLeft: (size / (-2 * secondGridSize)) + "%", borderCollapse: 'collapse' }).find("td").each(function(index) { $(this).click(function() { tp_inst.second_slider.slider("option", "value", $(this).html()); tp_inst._onTimeChange(); tp_inst._onSelectHandler(); }).css({ cursor: 'pointer', width: (100 / secondGridSize) + '%', textAlign: 'center', overflow: 'hidden' }); }); } if (o.showMillisec && o.millisecGrid > 0) { $tp.find(".ui_tpicker_millisec table").css({ width: size + "%", marginLeft: (size / (-2 * millisecGridSize)) + "%", borderCollapse: 'collapse' }).find("td").each(function(index) { $(this).click(function() { tp_inst.millisec_slider.slider("option", "value", $(this).html()); tp_inst._onTimeChange(); tp_inst._onSelectHandler(); }).css({ cursor: 'pointer', width: (100 / millisecGridSize) + '%', textAlign: 'center', overflow: 'hidden' }); }); } var $buttonPanel = $dp.find('.ui-datepicker-buttonpane'); if ($buttonPanel.length) $buttonPanel.before($tp); else $dp.append($tp); this.$timeObj = $tp.find('#ui_tpicker_time_'+ dp_id); if (this.inst !== null) { var timeDefined = this.timeDefined; this._onTimeChange(); this.timeDefined = timeDefined; } //Emulate datepicker onSelect behavior. Call on slidestop. var onSelectDelegate = function() { tp_inst._onSelectHandler(); }; this.hour_slider.bind('slidestop',onSelectDelegate); this.minute_slider.bind('slidestop',onSelectDelegate); this.second_slider.bind('slidestop',onSelectDelegate); this.millisec_slider.bind('slidestop',onSelectDelegate); } }, //######################################################################## // This function tries to limit the ability to go outside the // min/max date range //######################################################################## _limitMinMaxDateTime: function(dp_inst, adjustSliders){ var o = this._defaults, dp_date = new Date(dp_inst.selectedYear, dp_inst.selectedMonth, dp_inst.selectedDay); if(!this._defaults.showTimepicker) return; // No time so nothing to check here if($.datepicker._get(dp_inst, 'minDateTime') !== null && $.datepicker._get(dp_inst, 'minDateTime') !== undefined && dp_date){ var minDateTime = $.datepicker._get(dp_inst, 'minDateTime'), minDateTimeDate = new Date(minDateTime.getFullYear(), minDateTime.getMonth(), minDateTime.getDate(), 0, 0, 0, 0); if(this.hourMinOriginal === null || this.minuteMinOriginal === null || this.secondMinOriginal === null || this.millisecMinOriginal === null){ this.hourMinOriginal = o.hourMin; this.minuteMinOriginal = o.minuteMin; this.secondMinOriginal = o.secondMin; this.millisecMinOriginal = o.millisecMin; } if(dp_inst.settings.timeOnly || minDateTimeDate.getTime() == dp_date.getTime()) { this._defaults.hourMin = minDateTime.getHours(); if (this.hour <= this._defaults.hourMin) { this.hour = this._defaults.hourMin; this._defaults.minuteMin = minDateTime.getMinutes(); if (this.minute <= this._defaults.minuteMin) { this.minute = this._defaults.minuteMin; this._defaults.secondMin = minDateTime.getSeconds(); } else if (this.second <= this._defaults.secondMin){ this.second = this._defaults.secondMin; this._defaults.millisecMin = minDateTime.getMilliseconds(); } else { if(this.millisec < this._defaults.millisecMin) this.millisec = this._defaults.millisecMin; this._defaults.millisecMin = this.millisecMinOriginal; } } else { this._defaults.minuteMin = this.minuteMinOriginal; this._defaults.secondMin = this.secondMinOriginal; this._defaults.millisecMin = this.millisecMinOriginal; } }else{ this._defaults.hourMin = this.hourMinOriginal; this._defaults.minuteMin = this.minuteMinOriginal; this._defaults.secondMin = this.secondMinOriginal; this._defaults.millisecMin = this.millisecMinOriginal; } } if($.datepicker._get(dp_inst, 'maxDateTime') !== null && $.datepicker._get(dp_inst, 'maxDateTime') !== undefined && dp_date){ var maxDateTime = $.datepicker._get(dp_inst, 'maxDateTime'), maxDateTimeDate = new Date(maxDateTime.getFullYear(), maxDateTime.getMonth(), maxDateTime.getDate(), 0, 0, 0, 0); if(this.hourMaxOriginal === null || this.minuteMaxOriginal === null || this.secondMaxOriginal === null){ this.hourMaxOriginal = o.hourMax; this.minuteMaxOriginal = o.minuteMax; this.secondMaxOriginal = o.secondMax; this.millisecMaxOriginal = o.millisecMax; } if(dp_inst.settings.timeOnly || maxDateTimeDate.getTime() == dp_date.getTime()){ this._defaults.hourMax = maxDateTime.getHours(); if (this.hour >= this._defaults.hourMax) { this.hour = this._defaults.hourMax; this._defaults.minuteMax = maxDateTime.getMinutes(); if (this.minute >= this._defaults.minuteMax) { this.minute = this._defaults.minuteMax; this._defaults.secondMax = maxDateTime.getSeconds(); } else if (this.second >= this._defaults.secondMax) { this.second = this._defaults.secondMax; this._defaults.millisecMax = maxDateTime.getMilliseconds(); } else { if(this.millisec > this._defaults.millisecMax) this.millisec = this._defaults.millisecMax; this._defaults.millisecMax = this.millisecMaxOriginal; } } else { this._defaults.minuteMax = this.minuteMaxOriginal; this._defaults.secondMax = this.secondMaxOriginal; this._defaults.millisecMax = this.millisecMaxOriginal; } }else{ this._defaults.hourMax = this.hourMaxOriginal; this._defaults.minuteMax = this.minuteMaxOriginal; this._defaults.secondMax = this.secondMaxOriginal; this._defaults.millisecMax = this.millisecMaxOriginal; } } if(adjustSliders !== undefined && adjustSliders === true){ var hourMax = (this._defaults.hourMax - ((this._defaults.hourMax - this._defaults.hourMin) % this._defaults.stepHour)).toFixed(0), minMax = (this._defaults.minuteMax - ((this._defaults.minuteMax - this._defaults.minuteMin) % this._defaults.stepMinute)).toFixed(0), secMax = (this._defaults.secondMax - ((this._defaults.secondMax - this._defaults.secondMin) % this._defaults.stepSecond)).toFixed(0), millisecMax = (this._defaults.millisecMax - ((this._defaults.millisecMax - this._defaults.millisecMin) % this._defaults.stepMillisec)).toFixed(0); if(this.hour_slider) this.hour_slider.slider("option", { min: this._defaults.hourMin, max: hourMax }).slider('value', this.hour); if(this.minute_slider) this.minute_slider.slider("option", { min: this._defaults.minuteMin, max: minMax }).slider('value', this.minute); if(this.second_slider) this.second_slider.slider("option", { min: this._defaults.secondMin, max: secMax }).slider('value', this.second); if(this.millisec_slider) this.millisec_slider.slider("option", { min: this._defaults.millisecMin, max: millisecMax }).slider('value', this.millisec); } }, //######################################################################## // when a slider moves, set the internal time... // on time change is also called when the time is updated in the text field //######################################################################## _onTimeChange: function() { var hour = (this.hour_slider) ? this.hour_slider.slider('value') : false, minute = (this.minute_slider) ? this.minute_slider.slider('value') : false, second = (this.second_slider) ? this.second_slider.slider('value') : false, millisec = (this.millisec_slider) ? this.millisec_slider.slider('value') : false, timezone = (this.timezone_select) ? this.timezone_select.val() : false, o = this._defaults; if (typeof(hour) == 'object') hour = false; if (typeof(minute) == 'object') minute = false; if (typeof(second) == 'object') second = false; if (typeof(millisec) == 'object') millisec = false; if (typeof(timezone) == 'object') timezone = false; if (hour !== false) hour = parseInt(hour,10); if (minute !== false) minute = parseInt(minute,10); if (second !== false) second = parseInt(second,10); if (millisec !== false) millisec = parseInt(millisec,10); var ampm = o[hour < 12 ? 'amNames' : 'pmNames'][0]; // If the update was done in the input field, the input field should not be updated. // If the update was done using the sliders, update the input field. var hasChanged = (hour != this.hour || minute != this.minute || second != this.second || millisec != this.millisec || (this.ampm.length > 0 && (hour < 12) != ($.inArray(this.ampm.toUpperCase(), this.amNames) !== -1)) || timezone != this.timezone); if (hasChanged) { if (hour !== false)this.hour = hour; if (minute !== false) this.minute = minute; if (second !== false) this.second = second; if (millisec !== false) this.millisec = millisec; if (timezone !== false) this.timezone = timezone; if (!this.inst) this.inst = $.datepicker._getInst(this.$input[0]); this._limitMinMaxDateTime(this.inst, true); } if (o.ampm) this.ampm = ampm; this._formatTime(); if (this.$timeObj) this.$timeObj.text(this.formattedTime + o.timeSuffix); this.timeDefined = true; if (hasChanged) this._updateDateTime(); }, //######################################################################## // call custom onSelect. // bind to sliders slidestop, and grid click. //######################################################################## _onSelectHandler: function() { var onSelect = this._defaults.onSelect; var inputEl = this.$input ? this.$input[0] : null; if (onSelect && inputEl) { onSelect.apply(inputEl, [this.formattedDateTime, this]); } }, //######################################################################## // format the time all pretty... //######################################################################## _formatTime: function(time, format, ampm) { if (ampm == undefined) ampm = this._defaults.ampm; time = time || { hour: this.hour, minute: this.minute, second: this.second, millisec: this.millisec, ampm: this.ampm, timezone: this.timezone }; var tmptime = (format || this._defaults.timeFormat).toString(); var hour = parseInt(time.hour, 10); if (ampm) { if (!$.inArray(time.ampm.toUpperCase(), this.amNames) !== -1) hour = hour % 12; if (hour === 0) hour = 12; } tmptime = tmptime.replace(/(?:hh?|mm?|ss?|[tT]{1,2}|[lz])/g, function(match) { switch (match.toLowerCase()) { case 'hh': return ('0' + hour).slice(-2); case 'h': return hour; case 'mm': return ('0' + time.minute).slice(-2); case 'm': return time.minute; case 'ss': return ('0' + time.second).slice(-2); case 's': return time.second; case 'l': return ('00' + time.millisec).slice(-3); case 'z': return time.timezone; case 't': case 'tt': if (ampm) { var _ampm = time.ampm; if (match.length == 1) _ampm = _ampm.charAt(0); return match.charAt(0) == 'T' ? _ampm.toUpperCase() : _ampm.toLowerCase(); } return ''; } }); if (arguments.length) return tmptime; else this.formattedTime = tmptime; }, //######################################################################## // update our input with the new date time.. //######################################################################## _updateDateTime: function(dp_inst) { dp_inst = this.inst || dp_inst, dt = new Date(dp_inst.selectedYear, dp_inst.selectedMonth, dp_inst.selectedDay), dateFmt = $.datepicker._get(dp_inst, 'dateFormat'), formatCfg = $.datepicker._getFormatConfig(dp_inst), timeAvailable = dt !== null && this.timeDefined; this.formattedDate = $.datepicker.formatDate(dateFmt, (dt === null ? new Date() : dt), formatCfg); var formattedDateTime = this.formattedDate; if (dp_inst.lastVal !== undefined && (dp_inst.lastVal.length > 0 && this.$input.val().length === 0)) return; if (this._defaults.timeOnly === true) { formattedDateTime = this.formattedTime; } else if (this._defaults.timeOnly !== true && (this._defaults.alwaysSetTime || timeAvailable)) { formattedDateTime += this._defaults.separator + this.formattedTime + this._defaults.timeSuffix; } this.formattedDateTime = formattedDateTime; if(!this._defaults.showTimepicker) { this.$input.val(this.formattedDate); } else if (this.$altInput && this._defaults.altFieldTimeOnly === true) { this.$altInput.val(this.formattedTime); this.$input.val(this.formattedDate); } else if(this.$altInput) { this.$altInput.val(formattedDateTime); this.$input.val(formattedDateTime); } else { this.$input.val(formattedDateTime); } this.$input.trigger("change"); } }); $.fn.extend({ //######################################################################## // shorthand just to use timepicker.. //######################################################################## timepicker: function(o) { o = o || {}; var tmp_args = arguments; if (typeof o == 'object') tmp_args[0] = $.extend(o, { timeOnly: true }); return $(this).each(function() { $.fn.datetimepicker.apply($(this), tmp_args); }); }, //######################################################################## // extend timepicker to datepicker //######################################################################## datetimepicker: function(o) { o = o || {}; var $input = this, tmp_args = arguments; if (typeof(o) == 'string'){ if(o == 'getDate') return $.fn.datepicker.apply($(this[0]), tmp_args); else return this.each(function() { var $t = $(this); $t.datepicker.apply($t, tmp_args); }); } else return this.each(function() { var $t = $(this); $t.datepicker($.timepicker._newInst($t, o)._defaults); }); } }); //######################################################################## // the bad hack :/ override datepicker so it doesnt close on select // inspired: http://stackoverflow.com/questions/1252512/jquery-datepicker-prevent-closing-picker-when-clicking-a-date/1762378#1762378 //######################################################################## $.datepicker._base_selectDate = $.datepicker._selectDate; $.datepicker._selectDate = function (id, dateStr) { var inst = this._getInst($(id)[0]), tp_inst = this._get(inst, 'timepicker'); if (tp_inst) { tp_inst._limitMinMaxDateTime(inst, true); inst.inline = inst.stay_open = true; //This way the onSelect handler called from calendarpicker get the full dateTime this._base_selectDate(id, dateStr); inst.inline = inst.stay_open = false; this._notifyChange(inst); this._updateDatepicker(inst); } else this._base_selectDate(id, dateStr); }; //############################################################################################# // second bad hack :/ override datepicker so it triggers an event when changing the input field // and does not redraw the datepicker on every selectDate event //############################################################################################# $.datepicker._base_updateDatepicker = $.datepicker._updateDatepicker; $.datepicker._updateDatepicker = function(inst) { // don't popup the datepicker if there is another instance already opened var input = inst.input[0]; if($.datepicker._curInst && $.datepicker._curInst != inst && $.datepicker._datepickerShowing && $.datepicker._lastInput != input) { return; } if (typeof(inst.stay_open) !== 'boolean' || inst.stay_open === false) { this._base_updateDatepicker(inst); // Reload the time control when changing something in the input text field. var tp_inst = this._get(inst, 'timepicker'); if(tp_inst) tp_inst._addTimePicker(inst); } }; //####################################################################################### // third bad hack :/ override datepicker so it allows spaces and colon in the input field //####################################################################################### $.datepicker._base_doKeyPress = $.datepicker._doKeyPress; $.datepicker._doKeyPress = function(event) { var inst = $.datepicker._getInst(event.target), tp_inst = $.datepicker._get(inst, 'timepicker'); if (tp_inst) { if ($.datepicker._get(inst, 'constrainInput')) { var ampm = tp_inst._defaults.ampm, dateChars = $.datepicker._possibleChars($.datepicker._get(inst, 'dateFormat')), datetimeChars = tp_inst._defaults.timeFormat.toString() .replace(/[hms]/g, '') .replace(/TT/g, ampm ? 'APM' : '') .replace(/Tt/g, ampm ? 'AaPpMm' : '') .replace(/tT/g, ampm ? 'AaPpMm' : '') .replace(/T/g, ampm ? 'AP' : '') .replace(/tt/g, ampm ? 'apm' : '') .replace(/t/g, ampm ? 'ap' : '') + " " + tp_inst._defaults.separator + tp_inst._defaults.timeSuffix + (tp_inst._defaults.showTimezone ? tp_inst._defaults.timezoneList.join('') : '') + (tp_inst._defaults.amNames.join('')) + (tp_inst._defaults.pmNames.join('')) + dateChars, chr = String.fromCharCode(event.charCode === undefined ? event.keyCode : event.charCode); return event.ctrlKey || (chr < ' ' || !dateChars || datetimeChars.indexOf(chr) > -1); } } return $.datepicker._base_doKeyPress(event); }; //####################################################################################### // Override key up event to sync manual input changes. //####################################################################################### $.datepicker._base_doKeyUp = $.datepicker._doKeyUp; $.datepicker._doKeyUp = function (event) { var inst = $.datepicker._getInst(event.target), tp_inst = $.datepicker._get(inst, 'timepicker'); if (tp_inst) { if (tp_inst._defaults.timeOnly && (inst.input.val() != inst.lastVal)) { try { $.datepicker._updateDatepicker(inst); } catch (err) { $.datepicker.log(err); } } } return $.datepicker._base_doKeyUp(event); }; //####################################################################################### // override "Today" button to also grab the time. //####################################################################################### $.datepicker._base_gotoToday = $.datepicker._gotoToday; $.datepicker._gotoToday = function(id) { var inst = this._getInst($(id)[0]), $dp = inst.dpDiv; this._base_gotoToday(id); var now = new Date(); var tp_inst = this._get(inst, 'timepicker'); if (tp_inst._defaults.showTimezone && tp_inst.timezone_select) { var tzoffset = now.getTimezoneOffset(); // If +0100, returns -60 var tzsign = tzoffset > 0 ? '-' : '+'; tzoffset = Math.abs(tzoffset); var tzmin = tzoffset % 60 tzoffset = tzsign + ('0' + (tzoffset - tzmin) / 60).slice(-2) + ('0' + tzmin).slice(-2); if (tp_inst._defaults.timezoneIso8609) tzoffset = tzoffset.substring(0, 3) + ':' + tzoffset.substring(3); tp_inst.timezone_select.val(tzoffset); } this._setTime(inst, now); $( '.ui-datepicker-today', $dp).click(); }; //####################################################################################### // Disable & enable the Time in the datetimepicker //####################################################################################### $.datepicker._disableTimepickerDatepicker = function(target, date, withDate) { var inst = this._getInst(target), tp_inst = this._get(inst, 'timepicker'); $(target).datepicker('getDate'); // Init selected[Year|Month|Day] if (tp_inst) { tp_inst._defaults.showTimepicker = false; tp_inst._updateDateTime(inst); } }; $.datepicker._enableTimepickerDatepicker = function(target, date, withDate) { var inst = this._getInst(target), tp_inst = this._get(inst, 'timepicker'); $(target).datepicker('getDate'); // Init selected[Year|Month|Day] if (tp_inst) { tp_inst._defaults.showTimepicker = true; tp_inst._addTimePicker(inst); // Could be disabled on page load tp_inst._updateDateTime(inst); } }; //####################################################################################### // Create our own set time function //####################################################################################### $.datepicker._setTime = function(inst, date) { var tp_inst = this._get(inst, 'timepicker'); if (tp_inst) { var defaults = tp_inst._defaults, // calling _setTime with no date sets time to defaults hour = date ? date.getHours() : defaults.hour, minute = date ? date.getMinutes() : defaults.minute, second = date ? date.getSeconds() : defaults.second, millisec = date ? date.getMilliseconds() : defaults.millisec; //check if within min/max times.. if ((hour < defaults.hourMin || hour > defaults.hourMax) || (minute < defaults.minuteMin || minute > defaults.minuteMax) || (second < defaults.secondMin || second > defaults.secondMax) || (millisec < defaults.millisecMin || millisec > defaults.millisecMax)) { hour = defaults.hourMin; minute = defaults.minuteMin; second = defaults.secondMin; millisec = defaults.millisecMin; } tp_inst.hour = hour; tp_inst.minute = minute; tp_inst.second = second; tp_inst.millisec = millisec; if (tp_inst.hour_slider) tp_inst.hour_slider.slider('value', hour); if (tp_inst.minute_slider) tp_inst.minute_slider.slider('value', minute); if (tp_inst.second_slider) tp_inst.second_slider.slider('value', second); if (tp_inst.millisec_slider) tp_inst.millisec_slider.slider('value', millisec); tp_inst._onTimeChange(); tp_inst._updateDateTime(inst); } }; //####################################################################################### // Create new public method to set only time, callable as $().datepicker('setTime', date) //####################################################################################### $.datepicker._setTimeDatepicker = function(target, date, withDate) { var inst = this._getInst(target), tp_inst = this._get(inst, 'timepicker'); if (tp_inst) { this._setDateFromField(inst); var tp_date; if (date) { if (typeof date == "string") { tp_inst._parseTime(date, withDate); tp_date = new Date(); tp_date.setHours(tp_inst.hour, tp_inst.minute, tp_inst.second, tp_inst.millisec); } else tp_date = new Date(date.getTime()); if (tp_date.toString() == 'Invalid Date') tp_date = undefined; this._setTime(inst, tp_date); } } }; //####################################################################################### // override setDate() to allow setting time too within Date object //####################################################################################### $.datepicker._base_setDateDatepicker = $.datepicker._setDateDatepicker; $.datepicker._setDateDatepicker = function(target, date) { var inst = this._getInst(target), tp_date = (date instanceof Date) ? new Date(date.getTime()) : date; this._updateDatepicker(inst); this._base_setDateDatepicker.apply(this, arguments); this._setTimeDatepicker(target, tp_date, true); }; //####################################################################################### // override getDate() to allow getting time too within Date object //####################################################################################### $.datepicker._base_getDateDatepicker = $.datepicker._getDateDatepicker; $.datepicker._getDateDatepicker = function(target, noDefault) { var inst = this._getInst(target), tp_inst = this._get(inst, 'timepicker'); if (tp_inst) { this._setDateFromField(inst, noDefault); var date = this._getDate(inst); if (date && tp_inst._parseTime($(target).val(), tp_inst.timeOnly)) date.setHours(tp_inst.hour, tp_inst.minute, tp_inst.second, tp_inst.millisec); return date; } return this._base_getDateDatepicker(target, noDefault); }; //####################################################################################### // override parseDate() because UI 1.8.14 throws an error about "Extra characters" // An option in datapicker to ignore extra format characters would be nicer. //####################################################################################### $.datepicker._base_parseDate = $.datepicker.parseDate; $.datepicker.parseDate = function(format, value, settings) { var date; try { date = this._base_parseDate(format, value, settings); } catch (err) { // Hack! The error message ends with a colon, a space, and // the "extra" characters. We rely on that instead of // attempting to perfectly reproduce the parsing algorithm. date = this._base_parseDate(format, value.substring(0,value.length-(err.length-err.indexOf(':')-2)), settings); } return date; }; //####################################################################################### // override formatDate to set date with time to the input //####################################################################################### $.datepicker._base_formatDate=$.datepicker._formatDate; $.datepicker._formatDate = function(inst, day, month, year){ var tp_inst = this._get(inst, 'timepicker'); if(tp_inst) { if(day) var b = this._base_formatDate(inst, day, month, year); tp_inst._updateDateTime(); return tp_inst.$input.val(); } return this._base_formatDate(inst); } //####################################################################################### // override options setter to add time to maxDate(Time) and minDate(Time). MaxDate //####################################################################################### $.datepicker._base_optionDatepicker = $.datepicker._optionDatepicker; $.datepicker._optionDatepicker = function(target, name, value) { var inst = this._getInst(target), tp_inst = this._get(inst, 'timepicker'); if (tp_inst) { var min,max,onselect; if (typeof name == 'string') { // if min/max was set with the string if (name==='minDate' || name==='minDateTime' ) min = value; else if (name==='maxDate' || name==='maxDateTime') max = value; else if (name==='onSelect') onselect=value; } else if (typeof name == 'object') { //if min/max was set with the JSON if(name.minDate) min = name.minDate; else if (name.minDateTime) min = name.minDateTime; else if (name.maxDate) max = name.maxDate; else if (name.maxDateTime) max = name.maxDateTime; } if(min){ //if min was set if(min==0) min=new Date(); else min= new Date(min); tp_inst._defaults.minDate = min; tp_inst._defaults.minDateTime = min; } else if (max){ //if max was set if(max==0) max=new Date(); else max= new Date(max); tp_inst._defaults.maxDate = max; tp_inst._defaults.maxDateTime = max; } else if (onselect) tp_inst._defaults.onSelect=onselect; } this._base_optionDatepicker(target, name, value); }; //####################################################################################### // jQuery extend now ignores nulls! //####################################################################################### function extendRemove(target, props) { $.extend(target, props); for (var name in props) if (props[name] === null || props[name] === undefined) target[name] = props[name]; return target; } $.timepicker = new Timepicker(); // singleton instance $.timepicker.version = "0.9.7"; })(jQuery);
JavaScript
/* Flot plugin for stacking data sets, i.e. putting them on top of each other, for accumulative graphs. The plugin assumes the data is sorted on x (or y if stacking horizontally). For line charts, it is assumed that if a line has an undefined gap (from a null point), then the line above it should have the same gap - insert zeros instead of "null" if you want another behaviour. This also holds for the start and end of the chart. Note that stacking a mix of positive and negative values in most instances doesn't make sense (so it looks weird). Two or more series are stacked when their "stack" attribute is set to the same key (which can be any number or string or just "true"). To specify the default stack, you can set series: { stack: null or true or key (number/string) } or specify it for a specific series $.plot($("#placeholder"), [{ data: [ ... ], stack: true }]) The stacking order is determined by the order of the data series in the array (later series end up on top of the previous). Internally, the plugin modifies the datapoints in each series, adding an offset to the y value. For line series, extra data points are inserted through interpolation. If there's a second y value, it's also adjusted (e.g for bar charts or filled areas). */ (function ($) { var options = { series: { stack: null } // or number/string }; function init(plot) { function findMatchingSeries(s, allseries) { var res = null for (var i = 0; i < allseries.length; ++i) { if (s == allseries[i]) break; if (allseries[i].stack == s.stack) res = allseries[i]; } return res; } function stackData(plot, s, datapoints) { if (s.stack == null) return; var other = findMatchingSeries(s, plot.getData()); if (!other) return; var ps = datapoints.pointsize, points = datapoints.points, otherps = other.datapoints.pointsize, otherpoints = other.datapoints.points, newpoints = [], px, py, intery, qx, qy, bottom, withlines = s.lines.show, horizontal = s.bars.horizontal, withbottom = ps > 2 && (horizontal ? datapoints.format[2].x : datapoints.format[2].y), withsteps = withlines && s.lines.steps, fromgap = true, keyOffset = horizontal ? 1 : 0, accumulateOffset = horizontal ? 0 : 1, i = 0, j = 0, l; while (true) { if (i >= points.length) break; l = newpoints.length; if (points[i] == null) { // copy gaps for (m = 0; m < ps; ++m) newpoints.push(points[i + m]); i += ps; } else if (j >= otherpoints.length) { // for lines, we can't use the rest of the points if (!withlines) { for (m = 0; m < ps; ++m) newpoints.push(points[i + m]); } i += ps; } else if (otherpoints[j] == null) { // oops, got a gap for (m = 0; m < ps; ++m) newpoints.push(null); fromgap = true; j += otherps; } else { // cases where we actually got two points px = points[i + keyOffset]; py = points[i + accumulateOffset]; qx = otherpoints[j + keyOffset]; qy = otherpoints[j + accumulateOffset]; bottom = 0; if (px == qx) { for (m = 0; m < ps; ++m) newpoints.push(points[i + m]); newpoints[l + accumulateOffset] += qy; bottom = qy; i += ps; j += otherps; } else if (px > qx) { // we got past point below, might need to // insert interpolated extra point if (withlines && i > 0 && points[i - ps] != null) { intery = py + (points[i - ps + accumulateOffset] - py) * (qx - px) / (points[i - ps + keyOffset] - px); newpoints.push(qx); newpoints.push(intery + qy); for (m = 2; m < ps; ++m) newpoints.push(points[i + m]); bottom = qy; } j += otherps; } else { // px < qx if (fromgap && withlines) { // if we come from a gap, we just skip this point i += ps; continue; } for (m = 0; m < ps; ++m) newpoints.push(points[i + m]); // we might be able to interpolate a point below, // this can give us a better y if (withlines && j > 0 && otherpoints[j - otherps] != null) bottom = qy + (otherpoints[j - otherps + accumulateOffset] - qy) * (px - qx) / (otherpoints[j - otherps + keyOffset] - qx); newpoints[l + accumulateOffset] += bottom; i += ps; } fromgap = false; if (l != newpoints.length && withbottom) newpoints[l + 2] += bottom; } // maintain the line steps invariant if (withsteps && l != newpoints.length && l > 0 && newpoints[l] != null && newpoints[l] != newpoints[l - ps] && newpoints[l + 1] != newpoints[l - ps + 1]) { for (m = 0; m < ps; ++m) newpoints[l + ps + m] = newpoints[l + m]; newpoints[l + 1] = newpoints[l - ps + 1]; } } datapoints.points = newpoints; } plot.hooks.processDatapoints.push(stackData); } $.plot.plugins.push({ init: init, options: options, name: 'stack', version: '1.2' }); })(jQuery);
JavaScript
/*! Javascript plotting library for jQuery, v. 0.7. * * Released under the MIT license by IOLA, December 2007. * */ // first an inline dependency, jquery.colorhelpers.js, we inline it here // for convenience /* Plugin for jQuery for working with colors. * * Version 1.1. * * Inspiration from jQuery color animation plugin by John Resig. * * Released under the MIT license by Ole Laursen, October 2009. * * Examples: * * $.color.parse("#fff").scale('rgb', 0.25).add('a', -0.5).toString() * var c = $.color.extract($("#mydiv"), 'background-color'); * console.log(c.r, c.g, c.b, c.a); * $.color.make(100, 50, 25, 0.4).toString() // returns "rgba(100,50,25,0.4)" * * Note that .scale() and .add() return the same modified object * instead of making a new one. * * V. 1.1: Fix error handling so e.g. parsing an empty string does * produce a color rather than just crashing. */ (function(B){B.color={};B.color.make=function(F,E,C,D){var G={};G.r=F||0;G.g=E||0;G.b=C||0;G.a=D!=null?D:1;G.add=function(J,I){for(var H=0;H<J.length;++H){G[J.charAt(H)]+=I}return G.normalize()};G.scale=function(J,I){for(var H=0;H<J.length;++H){G[J.charAt(H)]*=I}return G.normalize()};G.toString=function(){if(G.a>=1){return"rgb("+[G.r,G.g,G.b].join(",")+")"}else{return"rgba("+[G.r,G.g,G.b,G.a].join(",")+")"}};G.normalize=function(){function H(J,K,I){return K<J?J:(K>I?I:K)}G.r=H(0,parseInt(G.r),255);G.g=H(0,parseInt(G.g),255);G.b=H(0,parseInt(G.b),255);G.a=H(0,G.a,1);return G};G.clone=function(){return B.color.make(G.r,G.b,G.g,G.a)};return G.normalize()};B.color.extract=function(D,C){var E;do{E=D.css(C).toLowerCase();if(E!=""&&E!="transparent"){break}D=D.parent()}while(!B.nodeName(D.get(0),"body"));if(E=="rgba(0, 0, 0, 0)"){E="transparent"}return B.color.parse(E)};B.color.parse=function(F){var E,C=B.color.make;if(E=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(F)){return C(parseInt(E[1],10),parseInt(E[2],10),parseInt(E[3],10))}if(E=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(F)){return C(parseInt(E[1],10),parseInt(E[2],10),parseInt(E[3],10),parseFloat(E[4]))}if(E=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(F)){return C(parseFloat(E[1])*2.55,parseFloat(E[2])*2.55,parseFloat(E[3])*2.55)}if(E=/rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(F)){return C(parseFloat(E[1])*2.55,parseFloat(E[2])*2.55,parseFloat(E[3])*2.55,parseFloat(E[4]))}if(E=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(F)){return C(parseInt(E[1],16),parseInt(E[2],16),parseInt(E[3],16))}if(E=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(F)){return C(parseInt(E[1]+E[1],16),parseInt(E[2]+E[2],16),parseInt(E[3]+E[3],16))}var D=B.trim(F).toLowerCase();if(D=="transparent"){return C(255,255,255,0)}else{E=A[D]||[0,0,0];return C(E[0],E[1],E[2])}};var A={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]}})(jQuery); // the actual Flot code (function($) { function Plot(placeholder, data_, options_, plugins) { // data is on the form: // [ series1, series2 ... ] // where series is either just the data as [ [x1, y1], [x2, y2], ... ] // or { data: [ [x1, y1], [x2, y2], ... ], label: "some label", ... } var series = [], options = { // the color theme used for graphs colors: ["#edc240", "#afd8f8", "#cb4b4b", "#4da74d", "#9440ed"], legend: { show: true, noColumns: 1, // number of colums in legend table labelFormatter: null, // fn: string -> string labelBoxBorderColor: "#ccc", // border color for the little label boxes container: null, // container (as jQuery object) to put legend in, null means default on top of graph position: "ne", // position of default legend container within plot margin: 5, // distance from grid edge to default legend container within plot backgroundColor: null, // null means auto-detect backgroundOpacity: 0.85 // set to 0 to avoid background }, xaxis: { show: null, // null = auto-detect, true = always, false = never position: "bottom", // or "top" mode: null, // null or "time" color: null, // base color, labels, ticks tickColor: null, // possibly different color of ticks, e.g. "rgba(0,0,0,0.15)" transform: null, // null or f: number -> number to transform axis inverseTransform: null, // if transform is set, this should be the inverse function min: null, // min. value to show, null means set automatically max: null, // max. value to show, null means set automatically autoscaleMargin: null, // margin in % to add if auto-setting min/max ticks: null, // either [1, 3] or [[1, "a"], 3] or (fn: axis info -> ticks) or app. number of ticks for auto-ticks tickFormatter: null, // fn: number -> string labelWidth: null, // size of tick labels in pixels labelHeight: null, reserveSpace: null, // whether to reserve space even if axis isn't shown tickLength: null, // size in pixels of ticks, or "full" for whole line alignTicksWithAxis: null, // axis number or null for no sync // mode specific options tickDecimals: null, // no. of decimals, null means auto tickSize: null, // number or [number, "unit"] minTickSize: null, // number or [number, "unit"] monthNames: null, // list of names of months timeformat: null, // format string to use twelveHourClock: false // 12 or 24 time in time mode }, yaxis: { autoscaleMargin: 0.02, position: "left" // or "right" }, xaxes: [], yaxes: [], series: { points: { show: false, radius: 3, lineWidth: 2, // in pixels fill: true, fillColor: "#ffffff", symbol: "circle" // or callback }, lines: { // we don't put in show: false so we can see // whether lines were actively disabled lineWidth: 2, // in pixels fill: false, fillColor: null, steps: false }, bars: { show: false, lineWidth: 2, // in pixels barWidth: 1, // in units of the x axis fill: true, fillColor: null, align: "left", // or "center" horizontal: false }, shadowSize: 3 }, grid: { show: true, aboveData: false, color: "#545454", // primary color used for outline and labels backgroundColor: null, // null for transparent, else color borderColor: null, // set if different from the grid color tickColor: null, // color for the ticks, e.g. "rgba(0,0,0,0.15)" labelMargin: 5, // in pixels axisMargin: 8, // in pixels borderWidth: 2, // in pixels minBorderMargin: null, // in pixels, null means taken from points radius markings: null, // array of ranges or fn: axes -> array of ranges markingsColor: "#f4f4f4", markingsLineWidth: 2, // interactive stuff clickable: false, hoverable: false, autoHighlight: true, // highlight in case mouse is near mouseActiveRadius: 10 // how far the mouse can be away to activate an item }, hooks: {} }, canvas = null, // the canvas for the plot itself overlay = null, // canvas for interactive stuff on top of plot eventHolder = null, // jQuery object that events should be bound to ctx = null, octx = null, xaxes = [], yaxes = [], plotOffset = { left: 0, right: 0, top: 0, bottom: 0}, canvasWidth = 0, canvasHeight = 0, plotWidth = 0, plotHeight = 0, hooks = { processOptions: [], processRawData: [], processDatapoints: [], drawSeries: [], draw: [], bindEvents: [], drawOverlay: [], shutdown: [] }, plot = this; // public functions plot.setData = setData; plot.setupGrid = setupGrid; plot.draw = draw; plot.getPlaceholder = function() { return placeholder; }; plot.getCanvas = function() { return canvas; }; plot.getPlotOffset = function() { return plotOffset; }; plot.width = function () { return plotWidth; }; plot.height = function () { return plotHeight; }; plot.offset = function () { var o = eventHolder.offset(); o.left += plotOffset.left; o.top += plotOffset.top; return o; }; plot.getData = function () { return series; }; plot.getAxes = function () { var res = {}, i; $.each(xaxes.concat(yaxes), function (_, axis) { if (axis) res[axis.direction + (axis.n != 1 ? axis.n : "") + "axis"] = axis; }); return res; }; plot.getXAxes = function () { return xaxes; }; plot.getYAxes = function () { return yaxes; }; plot.c2p = canvasToAxisCoords; plot.p2c = axisToCanvasCoords; plot.getOptions = function () { return options; }; plot.highlight = highlight; plot.unhighlight = unhighlight; plot.triggerRedrawOverlay = triggerRedrawOverlay; plot.pointOffset = function(point) { return { left: parseInt(xaxes[axisNumber(point, "x") - 1].p2c(+point.x) + plotOffset.left), top: parseInt(yaxes[axisNumber(point, "y") - 1].p2c(+point.y) + plotOffset.top) }; }; plot.shutdown = shutdown; plot.resize = function () { getCanvasDimensions(); resizeCanvas(canvas); resizeCanvas(overlay); }; // public attributes plot.hooks = hooks; // initialize initPlugins(plot); parseOptions(options_); setupCanvases(); setData(data_); setupGrid(); draw(); bindEvents(); function executeHooks(hook, args) { args = [plot].concat(args); for (var i = 0; i < hook.length; ++i) hook[i].apply(this, args); } function initPlugins() { for (var i = 0; i < plugins.length; ++i) { var p = plugins[i]; p.init(plot); if (p.options) $.extend(true, options, p.options); } } function parseOptions(opts) { var i; $.extend(true, options, opts); if (options.xaxis.color == null) options.xaxis.color = options.grid.color; if (options.yaxis.color == null) options.yaxis.color = options.grid.color; if (options.xaxis.tickColor == null) // backwards-compatibility options.xaxis.tickColor = options.grid.tickColor; if (options.yaxis.tickColor == null) // backwards-compatibility options.yaxis.tickColor = options.grid.tickColor; if (options.grid.borderColor == null) options.grid.borderColor = options.grid.color; if (options.grid.tickColor == null) options.grid.tickColor = $.color.parse(options.grid.color).scale('a', 0.22).toString(); // fill in defaults in axes, copy at least always the // first as the rest of the code assumes it'll be there for (i = 0; i < Math.max(1, options.xaxes.length); ++i) options.xaxes[i] = $.extend(true, {}, options.xaxis, options.xaxes[i]); for (i = 0; i < Math.max(1, options.yaxes.length); ++i) options.yaxes[i] = $.extend(true, {}, options.yaxis, options.yaxes[i]); // backwards compatibility, to be removed in future if (options.xaxis.noTicks && options.xaxis.ticks == null) options.xaxis.ticks = options.xaxis.noTicks; if (options.yaxis.noTicks && options.yaxis.ticks == null) options.yaxis.ticks = options.yaxis.noTicks; if (options.x2axis) { options.xaxes[1] = $.extend(true, {}, options.xaxis, options.x2axis); options.xaxes[1].position = "top"; } if (options.y2axis) { options.yaxes[1] = $.extend(true, {}, options.yaxis, options.y2axis); options.yaxes[1].position = "right"; } if (options.grid.coloredAreas) options.grid.markings = options.grid.coloredAreas; if (options.grid.coloredAreasColor) options.grid.markingsColor = options.grid.coloredAreasColor; if (options.lines) $.extend(true, options.series.lines, options.lines); if (options.points) $.extend(true, options.series.points, options.points); if (options.bars) $.extend(true, options.series.bars, options.bars); if (options.shadowSize != null) options.series.shadowSize = options.shadowSize; // save options on axes for future reference for (i = 0; i < options.xaxes.length; ++i) getOrCreateAxis(xaxes, i + 1).options = options.xaxes[i]; for (i = 0; i < options.yaxes.length; ++i) getOrCreateAxis(yaxes, i + 1).options = options.yaxes[i]; // add hooks from options for (var n in hooks) if (options.hooks[n] && options.hooks[n].length) hooks[n] = hooks[n].concat(options.hooks[n]); executeHooks(hooks.processOptions, [options]); } function setData(d) { series = parseData(d); fillInSeriesOptions(); processData(); } function parseData(d) { var res = []; for (var i = 0; i < d.length; ++i) { var s = $.extend(true, {}, options.series); if (d[i].data != null) { s.data = d[i].data; // move the data instead of deep-copy delete d[i].data; $.extend(true, s, d[i]); d[i].data = s.data; } else s.data = d[i]; res.push(s); } return res; } function axisNumber(obj, coord) { var a = obj[coord + "axis"]; if (typeof a == "object") // if we got a real axis, extract number a = a.n; if (typeof a != "number") a = 1; // default to first axis return a; } function allAxes() { // return flat array without annoying null entries return $.grep(xaxes.concat(yaxes), function (a) { return a; }); } function canvasToAxisCoords(pos) { // return an object with x/y corresponding to all used axes var res = {}, i, axis; for (i = 0; i < xaxes.length; ++i) { axis = xaxes[i]; if (axis && axis.used) res["x" + axis.n] = axis.c2p(pos.left); } for (i = 0; i < yaxes.length; ++i) { axis = yaxes[i]; if (axis && axis.used) res["y" + axis.n] = axis.c2p(pos.top); } if (res.x1 !== undefined) res.x = res.x1; if (res.y1 !== undefined) res.y = res.y1; return res; } function axisToCanvasCoords(pos) { // get canvas coords from the first pair of x/y found in pos var res = {}, i, axis, key; for (i = 0; i < xaxes.length; ++i) { axis = xaxes[i]; if (axis && axis.used) { key = "x" + axis.n; if (pos[key] == null && axis.n == 1) key = "x"; if (pos[key] != null) { res.left = axis.p2c(pos[key]); break; } } } for (i = 0; i < yaxes.length; ++i) { axis = yaxes[i]; if (axis && axis.used) { key = "y" + axis.n; if (pos[key] == null && axis.n == 1) key = "y"; if (pos[key] != null) { res.top = axis.p2c(pos[key]); break; } } } return res; } function getOrCreateAxis(axes, number) { if (!axes[number - 1]) axes[number - 1] = { n: number, // save the number for future reference direction: axes == xaxes ? "x" : "y", options: $.extend(true, {}, axes == xaxes ? options.xaxis : options.yaxis) }; return axes[number - 1]; } function fillInSeriesOptions() { var i; // collect what we already got of colors var neededColors = series.length, usedColors = [], assignedColors = []; for (i = 0; i < series.length; ++i) { var sc = series[i].color; if (sc != null) { --neededColors; if (typeof sc == "number") assignedColors.push(sc); else usedColors.push($.color.parse(series[i].color)); } } // we might need to generate more colors if higher indices // are assigned for (i = 0; i < assignedColors.length; ++i) { neededColors = Math.max(neededColors, assignedColors[i] + 1); } // produce colors as needed var colors = [], variation = 0; i = 0; while (colors.length < neededColors) { var c; if (options.colors.length == i) // check degenerate case c = $.color.make(100, 100, 100); else c = $.color.parse(options.colors[i]); // vary color if needed var sign = variation % 2 == 1 ? -1 : 1; c.scale('rgb', 1 + sign * Math.ceil(variation / 2) * 0.2) // FIXME: if we're getting to close to something else, // we should probably skip this one colors.push(c); ++i; if (i >= options.colors.length) { i = 0; ++variation; } } // fill in the options var colori = 0, s; for (i = 0; i < series.length; ++i) { s = series[i]; // assign colors if (s.color == null) { s.color = colors[colori].toString(); ++colori; } else if (typeof s.color == "number") s.color = colors[s.color].toString(); // turn on lines automatically in case nothing is set if (s.lines.show == null) { var v, show = true; for (v in s) if (s[v] && s[v].show) { show = false; break; } if (show) s.lines.show = true; } // setup axes s.xaxis = getOrCreateAxis(xaxes, axisNumber(s, "x")); s.yaxis = getOrCreateAxis(yaxes, axisNumber(s, "y")); } } function processData() { var topSentry = Number.POSITIVE_INFINITY, bottomSentry = Number.NEGATIVE_INFINITY, fakeInfinity = Number.MAX_VALUE, i, j, k, m, length, s, points, ps, x, y, axis, val, f, p; function updateAxis(axis, min, max) { if (min < axis.datamin && min != -fakeInfinity) axis.datamin = min; if (max > axis.datamax && max != fakeInfinity) axis.datamax = max; } $.each(allAxes(), function (_, axis) { // init axis axis.datamin = topSentry; axis.datamax = bottomSentry; axis.used = false; }); for (i = 0; i < series.length; ++i) { s = series[i]; s.datapoints = { points: [] }; executeHooks(hooks.processRawData, [ s, s.data, s.datapoints ]); } // first pass: clean and copy data for (i = 0; i < series.length; ++i) { s = series[i]; var data = s.data, format = s.datapoints.format; if (!format) { format = []; // find out how to copy format.push({ x: true, number: true, required: true }); format.push({ y: true, number: true, required: true }); if (s.bars.show || (s.lines.show && s.lines.fill)) { format.push({ y: true, number: true, required: false, defaultValue: 0 }); if (s.bars.horizontal) { delete format[format.length - 1].y; format[format.length - 1].x = true; } } s.datapoints.format = format; } if (s.datapoints.pointsize != null) continue; // already filled in s.datapoints.pointsize = format.length; ps = s.datapoints.pointsize; points = s.datapoints.points; insertSteps = s.lines.show && s.lines.steps; s.xaxis.used = s.yaxis.used = true; for (j = k = 0; j < data.length; ++j, k += ps) { p = data[j]; var nullify = p == null; if (!nullify) { for (m = 0; m < ps; ++m) { val = p[m]; f = format[m]; if (f) { if (f.number && val != null) { val = +val; // convert to number if (isNaN(val)) val = null; else if (val == Infinity) val = fakeInfinity; else if (val == -Infinity) val = -fakeInfinity; } if (val == null) { if (f.required) nullify = true; if (f.defaultValue != null) val = f.defaultValue; } } points[k + m] = val; } } if (nullify) { for (m = 0; m < ps; ++m) { val = points[k + m]; if (val != null) { f = format[m]; // extract min/max info if (f.x) updateAxis(s.xaxis, val, val); if (f.y) updateAxis(s.yaxis, val, val); } points[k + m] = null; } } else { // a little bit of line specific stuff that // perhaps shouldn't be here, but lacking // better means... if (insertSteps && k > 0 && points[k - ps] != null && points[k - ps] != points[k] && points[k - ps + 1] != points[k + 1]) { // copy the point to make room for a middle point for (m = 0; m < ps; ++m) points[k + ps + m] = points[k + m]; // middle point has same y points[k + 1] = points[k - ps + 1]; // we've added a point, better reflect that k += ps; } } } } // give the hooks a chance to run for (i = 0; i < series.length; ++i) { s = series[i]; executeHooks(hooks.processDatapoints, [ s, s.datapoints]); } // second pass: find datamax/datamin for auto-scaling for (i = 0; i < series.length; ++i) { s = series[i]; points = s.datapoints.points, ps = s.datapoints.pointsize; var xmin = topSentry, ymin = topSentry, xmax = bottomSentry, ymax = bottomSentry; for (j = 0; j < points.length; j += ps) { if (points[j] == null) continue; for (m = 0; m < ps; ++m) { val = points[j + m]; f = format[m]; if (!f || val == fakeInfinity || val == -fakeInfinity) continue; if (f.x) { if (val < xmin) xmin = val; if (val > xmax) xmax = val; } if (f.y) { if (val < ymin) ymin = val; if (val > ymax) ymax = val; } } } if (s.bars.show) { // make sure we got room for the bar on the dancing floor var delta = s.bars.align == "left" ? 0 : -s.bars.barWidth/2; if (s.bars.horizontal) { ymin += delta; ymax += delta + s.bars.barWidth; } else { xmin += delta; xmax += delta + s.bars.barWidth; } } updateAxis(s.xaxis, xmin, xmax); updateAxis(s.yaxis, ymin, ymax); } $.each(allAxes(), function (_, axis) { if (axis.datamin == topSentry) axis.datamin = null; if (axis.datamax == bottomSentry) axis.datamax = null; }); } function makeCanvas(skipPositioning, cls) { var c = document.createElement('canvas'); c.className = cls; c.width = canvasWidth; c.height = canvasHeight; if (!skipPositioning) $(c).css({ position: 'absolute', left: 0, top: 0 }); $(c).appendTo(placeholder); if (!c.getContext) // excanvas hack c = window.G_vmlCanvasManager.initElement(c); // used for resetting in case we get replotted c.getContext("2d").save(); return c; } function getCanvasDimensions() { canvasWidth = placeholder.width(); canvasHeight = placeholder.height(); if (canvasWidth <= 0 || canvasHeight <= 0) throw "Invalid dimensions for plot, width = " + canvasWidth + ", height = " + canvasHeight; } function resizeCanvas(c) { // resizing should reset the state (excanvas seems to be // buggy though) if (c.width != canvasWidth) c.width = canvasWidth; if (c.height != canvasHeight) c.height = canvasHeight; // so try to get back to the initial state (even if it's // gone now, this should be safe according to the spec) var cctx = c.getContext("2d"); cctx.restore(); // and save again cctx.save(); } function setupCanvases() { var reused, existingCanvas = placeholder.children("canvas.base"), existingOverlay = placeholder.children("canvas.overlay"); if (existingCanvas.length == 0 || existingOverlay == 0) { // init everything placeholder.html(""); // make sure placeholder is clear placeholder.css({ padding: 0 }); // padding messes up the positioning if (placeholder.css("position") == 'static') placeholder.css("position", "relative"); // for positioning labels and overlay getCanvasDimensions(); canvas = makeCanvas(true, "base"); overlay = makeCanvas(false, "overlay"); // overlay canvas for interactive features reused = false; } else { // reuse existing elements canvas = existingCanvas.get(0); overlay = existingOverlay.get(0); reused = true; } ctx = canvas.getContext("2d"); octx = overlay.getContext("2d"); // we include the canvas in the event holder too, because IE 7 // sometimes has trouble with the stacking order eventHolder = $([overlay, canvas]); if (reused) { // run shutdown in the old plot object placeholder.data("plot").shutdown(); // reset reused canvases plot.resize(); // make sure overlay pixels are cleared (canvas is cleared when we redraw) octx.clearRect(0, 0, canvasWidth, canvasHeight); // then whack any remaining obvious garbage left eventHolder.unbind(); placeholder.children().not([canvas, overlay]).remove(); } // save in case we get replotted placeholder.data("plot", plot); } function bindEvents() { // bind events if (options.grid.hoverable) { eventHolder.mousemove(onMouseMove); eventHolder.mouseleave(onMouseLeave); } if (options.grid.clickable) eventHolder.click(onClick); executeHooks(hooks.bindEvents, [eventHolder]); } function shutdown() { if (redrawTimeout) clearTimeout(redrawTimeout); eventHolder.unbind("mousemove", onMouseMove); eventHolder.unbind("mouseleave", onMouseLeave); eventHolder.unbind("click", onClick); executeHooks(hooks.shutdown, [eventHolder]); } function setTransformationHelpers(axis) { // set helper functions on the axis, assumes plot area // has been computed already function identity(x) { return x; } var s, m, t = axis.options.transform || identity, it = axis.options.inverseTransform; // precompute how much the axis is scaling a point // in canvas space if (axis.direction == "x") { s = axis.scale = plotWidth / Math.abs(t(axis.max) - t(axis.min)); m = Math.min(t(axis.max), t(axis.min)); } else { s = axis.scale = plotHeight / Math.abs(t(axis.max) - t(axis.min)); s = -s; m = Math.max(t(axis.max), t(axis.min)); } // data point to canvas coordinate if (t == identity) // slight optimization axis.p2c = function (p) { return (p - m) * s; }; else axis.p2c = function (p) { return (t(p) - m) * s; }; // canvas coordinate to data point if (!it) axis.c2p = function (c) { return m + c / s; }; else axis.c2p = function (c) { return it(m + c / s); }; } function measureTickLabels(axis) { var opts = axis.options, i, ticks = axis.ticks || [], labels = [], l, w = opts.labelWidth, h = opts.labelHeight, dummyDiv; function makeDummyDiv(labels, width) { return $('<div style="position:absolute;top:-10000px;' + width + 'font-size:smaller">' + '<div class="' + axis.direction + 'Axis ' + axis.direction + axis.n + 'Axis">' + labels.join("") + '</div></div>') .appendTo(placeholder); } if (axis.direction == "x") { // to avoid measuring the widths of the labels (it's slow), we // construct fixed-size boxes and put the labels inside // them, we don't need the exact figures and the // fixed-size box content is easy to center if (w == null) w = Math.floor(canvasWidth / (ticks.length > 0 ? ticks.length : 1)); // measure x label heights if (h == null) { labels = []; for (i = 0; i < ticks.length; ++i) { l = ticks[i].label; if (l) labels.push('<div class="tickLabel" style="float:left;width:' + w + 'px">' + l + '</div>'); } if (labels.length > 0) { // stick them all in the same div and measure // collective height labels.push('<div style="clear:left"></div>'); dummyDiv = makeDummyDiv(labels, "width:10000px;"); h = dummyDiv.height(); dummyDiv.remove(); } } } else if (w == null || h == null) { // calculate y label dimensions for (i = 0; i < ticks.length; ++i) { l = ticks[i].label; if (l) labels.push('<div class="tickLabel">' + l + '</div>'); } if (labels.length > 0) { dummyDiv = makeDummyDiv(labels, ""); if (w == null) w = dummyDiv.children().width(); if (h == null) h = dummyDiv.find("div.tickLabel").height(); dummyDiv.remove(); } } if (w == null) w = 0; if (h == null) h = 0; axis.labelWidth = w; axis.labelHeight = h; } function allocateAxisBoxFirstPhase(axis) { // find the bounding box of the axis by looking at label // widths/heights and ticks, make room by diminishing the // plotOffset var lw = axis.labelWidth, lh = axis.labelHeight, pos = axis.options.position, tickLength = axis.options.tickLength, axismargin = options.grid.axisMargin, padding = options.grid.labelMargin, all = axis.direction == "x" ? xaxes : yaxes, index; // determine axis margin var samePosition = $.grep(all, function (a) { return a && a.options.position == pos && a.reserveSpace; }); if ($.inArray(axis, samePosition) == samePosition.length - 1) axismargin = 0; // outermost // determine tick length - if we're innermost, we can use "full" if (tickLength == null) tickLength = "full"; var sameDirection = $.grep(all, function (a) { return a && a.reserveSpace; }); var innermost = $.inArray(axis, sameDirection) == 0; if (!innermost && tickLength == "full") tickLength = 5; if (!isNaN(+tickLength)) padding += +tickLength; // compute box if (axis.direction == "x") { lh += padding; if (pos == "bottom") { plotOffset.bottom += lh + axismargin; axis.box = { top: canvasHeight - plotOffset.bottom, height: lh }; } else { axis.box = { top: plotOffset.top + axismargin, height: lh }; plotOffset.top += lh + axismargin; } } else { lw += padding; if (pos == "left") { axis.box = { left: plotOffset.left + axismargin, width: lw }; plotOffset.left += lw + axismargin; } else { plotOffset.right += lw + axismargin; axis.box = { left: canvasWidth - plotOffset.right, width: lw }; } } // save for future reference axis.position = pos; axis.tickLength = tickLength; axis.box.padding = padding; axis.innermost = innermost; } function allocateAxisBoxSecondPhase(axis) { // set remaining bounding box coordinates if (axis.direction == "x") { axis.box.left = plotOffset.left; axis.box.width = plotWidth; } else { axis.box.top = plotOffset.top; axis.box.height = plotHeight; } } function setupGrid() { var i, axes = allAxes(); // first calculate the plot and axis box dimensions $.each(axes, function (_, axis) { axis.show = axis.options.show; if (axis.show == null) axis.show = axis.used; // by default an axis is visible if it's got data axis.reserveSpace = axis.show || axis.options.reserveSpace; setRange(axis); }); allocatedAxes = $.grep(axes, function (axis) { return axis.reserveSpace; }); plotOffset.left = plotOffset.right = plotOffset.top = plotOffset.bottom = 0; if (options.grid.show) { $.each(allocatedAxes, function (_, axis) { // make the ticks setupTickGeneration(axis); setTicks(axis); snapRangeToTicks(axis, axis.ticks); // find labelWidth/Height for axis measureTickLabels(axis); }); // with all dimensions in house, we can compute the // axis boxes, start from the outside (reverse order) for (i = allocatedAxes.length - 1; i >= 0; --i) allocateAxisBoxFirstPhase(allocatedAxes[i]); // make sure we've got enough space for things that // might stick out var minMargin = options.grid.minBorderMargin; if (minMargin == null) { minMargin = 0; for (i = 0; i < series.length; ++i) minMargin = Math.max(minMargin, series[i].points.radius + series[i].points.lineWidth/2); } for (var a in plotOffset) { plotOffset[a] += options.grid.borderWidth; plotOffset[a] = Math.max(minMargin, plotOffset[a]); } } plotWidth = canvasWidth - plotOffset.left - plotOffset.right; plotHeight = canvasHeight - plotOffset.bottom - plotOffset.top; // now we got the proper plotWidth/Height, we can compute the scaling $.each(axes, function (_, axis) { setTransformationHelpers(axis); }); if (options.grid.show) { $.each(allocatedAxes, function (_, axis) { allocateAxisBoxSecondPhase(axis); }); insertAxisLabels(); } insertLegend(); } function setRange(axis) { var opts = axis.options, min = +(opts.min != null ? opts.min : axis.datamin), max = +(opts.max != null ? opts.max : axis.datamax), delta = max - min; if (delta == 0.0) { // degenerate case var widen = max == 0 ? 1 : 0.01; if (opts.min == null) min -= widen; // always widen max if we couldn't widen min to ensure we // don't fall into min == max which doesn't work if (opts.max == null || opts.min != null) max += widen; } else { // consider autoscaling var margin = opts.autoscaleMargin; if (margin != null) { if (opts.min == null) { min -= delta * margin; // make sure we don't go below zero if all values // are positive if (min < 0 && axis.datamin != null && axis.datamin >= 0) min = 0; } if (opts.max == null) { max += delta * margin; if (max > 0 && axis.datamax != null && axis.datamax <= 0) max = 0; } } } axis.min = min; axis.max = max; } function setupTickGeneration(axis) { var opts = axis.options; // estimate number of ticks var noTicks; if (typeof opts.ticks == "number" && opts.ticks > 0) noTicks = opts.ticks; else // heuristic based on the model a*sqrt(x) fitted to // some data points that seemed reasonable noTicks = 0.3 * Math.sqrt(axis.direction == "x" ? canvasWidth : canvasHeight); var delta = (axis.max - axis.min) / noTicks, size, generator, unit, formatter, i, magn, norm; if (opts.mode == "time") { // pretty handling of time // map of app. size of time units in milliseconds var timeUnitSize = { "second": 1000, "minute": 60 * 1000, "hour": 60 * 60 * 1000, "day": 24 * 60 * 60 * 1000, "month": 30 * 24 * 60 * 60 * 1000, "year": 365.2425 * 24 * 60 * 60 * 1000 }; // the allowed tick sizes, after 1 year we use // an integer algorithm var spec = [ [1, "second"], [2, "second"], [5, "second"], [10, "second"], [30, "second"], [1, "minute"], [2, "minute"], [5, "minute"], [10, "minute"], [30, "minute"], [1, "hour"], [2, "hour"], [4, "hour"], [8, "hour"], [12, "hour"], [1, "day"], [2, "day"], [3, "day"], [0.25, "month"], [0.5, "month"], [1, "month"], [2, "month"], [3, "month"], [6, "month"], [1, "year"] ]; var minSize = 0; if (opts.minTickSize != null) { if (typeof opts.tickSize == "number") minSize = opts.tickSize; else minSize = opts.minTickSize[0] * timeUnitSize[opts.minTickSize[1]]; } for (var i = 0; i < spec.length - 1; ++i) if (delta < (spec[i][0] * timeUnitSize[spec[i][1]] + spec[i + 1][0] * timeUnitSize[spec[i + 1][1]]) / 2 && spec[i][0] * timeUnitSize[spec[i][1]] >= minSize) break; size = spec[i][0]; unit = spec[i][1]; // special-case the possibility of several years if (unit == "year") { magn = Math.pow(10, Math.floor(Math.log(delta / timeUnitSize.year) / Math.LN10)); norm = (delta / timeUnitSize.year) / magn; if (norm < 1.5) size = 1; else if (norm < 3) size = 2; else if (norm < 7.5) size = 5; else size = 10; size *= magn; } axis.tickSize = opts.tickSize || [size, unit]; generator = function(axis) { var ticks = [], tickSize = axis.tickSize[0], unit = axis.tickSize[1], d = new Date(axis.min); var step = tickSize * timeUnitSize[unit]; if (unit == "second") d.setUTCSeconds(floorInBase(d.getUTCSeconds(), tickSize)); if (unit == "minute") d.setUTCMinutes(floorInBase(d.getUTCMinutes(), tickSize)); if (unit == "hour") d.setUTCHours(floorInBase(d.getUTCHours(), tickSize)); if (unit == "month") d.setUTCMonth(floorInBase(d.getUTCMonth(), tickSize)); if (unit == "year") d.setUTCFullYear(floorInBase(d.getUTCFullYear(), tickSize)); // reset smaller components d.setUTCMilliseconds(0); if (step >= timeUnitSize.minute) d.setUTCSeconds(0); if (step >= timeUnitSize.hour) d.setUTCMinutes(0); if (step >= timeUnitSize.day) d.setUTCHours(0); if (step >= timeUnitSize.day * 4) d.setUTCDate(1); if (step >= timeUnitSize.year) d.setUTCMonth(0); var carry = 0, v = Number.NaN, prev; do { prev = v; v = d.getTime(); ticks.push(v); if (unit == "month") { if (tickSize < 1) { // a bit complicated - we'll divide the month // up but we need to take care of fractions // so we don't end up in the middle of a day d.setUTCDate(1); var start = d.getTime(); d.setUTCMonth(d.getUTCMonth() + 1); var end = d.getTime(); d.setTime(v + carry * timeUnitSize.hour + (end - start) * tickSize); carry = d.getUTCHours(); d.setUTCHours(0); } else d.setUTCMonth(d.getUTCMonth() + tickSize); } else if (unit == "year") { d.setUTCFullYear(d.getUTCFullYear() + tickSize); } else d.setTime(v + step); } while (v < axis.max && v != prev); return ticks; }; formatter = function (v, axis) { var d = new Date(v); // first check global format if (opts.timeformat != null) return $.plot.formatDate(d, opts.timeformat, opts.monthNames); var t = axis.tickSize[0] * timeUnitSize[axis.tickSize[1]]; var span = axis.max - axis.min; var suffix = (opts.twelveHourClock) ? " %p" : ""; if (t < timeUnitSize.minute) fmt = "%h:%M:%S" + suffix; else if (t < timeUnitSize.day) { if (span < 2 * timeUnitSize.day) fmt = "%h:%M" + suffix; else fmt = "%b %d %h:%M" + suffix; } else if (t < timeUnitSize.month) fmt = "%b %d"; else if (t < timeUnitSize.year) { if (span < timeUnitSize.year) fmt = "%b"; else fmt = "%b %y"; } else fmt = "%y"; return $.plot.formatDate(d, fmt, opts.monthNames); }; } else { // pretty rounding of base-10 numbers var maxDec = opts.tickDecimals; var dec = -Math.floor(Math.log(delta) / Math.LN10); if (maxDec != null && dec > maxDec) dec = maxDec; magn = Math.pow(10, -dec); norm = delta / magn; // norm is between 1.0 and 10.0 if (norm < 1.5) size = 1; else if (norm < 3) { size = 2; // special case for 2.5, requires an extra decimal if (norm > 2.25 && (maxDec == null || dec + 1 <= maxDec)) { size = 2.5; ++dec; } } else if (norm < 7.5) size = 5; else size = 10; size *= magn; if (opts.minTickSize != null && size < opts.minTickSize) size = opts.minTickSize; axis.tickDecimals = Math.max(0, maxDec != null ? maxDec : dec); axis.tickSize = opts.tickSize || size; generator = function (axis) { var ticks = []; // spew out all possible ticks var start = floorInBase(axis.min, axis.tickSize), i = 0, v = Number.NaN, prev; do { prev = v; v = start + i * axis.tickSize; ticks.push(v); ++i; } while (v < axis.max && v != prev); return ticks; }; formatter = function (v, axis) { return v.toFixed(axis.tickDecimals); }; } if (opts.alignTicksWithAxis != null) { var otherAxis = (axis.direction == "x" ? xaxes : yaxes)[opts.alignTicksWithAxis - 1]; if (otherAxis && otherAxis.used && otherAxis != axis) { // consider snapping min/max to outermost nice ticks var niceTicks = generator(axis); if (niceTicks.length > 0) { if (opts.min == null) axis.min = Math.min(axis.min, niceTicks[0]); if (opts.max == null && niceTicks.length > 1) axis.max = Math.max(axis.max, niceTicks[niceTicks.length - 1]); } generator = function (axis) { // copy ticks, scaled to this axis var ticks = [], v, i; for (i = 0; i < otherAxis.ticks.length; ++i) { v = (otherAxis.ticks[i].v - otherAxis.min) / (otherAxis.max - otherAxis.min); v = axis.min + v * (axis.max - axis.min); ticks.push(v); } return ticks; }; // we might need an extra decimal since forced // ticks don't necessarily fit naturally if (axis.mode != "time" && opts.tickDecimals == null) { var extraDec = Math.max(0, -Math.floor(Math.log(delta) / Math.LN10) + 1), ts = generator(axis); // only proceed if the tick interval rounded // with an extra decimal doesn't give us a // zero at end if (!(ts.length > 1 && /\..*0$/.test((ts[1] - ts[0]).toFixed(extraDec)))) axis.tickDecimals = extraDec; } } } axis.tickGenerator = generator; if ($.isFunction(opts.tickFormatter)) axis.tickFormatter = function (v, axis) { return "" + opts.tickFormatter(v, axis); }; else axis.tickFormatter = formatter; } function setTicks(axis) { var oticks = axis.options.ticks, ticks = []; if (oticks == null || (typeof oticks == "number" && oticks > 0)) ticks = axis.tickGenerator(axis); else if (oticks) { if ($.isFunction(oticks)) // generate the ticks ticks = oticks({ min: axis.min, max: axis.max }); else ticks = oticks; } // clean up/labelify the supplied ticks, copy them over var i, v; axis.ticks = []; for (i = 0; i < ticks.length; ++i) { var label = null; var t = ticks[i]; if (typeof t == "object") { v = +t[0]; if (t.length > 1) label = t[1]; } else v = +t; if (label == null) label = axis.tickFormatter(v, axis); if (!isNaN(v)) axis.ticks.push({ v: v, label: label }); } } function snapRangeToTicks(axis, ticks) { if (axis.options.autoscaleMargin && ticks.length > 0) { // snap to ticks if (axis.options.min == null) axis.min = Math.min(axis.min, ticks[0].v); if (axis.options.max == null && ticks.length > 1) axis.max = Math.max(axis.max, ticks[ticks.length - 1].v); } } function draw() { ctx.clearRect(0, 0, canvasWidth, canvasHeight); var grid = options.grid; // draw background, if any if (grid.show && grid.backgroundColor) drawBackground(); if (grid.show && !grid.aboveData) drawGrid(); for (var i = 0; i < series.length; ++i) { executeHooks(hooks.drawSeries, [ctx, series[i]]); drawSeries(series[i]); } executeHooks(hooks.draw, [ctx]); if (grid.show && grid.aboveData) drawGrid(); } function extractRange(ranges, coord) { var axis, from, to, key, axes = allAxes(); for (i = 0; i < axes.length; ++i) { axis = axes[i]; if (axis.direction == coord) { key = coord + axis.n + "axis"; if (!ranges[key] && axis.n == 1) key = coord + "axis"; // support x1axis as xaxis if (ranges[key]) { from = ranges[key].from; to = ranges[key].to; break; } } } // backwards-compat stuff - to be removed in future if (!ranges[key]) { axis = coord == "x" ? xaxes[0] : yaxes[0]; from = ranges[coord + "1"]; to = ranges[coord + "2"]; } // auto-reverse as an added bonus if (from != null && to != null && from > to) { var tmp = from; from = to; to = tmp; } return { from: from, to: to, axis: axis }; } function drawBackground() { ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); ctx.fillStyle = getColorOrGradient(options.grid.backgroundColor, plotHeight, 0, "rgba(255, 255, 255, 0)"); ctx.fillRect(0, 0, plotWidth, plotHeight); ctx.restore(); } function drawGrid() { var i; ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); // draw markings var markings = options.grid.markings; if (markings) { if ($.isFunction(markings)) { var axes = plot.getAxes(); // xmin etc. is backwards compatibility, to be // removed in the future axes.xmin = axes.xaxis.min; axes.xmax = axes.xaxis.max; axes.ymin = axes.yaxis.min; axes.ymax = axes.yaxis.max; markings = markings(axes); } for (i = 0; i < markings.length; ++i) { var m = markings[i], xrange = extractRange(m, "x"), yrange = extractRange(m, "y"); // fill in missing if (xrange.from == null) xrange.from = xrange.axis.min; if (xrange.to == null) xrange.to = xrange.axis.max; if (yrange.from == null) yrange.from = yrange.axis.min; if (yrange.to == null) yrange.to = yrange.axis.max; // clip if (xrange.to < xrange.axis.min || xrange.from > xrange.axis.max || yrange.to < yrange.axis.min || yrange.from > yrange.axis.max) continue; xrange.from = Math.max(xrange.from, xrange.axis.min); xrange.to = Math.min(xrange.to, xrange.axis.max); yrange.from = Math.max(yrange.from, yrange.axis.min); yrange.to = Math.min(yrange.to, yrange.axis.max); if (xrange.from == xrange.to && yrange.from == yrange.to) continue; // then draw xrange.from = xrange.axis.p2c(xrange.from); xrange.to = xrange.axis.p2c(xrange.to); yrange.from = yrange.axis.p2c(yrange.from); yrange.to = yrange.axis.p2c(yrange.to); if (xrange.from == xrange.to || yrange.from == yrange.to) { // draw line ctx.beginPath(); ctx.strokeStyle = m.color || options.grid.markingsColor; ctx.lineWidth = m.lineWidth || options.grid.markingsLineWidth; ctx.moveTo(xrange.from, yrange.from); ctx.lineTo(xrange.to, yrange.to); ctx.stroke(); } else { // fill area ctx.fillStyle = m.color || options.grid.markingsColor; ctx.fillRect(xrange.from, yrange.to, xrange.to - xrange.from, yrange.from - yrange.to); } } } // draw the ticks var axes = allAxes(), bw = options.grid.borderWidth; for (var j = 0; j < axes.length; ++j) { var axis = axes[j], box = axis.box, t = axis.tickLength, x, y, xoff, yoff; if (!axis.show || axis.ticks.length == 0) continue ctx.strokeStyle = axis.options.tickColor || $.color.parse(axis.options.color).scale('a', 0.22).toString(); ctx.lineWidth = 1; // find the edges if (axis.direction == "x") { x = 0; if (t == "full") y = (axis.position == "top" ? 0 : plotHeight); else y = box.top - plotOffset.top + (axis.position == "top" ? box.height : 0); } else { y = 0; if (t == "full") x = (axis.position == "left" ? 0 : plotWidth); else x = box.left - plotOffset.left + (axis.position == "left" ? box.width : 0); } // draw tick bar if (!axis.innermost) { ctx.beginPath(); xoff = yoff = 0; if (axis.direction == "x") xoff = plotWidth; else yoff = plotHeight; if (ctx.lineWidth == 1) { x = Math.floor(x) + 0.5; y = Math.floor(y) + 0.5; } ctx.moveTo(x, y); ctx.lineTo(x + xoff, y + yoff); ctx.stroke(); } // draw ticks ctx.beginPath(); for (i = 0; i < axis.ticks.length; ++i) { var v = axis.ticks[i].v; xoff = yoff = 0; if (v < axis.min || v > axis.max // skip those lying on the axes if we got a border || (t == "full" && bw > 0 && (v == axis.min || v == axis.max))) continue; if (axis.direction == "x") { x = axis.p2c(v); yoff = t == "full" ? -plotHeight : t; if (axis.position == "top") yoff = -yoff; } else { y = axis.p2c(v); xoff = t == "full" ? -plotWidth : t; if (axis.position == "left") xoff = -xoff; } if (ctx.lineWidth == 1) { if (axis.direction == "x") x = Math.floor(x) + 0.5; else y = Math.floor(y) + 0.5; } ctx.moveTo(x, y); ctx.lineTo(x + xoff, y + yoff); } ctx.stroke(); } // draw border if (bw) { ctx.lineWidth = bw; ctx.strokeStyle = options.grid.borderColor; ctx.strokeRect(-bw/2, -bw/2, plotWidth + bw, plotHeight + bw); } ctx.restore(); } function insertAxisLabels() { placeholder.find(".tickLabels").remove(); var html = ['<div class="tickLabels" style="font-size:smaller">']; var axes = allAxes(); for (var j = 0; j < axes.length; ++j) { var axis = axes[j], box = axis.box; if (!axis.show) continue; //debug: html.push('<div style="position:absolute;opacity:0.10;background-color:red;left:' + box.left + 'px;top:' + box.top + 'px;width:' + box.width + 'px;height:' + box.height + 'px"></div>') html.push('<div class="' + axis.direction + 'Axis ' + axis.direction + axis.n + 'Axis" style="color:' + axis.options.color + '">'); for (var i = 0; i < axis.ticks.length; ++i) { var tick = axis.ticks[i]; if (!tick.label || tick.v < axis.min || tick.v > axis.max) continue; var pos = {}, align; if (axis.direction == "x") { align = "center"; pos.left = Math.round(plotOffset.left + axis.p2c(tick.v) - axis.labelWidth/2); if (axis.position == "bottom") pos.top = box.top + box.padding; else pos.bottom = canvasHeight - (box.top + box.height - box.padding); } else { pos.top = Math.round(plotOffset.top + axis.p2c(tick.v) - axis.labelHeight/2); if (axis.position == "left") { pos.right = canvasWidth - (box.left + box.width - box.padding) align = "right"; } else { pos.left = box.left + box.padding; align = "left"; } } pos.width = axis.labelWidth; var style = ["position:absolute", "text-align:" + align ]; for (var a in pos) style.push(a + ":" + pos[a] + "px") html.push('<div class="tickLabel" style="' + style.join(';') + '">' + tick.label + '</div>'); } html.push('</div>'); } html.push('</div>'); placeholder.append(html.join("")); } function drawSeries(series) { if (series.lines.show) drawSeriesLines(series); if (series.bars.show) drawSeriesBars(series); if (series.points.show) drawSeriesPoints(series); } function drawSeriesLines(series) { function plotLine(datapoints, xoffset, yoffset, axisx, axisy) { var points = datapoints.points, ps = datapoints.pointsize, prevx = null, prevy = null; ctx.beginPath(); for (var i = ps; i < points.length; i += ps) { var x1 = points[i - ps], y1 = points[i - ps + 1], x2 = points[i], y2 = points[i + 1]; if (x1 == null || x2 == null) continue; // clip with ymin if (y1 <= y2 && y1 < axisy.min) { if (y2 < axisy.min) continue; // line segment is outside // compute new intersection point x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1; y1 = axisy.min; } else if (y2 <= y1 && y2 < axisy.min) { if (y1 < axisy.min) continue; x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1; y2 = axisy.min; } // clip with ymax if (y1 >= y2 && y1 > axisy.max) { if (y2 > axisy.max) continue; x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1; y1 = axisy.max; } else if (y2 >= y1 && y2 > axisy.max) { if (y1 > axisy.max) continue; x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1; y2 = axisy.max; } // clip with xmin if (x1 <= x2 && x1 < axisx.min) { if (x2 < axisx.min) continue; y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1; x1 = axisx.min; } else if (x2 <= x1 && x2 < axisx.min) { if (x1 < axisx.min) continue; y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1; x2 = axisx.min; } // clip with xmax if (x1 >= x2 && x1 > axisx.max) { if (x2 > axisx.max) continue; y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1; x1 = axisx.max; } else if (x2 >= x1 && x2 > axisx.max) { if (x1 > axisx.max) continue; y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1; x2 = axisx.max; } if (x1 != prevx || y1 != prevy) ctx.moveTo(axisx.p2c(x1) + xoffset, axisy.p2c(y1) + yoffset); prevx = x2; prevy = y2; ctx.lineTo(axisx.p2c(x2) + xoffset, axisy.p2c(y2) + yoffset); } ctx.stroke(); } function plotLineArea(datapoints, axisx, axisy) { var points = datapoints.points, ps = datapoints.pointsize, bottom = Math.min(Math.max(0, axisy.min), axisy.max), i = 0, top, areaOpen = false, ypos = 1, segmentStart = 0, segmentEnd = 0; // we process each segment in two turns, first forward // direction to sketch out top, then once we hit the // end we go backwards to sketch the bottom while (true) { if (ps > 0 && i > points.length + ps) break; i += ps; // ps is negative if going backwards var x1 = points[i - ps], y1 = points[i - ps + ypos], x2 = points[i], y2 = points[i + ypos]; if (areaOpen) { if (ps > 0 && x1 != null && x2 == null) { // at turning point segmentEnd = i; ps = -ps; ypos = 2; continue; } if (ps < 0 && i == segmentStart + ps) { // done with the reverse sweep ctx.fill(); areaOpen = false; ps = -ps; ypos = 1; i = segmentStart = segmentEnd + ps; continue; } } if (x1 == null || x2 == null) continue; // clip x values // clip with xmin if (x1 <= x2 && x1 < axisx.min) { if (x2 < axisx.min) continue; y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1; x1 = axisx.min; } else if (x2 <= x1 && x2 < axisx.min) { if (x1 < axisx.min) continue; y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1; x2 = axisx.min; } // clip with xmax if (x1 >= x2 && x1 > axisx.max) { if (x2 > axisx.max) continue; y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1; x1 = axisx.max; } else if (x2 >= x1 && x2 > axisx.max) { if (x1 > axisx.max) continue; y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1; x2 = axisx.max; } if (!areaOpen) { // open area ctx.beginPath(); ctx.moveTo(axisx.p2c(x1), axisy.p2c(bottom)); areaOpen = true; } // now first check the case where both is outside if (y1 >= axisy.max && y2 >= axisy.max) { ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.max)); ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.max)); continue; } else if (y1 <= axisy.min && y2 <= axisy.min) { ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.min)); ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.min)); continue; } // else it's a bit more complicated, there might // be a flat maxed out rectangle first, then a // triangular cutout or reverse; to find these // keep track of the current x values var x1old = x1, x2old = x2; // clip the y values, without shortcutting, we // go through all cases in turn // clip with ymin if (y1 <= y2 && y1 < axisy.min && y2 >= axisy.min) { x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1; y1 = axisy.min; } else if (y2 <= y1 && y2 < axisy.min && y1 >= axisy.min) { x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1; y2 = axisy.min; } // clip with ymax if (y1 >= y2 && y1 > axisy.max && y2 <= axisy.max) { x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1; y1 = axisy.max; } else if (y2 >= y1 && y2 > axisy.max && y1 <= axisy.max) { x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1; y2 = axisy.max; } // if the x value was changed we got a rectangle // to fill if (x1 != x1old) { ctx.lineTo(axisx.p2c(x1old), axisy.p2c(y1)); // it goes to (x1, y1), but we fill that below } // fill triangular section, this sometimes result // in redundant points if (x1, y1) hasn't changed // from previous line to, but we just ignore that ctx.lineTo(axisx.p2c(x1), axisy.p2c(y1)); ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2)); // fill the other rectangle if it's there if (x2 != x2old) { ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2)); ctx.lineTo(axisx.p2c(x2old), axisy.p2c(y2)); } } } ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); ctx.lineJoin = "round"; var lw = series.lines.lineWidth, sw = series.shadowSize; // FIXME: consider another form of shadow when filling is turned on if (lw > 0 && sw > 0) { // draw shadow as a thick and thin line with transparency ctx.lineWidth = sw; ctx.strokeStyle = "rgba(0,0,0,0.1)"; // position shadow at angle from the mid of line var angle = Math.PI/18; plotLine(series.datapoints, Math.sin(angle) * (lw/2 + sw/2), Math.cos(angle) * (lw/2 + sw/2), series.xaxis, series.yaxis); ctx.lineWidth = sw/2; plotLine(series.datapoints, Math.sin(angle) * (lw/2 + sw/4), Math.cos(angle) * (lw/2 + sw/4), series.xaxis, series.yaxis); } ctx.lineWidth = lw; ctx.strokeStyle = series.color; var fillStyle = getFillStyle(series.lines, series.color, 0, plotHeight); if (fillStyle) { ctx.fillStyle = fillStyle; plotLineArea(series.datapoints, series.xaxis, series.yaxis); } if (lw > 0) plotLine(series.datapoints, 0, 0, series.xaxis, series.yaxis); ctx.restore(); } function drawSeriesPoints(series) { function plotPoints(datapoints, radius, fillStyle, offset, shadow, axisx, axisy, symbol) { var points = datapoints.points, ps = datapoints.pointsize; for (var i = 0; i < points.length; i += ps) { var x = points[i], y = points[i + 1]; if (x == null || x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max) continue; ctx.beginPath(); x = axisx.p2c(x); y = axisy.p2c(y) + offset; if (symbol == "circle") ctx.arc(x, y, radius, 0, shadow ? Math.PI : Math.PI * 2, false); else symbol(ctx, x, y, radius, shadow); ctx.closePath(); if (fillStyle) { ctx.fillStyle = fillStyle; ctx.fill(); } ctx.stroke(); } } ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); var lw = series.points.lineWidth, sw = series.shadowSize, radius = series.points.radius, symbol = series.points.symbol; if (lw > 0 && sw > 0) { // draw shadow in two steps var w = sw / 2; ctx.lineWidth = w; ctx.strokeStyle = "rgba(0,0,0,0.1)"; plotPoints(series.datapoints, radius, null, w + w/2, true, series.xaxis, series.yaxis, symbol); ctx.strokeStyle = "rgba(0,0,0,0.2)"; plotPoints(series.datapoints, radius, null, w/2, true, series.xaxis, series.yaxis, symbol); } ctx.lineWidth = lw; ctx.strokeStyle = series.color; plotPoints(series.datapoints, radius, getFillStyle(series.points, series.color), 0, false, series.xaxis, series.yaxis, symbol); ctx.restore(); } function drawBar(x, y, b, barLeft, barRight, offset, fillStyleCallback, axisx, axisy, c, horizontal, lineWidth) { var left, right, bottom, top, drawLeft, drawRight, drawTop, drawBottom, tmp; // in horizontal mode, we start the bar from the left // instead of from the bottom so it appears to be // horizontal rather than vertical if (horizontal) { drawBottom = drawRight = drawTop = true; drawLeft = false; left = b; right = x; top = y + barLeft; bottom = y + barRight; // account for negative bars if (right < left) { tmp = right; right = left; left = tmp; drawLeft = true; drawRight = false; } } else { drawLeft = drawRight = drawTop = true; drawBottom = false; left = x + barLeft; right = x + barRight; bottom = b; top = y; // account for negative bars if (top < bottom) { tmp = top; top = bottom; bottom = tmp; drawBottom = true; drawTop = false; } } // clip if (right < axisx.min || left > axisx.max || top < axisy.min || bottom > axisy.max) return; if (left < axisx.min) { left = axisx.min; drawLeft = false; } if (right > axisx.max) { right = axisx.max; drawRight = false; } if (bottom < axisy.min) { bottom = axisy.min; drawBottom = false; } if (top > axisy.max) { top = axisy.max; drawTop = false; } left = axisx.p2c(left); bottom = axisy.p2c(bottom); right = axisx.p2c(right); top = axisy.p2c(top); // fill the bar if (fillStyleCallback) { c.beginPath(); c.moveTo(left, bottom); c.lineTo(left, top); c.lineTo(right, top); c.lineTo(right, bottom); c.fillStyle = fillStyleCallback(bottom, top); c.fill(); } // draw outline if (lineWidth > 0 && (drawLeft || drawRight || drawTop || drawBottom)) { c.beginPath(); // FIXME: inline moveTo is buggy with excanvas c.moveTo(left, bottom + offset); if (drawLeft) c.lineTo(left, top + offset); else c.moveTo(left, top + offset); if (drawTop) c.lineTo(right, top + offset); else c.moveTo(right, top + offset); if (drawRight) c.lineTo(right, bottom + offset); else c.moveTo(right, bottom + offset); if (drawBottom) c.lineTo(left, bottom + offset); else c.moveTo(left, bottom + offset); c.stroke(); } } function drawSeriesBars(series) { function plotBars(datapoints, barLeft, barRight, offset, fillStyleCallback, axisx, axisy) { var points = datapoints.points, ps = datapoints.pointsize; for (var i = 0; i < points.length; i += ps) { if (points[i] == null) continue; drawBar(points[i], points[i + 1], points[i + 2], barLeft, barRight, offset, fillStyleCallback, axisx, axisy, ctx, series.bars.horizontal, series.bars.lineWidth); } } ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); // FIXME: figure out a way to add shadows (for instance along the right edge) ctx.lineWidth = series.bars.lineWidth; ctx.strokeStyle = series.color; var barLeft = series.bars.align == "left" ? 0 : -series.bars.barWidth/2; var fillStyleCallback = series.bars.fill ? function (bottom, top) { return getFillStyle(series.bars, series.color, bottom, top); } : null; plotBars(series.datapoints, barLeft, barLeft + series.bars.barWidth, 0, fillStyleCallback, series.xaxis, series.yaxis); ctx.restore(); } function getFillStyle(filloptions, seriesColor, bottom, top) { var fill = filloptions.fill; if (!fill) return null; if (filloptions.fillColor) return getColorOrGradient(filloptions.fillColor, bottom, top, seriesColor); var c = $.color.parse(seriesColor); c.a = typeof fill == "number" ? fill : 0.4; c.normalize(); return c.toString(); } function insertLegend() { placeholder.find(".legend").remove(); if (!options.legend.show) return; var fragments = [], rowStarted = false, lf = options.legend.labelFormatter, s, label; for (var i = 0; i < series.length; ++i) { s = series[i]; label = s.label; if (!label) continue; if (i % options.legend.noColumns == 0) { if (rowStarted) fragments.push('</tr>'); fragments.push('<tr>'); rowStarted = true; } if (lf) label = lf(label, s); fragments.push( '<td class="legendColorBox"><div style="border:1px solid ' + options.legend.labelBoxBorderColor + ';padding:1px"><div style="width:4px;height:0;border:5px solid ' + s.color + ';overflow:hidden"></div></div></td>' + '<td class="legendLabel">' + label + '</td>'); } if (rowStarted) fragments.push('</tr>'); if (fragments.length == 0) return; var table = '<table style="font-size:smaller;color:' + options.grid.color + '">' + fragments.join("") + '</table>'; if (options.legend.container != null) $(options.legend.container).html(table); else { var pos = "", p = options.legend.position, m = options.legend.margin; if (m[0] == null) m = [m, m]; if (p.charAt(0) == "n") pos += 'top:' + (m[1] + plotOffset.top) + 'px;'; else if (p.charAt(0) == "s") pos += 'bottom:' + (m[1] + plotOffset.bottom) + 'px;'; if (p.charAt(1) == "e") pos += 'right:' + (m[0] + plotOffset.right) + 'px;'; else if (p.charAt(1) == "w") pos += 'left:' + (m[0] + plotOffset.left) + 'px;'; var legend = $('<div class="legend">' + table.replace('style="', 'style="position:absolute;' + pos +';') + '</div>').appendTo(placeholder); if (options.legend.backgroundOpacity != 0.0) { // put in the transparent background // separately to avoid blended labels and // label boxes var c = options.legend.backgroundColor; if (c == null) { c = options.grid.backgroundColor; if (c && typeof c == "string") c = $.color.parse(c); else c = $.color.extract(legend, 'background-color'); c.a = 1; c = c.toString(); } var div = legend.children(); $('<div style="position:absolute;width:' + div.width() + 'px;height:' + div.height() + 'px;' + pos +'background-color:' + c + ';"> </div>').prependTo(legend).css('opacity', options.legend.backgroundOpacity); } } } // interactive features var highlights = [], redrawTimeout = null; // returns the data item the mouse is over, or null if none is found function findNearbyItem(mouseX, mouseY, seriesFilter) { var maxDistance = options.grid.mouseActiveRadius, smallestDistance = maxDistance * maxDistance + 1, item = null, foundPoint = false, i, j; for (i = series.length - 1; i >= 0; --i) { if (!seriesFilter(series[i])) continue; var s = series[i], axisx = s.xaxis, axisy = s.yaxis, points = s.datapoints.points, ps = s.datapoints.pointsize, mx = axisx.c2p(mouseX), // precompute some stuff to make the loop faster my = axisy.c2p(mouseY), maxx = maxDistance / axisx.scale, maxy = maxDistance / axisy.scale; // with inverse transforms, we can't use the maxx/maxy // optimization, sadly if (axisx.options.inverseTransform) maxx = Number.MAX_VALUE; if (axisy.options.inverseTransform) maxy = Number.MAX_VALUE; if (s.lines.show || s.points.show) { for (j = 0; j < points.length; j += ps) { var x = points[j], y = points[j + 1]; if (x == null) continue; // For points and lines, the cursor must be within a // certain distance to the data point if (x - mx > maxx || x - mx < -maxx || y - my > maxy || y - my < -maxy) continue; // We have to calculate distances in pixels, not in // data units, because the scales of the axes may be different var dx = Math.abs(axisx.p2c(x) - mouseX), dy = Math.abs(axisy.p2c(y) - mouseY), dist = dx * dx + dy * dy; // we save the sqrt // use <= to ensure last point takes precedence // (last generally means on top of) if (dist < smallestDistance) { smallestDistance = dist; item = [i, j / ps]; } } } if (s.bars.show && !item) { // no other point can be nearby var barLeft = s.bars.align == "left" ? 0 : -s.bars.barWidth/2, barRight = barLeft + s.bars.barWidth; for (j = 0; j < points.length; j += ps) { var x = points[j], y = points[j + 1], b = points[j + 2]; if (x == null) continue; // for a bar graph, the cursor must be inside the bar if (series[i].bars.horizontal ? (mx <= Math.max(b, x) && mx >= Math.min(b, x) && my >= y + barLeft && my <= y + barRight) : (mx >= x + barLeft && mx <= x + barRight && my >= Math.min(b, y) && my <= Math.max(b, y))) item = [i, j / ps]; } } } if (item) { i = item[0]; j = item[1]; ps = series[i].datapoints.pointsize; return { datapoint: series[i].datapoints.points.slice(j * ps, (j + 1) * ps), dataIndex: j, series: series[i], seriesIndex: i }; } return null; } function onMouseMove(e) { if (options.grid.hoverable) triggerClickHoverEvent("plothover", e, function (s) { return s["hoverable"] != false; }); } function onMouseLeave(e) { if (options.grid.hoverable) triggerClickHoverEvent("plothover", e, function (s) { return false; }); } function onClick(e) { triggerClickHoverEvent("plotclick", e, function (s) { return s["clickable"] != false; }); } // trigger click or hover event (they send the same parameters // so we share their code) function triggerClickHoverEvent(eventname, event, seriesFilter) { var offset = eventHolder.offset(), canvasX = event.pageX - offset.left - plotOffset.left, canvasY = event.pageY - offset.top - plotOffset.top, pos = canvasToAxisCoords({ left: canvasX, top: canvasY }); pos.pageX = event.pageX; pos.pageY = event.pageY; var item = findNearbyItem(canvasX, canvasY, seriesFilter); if (item) { // fill in mouse pos for any listeners out there item.pageX = parseInt(item.series.xaxis.p2c(item.datapoint[0]) + offset.left + plotOffset.left); item.pageY = parseInt(item.series.yaxis.p2c(item.datapoint[1]) + offset.top + plotOffset.top); } if (options.grid.autoHighlight) { // clear auto-highlights for (var i = 0; i < highlights.length; ++i) { var h = highlights[i]; if (h.auto == eventname && !(item && h.series == item.series && h.point[0] == item.datapoint[0] && h.point[1] == item.datapoint[1])) unhighlight(h.series, h.point); } if (item) highlight(item.series, item.datapoint, eventname); } placeholder.trigger(eventname, [ pos, item ]); } function triggerRedrawOverlay() { if (!redrawTimeout) redrawTimeout = setTimeout(drawOverlay, 30); } function drawOverlay() { redrawTimeout = null; // draw highlights octx.save(); octx.clearRect(0, 0, canvasWidth, canvasHeight); octx.translate(plotOffset.left, plotOffset.top); var i, hi; for (i = 0; i < highlights.length; ++i) { hi = highlights[i]; if (hi.series.bars.show) drawBarHighlight(hi.series, hi.point); else drawPointHighlight(hi.series, hi.point); } octx.restore(); executeHooks(hooks.drawOverlay, [octx]); } function highlight(s, point, auto) { if (typeof s == "number") s = series[s]; if (typeof point == "number") { var ps = s.datapoints.pointsize; point = s.datapoints.points.slice(ps * point, ps * (point + 1)); } var i = indexOfHighlight(s, point); if (i == -1) { highlights.push({ series: s, point: point, auto: auto }); triggerRedrawOverlay(); } else if (!auto) highlights[i].auto = false; } function unhighlight(s, point) { if (s == null && point == null) { highlights = []; triggerRedrawOverlay(); } if (typeof s == "number") s = series[s]; if (typeof point == "number") point = s.data[point]; var i = indexOfHighlight(s, point); if (i != -1) { highlights.splice(i, 1); triggerRedrawOverlay(); } } function indexOfHighlight(s, p) { for (var i = 0; i < highlights.length; ++i) { var h = highlights[i]; if (h.series == s && h.point[0] == p[0] && h.point[1] == p[1]) return i; } return -1; } function drawPointHighlight(series, point) { var x = point[0], y = point[1], axisx = series.xaxis, axisy = series.yaxis; if (x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max) return; var pointRadius = series.points.radius + series.points.lineWidth / 2; octx.lineWidth = pointRadius; octx.strokeStyle = $.color.parse(series.color).scale('a', 0.5).toString(); var radius = 1.5 * pointRadius, x = axisx.p2c(x), y = axisy.p2c(y); octx.beginPath(); if (series.points.symbol == "circle") octx.arc(x, y, radius, 0, 2 * Math.PI, false); else series.points.symbol(octx, x, y, radius, false); octx.closePath(); octx.stroke(); } function drawBarHighlight(series, point) { octx.lineWidth = series.bars.lineWidth; octx.strokeStyle = $.color.parse(series.color).scale('a', 0.5).toString(); var fillStyle = $.color.parse(series.color).scale('a', 0.5).toString(); var barLeft = series.bars.align == "left" ? 0 : -series.bars.barWidth/2; drawBar(point[0], point[1], point[2] || 0, barLeft, barLeft + series.bars.barWidth, 0, function () { return fillStyle; }, series.xaxis, series.yaxis, octx, series.bars.horizontal, series.bars.lineWidth); } function getColorOrGradient(spec, bottom, top, defaultColor) { if (typeof spec == "string") return spec; else { // assume this is a gradient spec; IE currently only // supports a simple vertical gradient properly, so that's // what we support too var gradient = ctx.createLinearGradient(0, top, 0, bottom); for (var i = 0, l = spec.colors.length; i < l; ++i) { var c = spec.colors[i]; if (typeof c != "string") { var co = $.color.parse(defaultColor); if (c.brightness != null) co = co.scale('rgb', c.brightness) if (c.opacity != null) co.a *= c.opacity; c = co.toString(); } gradient.addColorStop(i / (l - 1), c); } return gradient; } } } $.plot = function(placeholder, data, options) { //var t0 = new Date(); var plot = new Plot($(placeholder), data, options, $.plot.plugins); //(window.console ? console.log : alert)("time used (msecs): " + ((new Date()).getTime() - t0.getTime())); return plot; }; $.plot.version = "0.7"; $.plot.plugins = []; // returns a string with the date d formatted according to fmt $.plot.formatDate = function(d, fmt, monthNames) { var leftPad = function(n) { n = "" + n; return n.length == 1 ? "0" + n : n; }; var r = []; var escape = false, padNext = false; var hours = d.getUTCHours(); var isAM = hours < 12; if (monthNames == null) monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; if (fmt.search(/%p|%P/) != -1) { if (hours > 12) { hours = hours - 12; } else if (hours == 0) { hours = 12; } } for (var i = 0; i < fmt.length; ++i) { var c = fmt.charAt(i); if (escape) { switch (c) { case 'h': c = "" + hours; break; case 'H': c = leftPad(hours); break; case 'M': c = leftPad(d.getUTCMinutes()); break; case 'S': c = leftPad(d.getUTCSeconds()); break; case 'd': c = "" + d.getUTCDate(); break; case 'm': c = "" + (d.getUTCMonth() + 1); break; case 'y': c = "" + d.getUTCFullYear(); break; case 'b': c = "" + monthNames[d.getUTCMonth()]; break; case 'p': c = (isAM) ? ("" + "am") : ("" + "pm"); break; case 'P': c = (isAM) ? ("" + "AM") : ("" + "PM"); break; case '0': c = ""; padNext = true; break; } if (c && padNext) { c = leftPad(c); padNext = false; } r.push(c); if (!padNext) escape = false; } else { if (c == "%") escape = true; else r.push(c); } } return r.join(""); }; // round to nearby lower multiple of base function floorInBase(n, base) { return base * Math.floor(n / base); } })(jQuery);
JavaScript
/* Flot plugin for showing crosshairs, thin lines, when the mouse hovers over the plot. crosshair: { mode: null or "x" or "y" or "xy" color: color lineWidth: number } Set the mode to one of "x", "y" or "xy". The "x" mode enables a vertical crosshair that lets you trace the values on the x axis, "y" enables a horizontal crosshair and "xy" enables them both. "color" is the color of the crosshair (default is "rgba(170, 0, 0, 0.80)"), "lineWidth" is the width of the drawn lines (default is 1). The plugin also adds four public methods: - setCrosshair(pos) Set the position of the crosshair. Note that this is cleared if the user moves the mouse. "pos" is in coordinates of the plot and should be on the form { x: xpos, y: ypos } (you can use x2/x3/... if you're using multiple axes), which is coincidentally the same format as what you get from a "plothover" event. If "pos" is null, the crosshair is cleared. - clearCrosshair() Clear the crosshair. - lockCrosshair(pos) Cause the crosshair to lock to the current location, no longer updating if the user moves the mouse. Optionally supply a position (passed on to setCrosshair()) to move it to. Example usage: var myFlot = $.plot( $("#graph"), ..., { crosshair: { mode: "x" } } }; $("#graph").bind("plothover", function (evt, position, item) { if (item) { // Lock the crosshair to the data point being hovered myFlot.lockCrosshair({ x: item.datapoint[0], y: item.datapoint[1] }); } else { // Return normal crosshair operation myFlot.unlockCrosshair(); } }); - unlockCrosshair() Free the crosshair to move again after locking it. */ (function ($) { var options = { crosshair: { mode: null, // one of null, "x", "y" or "xy", color: "rgba(170, 0, 0, 0.80)", lineWidth: 1 } }; function init(plot) { // position of crosshair in pixels var crosshair = { x: -1, y: -1, locked: false }; plot.setCrosshair = function setCrosshair(pos) { if (!pos) crosshair.x = -1; else { var o = plot.p2c(pos); crosshair.x = Math.max(0, Math.min(o.left, plot.width())); crosshair.y = Math.max(0, Math.min(o.top, plot.height())); } plot.triggerRedrawOverlay(); }; plot.clearCrosshair = plot.setCrosshair; // passes null for pos plot.lockCrosshair = function lockCrosshair(pos) { if (pos) plot.setCrosshair(pos); crosshair.locked = true; } plot.unlockCrosshair = function unlockCrosshair() { crosshair.locked = false; } function onMouseOut(e) { if (crosshair.locked) return; if (crosshair.x != -1) { crosshair.x = -1; plot.triggerRedrawOverlay(); } } function onMouseMove(e) { if (crosshair.locked) return; if (plot.getSelection && plot.getSelection()) { crosshair.x = -1; // hide the crosshair while selecting return; } var offset = plot.offset(); crosshair.x = Math.max(0, Math.min(e.pageX - offset.left, plot.width())); crosshair.y = Math.max(0, Math.min(e.pageY - offset.top, plot.height())); plot.triggerRedrawOverlay(); } plot.hooks.bindEvents.push(function (plot, eventHolder) { if (!plot.getOptions().crosshair.mode) return; eventHolder.mouseout(onMouseOut); eventHolder.mousemove(onMouseMove); }); plot.hooks.drawOverlay.push(function (plot, ctx) { var c = plot.getOptions().crosshair; if (!c.mode) return; var plotOffset = plot.getPlotOffset(); ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); if (crosshair.x != -1) { ctx.strokeStyle = c.color; ctx.lineWidth = c.lineWidth; ctx.lineJoin = "round"; ctx.beginPath(); if (c.mode.indexOf("x") != -1) { ctx.moveTo(crosshair.x, 0); ctx.lineTo(crosshair.x, plot.height()); } if (c.mode.indexOf("y") != -1) { ctx.moveTo(0, crosshair.y); ctx.lineTo(plot.width(), crosshair.y); } ctx.stroke(); } ctx.restore(); }); plot.hooks.shutdown.push(function (plot, eventHolder) { eventHolder.unbind("mouseout", onMouseOut); eventHolder.unbind("mousemove", onMouseMove); }); } $.plot.plugins.push({ init: init, options: options, name: 'crosshair', version: '1.0' }); })(jQuery);
JavaScript
/* Flot plugin for adding panning and zooming capabilities to a plot. The default behaviour is double click and scrollwheel up/down to zoom in, drag to pan. The plugin defines plot.zoom({ center }), plot.zoomOut() and plot.pan(offset) so you easily can add custom controls. It also fires a "plotpan" and "plotzoom" event when something happens, useful for synchronizing plots. Options: zoom: { interactive: false trigger: "dblclick" // or "click" for single click amount: 1.5 // 2 = 200% (zoom in), 0.5 = 50% (zoom out) } pan: { interactive: false cursor: "move" // CSS mouse cursor value used when dragging, e.g. "pointer" frameRate: 20 } xaxis, yaxis, x2axis, y2axis: { zoomRange: null // or [number, number] (min range, max range) or false panRange: null // or [number, number] (min, max) or false } "interactive" enables the built-in drag/click behaviour. If you enable interactive for pan, then you'll have a basic plot that supports moving around; the same for zoom. "amount" specifies the default amount to zoom in (so 1.5 = 150%) relative to the current viewport. "cursor" is a standard CSS mouse cursor string used for visual feedback to the user when dragging. "frameRate" specifies the maximum number of times per second the plot will update itself while the user is panning around on it (set to null to disable intermediate pans, the plot will then not update until the mouse button is released). "zoomRange" is the interval in which zooming can happen, e.g. with zoomRange: [1, 100] the zoom will never scale the axis so that the difference between min and max is smaller than 1 or larger than 100. You can set either end to null to ignore, e.g. [1, null]. If you set zoomRange to false, zooming on that axis will be disabled. "panRange" confines the panning to stay within a range, e.g. with panRange: [-10, 20] panning stops at -10 in one end and at 20 in the other. Either can be null, e.g. [-10, null]. If you set panRange to false, panning on that axis will be disabled. Example API usage: plot = $.plot(...); // zoom default amount in on the pixel (10, 20) plot.zoom({ center: { left: 10, top: 20 } }); // zoom out again plot.zoomOut({ center: { left: 10, top: 20 } }); // zoom 200% in on the pixel (10, 20) plot.zoom({ amount: 2, center: { left: 10, top: 20 } }); // pan 100 pixels to the left and 20 down plot.pan({ left: -100, top: 20 }) Here, "center" specifies where the center of the zooming should happen. Note that this is defined in pixel space, not the space of the data points (you can use the p2c helpers on the axes in Flot to help you convert between these). "amount" is the amount to zoom the viewport relative to the current range, so 1 is 100% (i.e. no change), 1.5 is 150% (zoom in), 0.7 is 70% (zoom out). You can set the default in the options. */ // First two dependencies, jquery.event.drag.js and // jquery.mousewheel.js, we put them inline here to save people the // effort of downloading them. /* jquery.event.drag.js ~ v1.5 ~ Copyright (c) 2008, Three Dub Media (http://threedubmedia.com) Licensed under the MIT License ~ http://threedubmedia.googlecode.com/files/MIT-LICENSE.txt */ (function(E){E.fn.drag=function(L,K,J){if(K){this.bind("dragstart",L)}if(J){this.bind("dragend",J)}return !L?this.trigger("drag"):this.bind("drag",K?K:L)};var A=E.event,B=A.special,F=B.drag={not:":input",distance:0,which:1,dragging:false,setup:function(J){J=E.extend({distance:F.distance,which:F.which,not:F.not},J||{});J.distance=I(J.distance);A.add(this,"mousedown",H,J);if(this.attachEvent){this.attachEvent("ondragstart",D)}},teardown:function(){A.remove(this,"mousedown",H);if(this===F.dragging){F.dragging=F.proxy=false}G(this,true);if(this.detachEvent){this.detachEvent("ondragstart",D)}}};B.dragstart=B.dragend={setup:function(){},teardown:function(){}};function H(L){var K=this,J,M=L.data||{};if(M.elem){K=L.dragTarget=M.elem;L.dragProxy=F.proxy||K;L.cursorOffsetX=M.pageX-M.left;L.cursorOffsetY=M.pageY-M.top;L.offsetX=L.pageX-L.cursorOffsetX;L.offsetY=L.pageY-L.cursorOffsetY}else{if(F.dragging||(M.which>0&&L.which!=M.which)||E(L.target).is(M.not)){return }}switch(L.type){case"mousedown":E.extend(M,E(K).offset(),{elem:K,target:L.target,pageX:L.pageX,pageY:L.pageY});A.add(document,"mousemove mouseup",H,M);G(K,false);F.dragging=null;return false;case !F.dragging&&"mousemove":if(I(L.pageX-M.pageX)+I(L.pageY-M.pageY)<M.distance){break}L.target=M.target;J=C(L,"dragstart",K);if(J!==false){F.dragging=K;F.proxy=L.dragProxy=E(J||K)[0]}case"mousemove":if(F.dragging){J=C(L,"drag",K);if(B.drop){B.drop.allowed=(J!==false);B.drop.handler(L)}if(J!==false){break}L.type="mouseup"}case"mouseup":A.remove(document,"mousemove mouseup",H);if(F.dragging){if(B.drop){B.drop.handler(L)}C(L,"dragend",K)}G(K,true);F.dragging=F.proxy=M.elem=false;break}return true}function C(M,K,L){M.type=K;var J=E.event.handle.call(L,M);return J===false?false:J||M.result}function I(J){return Math.pow(J,2)}function D(){return(F.dragging===false)}function G(K,J){if(!K){return }K.unselectable=J?"off":"on";K.onselectstart=function(){return J};if(K.style){K.style.MozUserSelect=J?"":"none"}}})(jQuery); /* jquery.mousewheel.min.js * Copyright (c) 2009 Brandon Aaron (http://brandonaaron.net) * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses. * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers. * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix. * * Version: 3.0.2 * * Requires: 1.2.2+ */ (function(c){var a=["DOMMouseScroll","mousewheel"];c.event.special.mousewheel={setup:function(){if(this.addEventListener){for(var d=a.length;d;){this.addEventListener(a[--d],b,false)}}else{this.onmousewheel=b}},teardown:function(){if(this.removeEventListener){for(var d=a.length;d;){this.removeEventListener(a[--d],b,false)}}else{this.onmousewheel=null}}};c.fn.extend({mousewheel:function(d){return d?this.bind("mousewheel",d):this.trigger("mousewheel")},unmousewheel:function(d){return this.unbind("mousewheel",d)}});function b(f){var d=[].slice.call(arguments,1),g=0,e=true;f=c.event.fix(f||window.event);f.type="mousewheel";if(f.wheelDelta){g=f.wheelDelta/120}if(f.detail){g=-f.detail/3}d.unshift(f,g);return c.event.handle.apply(this,d)}})(jQuery); (function ($) { var options = { xaxis: { zoomRange: null, // or [number, number] (min range, max range) panRange: null // or [number, number] (min, max) }, zoom: { interactive: false, trigger: "dblclick", // or "click" for single click amount: 1.5 // how much to zoom relative to current position, 2 = 200% (zoom in), 0.5 = 50% (zoom out) }, pan: { interactive: false, cursor: "move", frameRate: 20 } }; function init(plot) { function onZoomClick(e, zoomOut) { var c = plot.offset(); c.left = e.pageX - c.left; c.top = e.pageY - c.top; if (zoomOut) plot.zoomOut({ center: c }); else plot.zoom({ center: c }); } function onMouseWheel(e, delta) { onZoomClick(e, delta < 0); return false; } var prevCursor = 'default', prevPageX = 0, prevPageY = 0, panTimeout = null; function onDragStart(e) { if (e.which != 1) // only accept left-click return false; var c = plot.getPlaceholder().css('cursor'); if (c) prevCursor = c; plot.getPlaceholder().css('cursor', plot.getOptions().pan.cursor); prevPageX = e.pageX; prevPageY = e.pageY; } function onDrag(e) { var frameRate = plot.getOptions().pan.frameRate; if (panTimeout || !frameRate) return; panTimeout = setTimeout(function () { plot.pan({ left: prevPageX - e.pageX, top: prevPageY - e.pageY }); prevPageX = e.pageX; prevPageY = e.pageY; panTimeout = null; }, 1 / frameRate * 1000); } function onDragEnd(e) { if (panTimeout) { clearTimeout(panTimeout); panTimeout = null; } plot.getPlaceholder().css('cursor', prevCursor); plot.pan({ left: prevPageX - e.pageX, top: prevPageY - e.pageY }); } function bindEvents(plot, eventHolder) { var o = plot.getOptions(); if (o.zoom.interactive) { eventHolder[o.zoom.trigger](onZoomClick); eventHolder.mousewheel(onMouseWheel); } if (o.pan.interactive) { eventHolder.bind("dragstart", { distance: 10 }, onDragStart); eventHolder.bind("drag", onDrag); eventHolder.bind("dragend", onDragEnd); } } plot.zoomOut = function (args) { if (!args) args = {}; if (!args.amount) args.amount = plot.getOptions().zoom.amount args.amount = 1 / args.amount; plot.zoom(args); } plot.zoom = function (args) { if (!args) args = {}; var c = args.center, amount = args.amount || plot.getOptions().zoom.amount, w = plot.width(), h = plot.height(); if (!c) c = { left: w / 2, top: h / 2 }; var xf = c.left / w, yf = c.top / h, minmax = { x: { min: c.left - xf * w / amount, max: c.left + (1 - xf) * w / amount }, y: { min: c.top - yf * h / amount, max: c.top + (1 - yf) * h / amount } }; $.each(plot.getAxes(), function(_, axis) { var opts = axis.options, min = minmax[axis.direction].min, max = minmax[axis.direction].max, zr = opts.zoomRange; if (zr === false) // no zooming on this axis return; min = axis.c2p(min); max = axis.c2p(max); if (min > max) { // make sure min < max var tmp = min; min = max; max = tmp; } var range = max - min; if (zr && ((zr[0] != null && range < zr[0]) || (zr[1] != null && range > zr[1]))) return; opts.min = min; opts.max = max; }); plot.setupGrid(); plot.draw(); if (!args.preventEvent) plot.getPlaceholder().trigger("plotzoom", [ plot ]); } plot.pan = function (args) { var delta = { x: +args.left, y: +args.top }; if (isNaN(delta.x)) delta.x = 0; if (isNaN(delta.y)) delta.y = 0; $.each(plot.getAxes(), function (_, axis) { var opts = axis.options, min, max, d = delta[axis.direction]; min = axis.c2p(axis.p2c(axis.min) + d), max = axis.c2p(axis.p2c(axis.max) + d); var pr = opts.panRange; if (pr === false) // no panning on this axis return; if (pr) { // check whether we hit the wall if (pr[0] != null && pr[0] > min) { d = pr[0] - min; min += d; max += d; } if (pr[1] != null && pr[1] < max) { d = pr[1] - max; min += d; max += d; } } opts.min = min; opts.max = max; }); plot.setupGrid(); plot.draw(); if (!args.preventEvent) plot.getPlaceholder().trigger("plotpan", [ plot ]); } function shutdown(plot, eventHolder) { eventHolder.unbind(plot.getOptions().zoom.trigger, onZoomClick); eventHolder.unbind("mousewheel", onMouseWheel); eventHolder.unbind("dragstart", onDragStart); eventHolder.unbind("drag", onDrag); eventHolder.unbind("dragend", onDragEnd); if (panTimeout) clearTimeout(panTimeout); } plot.hooks.bindEvents.push(bindEvents); plot.hooks.shutdown.push(shutdown); } $.plot.plugins.push({ init: init, options: options, name: 'navigate', version: '1.3' }); })(jQuery);
JavaScript
/* Flot plugin that adds some extra symbols for plotting points. The symbols are accessed as strings through the standard symbol choice: series: { points: { symbol: "square" // or "diamond", "triangle", "cross" } } */ (function ($) { function processRawData(plot, series, datapoints) { // we normalize the area of each symbol so it is approximately the // same as a circle of the given radius var handlers = { square: function (ctx, x, y, radius, shadow) { // pi * r^2 = (2s)^2 => s = r * sqrt(pi)/2 var size = radius * Math.sqrt(Math.PI) / 2; ctx.rect(x - size, y - size, size + size, size + size); }, diamond: function (ctx, x, y, radius, shadow) { // pi * r^2 = 2s^2 => s = r * sqrt(pi/2) var size = radius * Math.sqrt(Math.PI / 2); ctx.moveTo(x - size, y); ctx.lineTo(x, y - size); ctx.lineTo(x + size, y); ctx.lineTo(x, y + size); ctx.lineTo(x - size, y); }, triangle: function (ctx, x, y, radius, shadow) { // pi * r^2 = 1/2 * s^2 * sin (pi / 3) => s = r * sqrt(2 * pi / sin(pi / 3)) var size = radius * Math.sqrt(2 * Math.PI / Math.sin(Math.PI / 3)); var height = size * Math.sin(Math.PI / 3); ctx.moveTo(x - size/2, y + height/2); ctx.lineTo(x + size/2, y + height/2); if (!shadow) { ctx.lineTo(x, y - height/2); ctx.lineTo(x - size/2, y + height/2); } }, cross: function (ctx, x, y, radius, shadow) { // pi * r^2 = (2s)^2 => s = r * sqrt(pi)/2 var size = radius * Math.sqrt(Math.PI) / 2; ctx.moveTo(x - size, y - size); ctx.lineTo(x + size, y + size); ctx.moveTo(x - size, y + size); ctx.lineTo(x + size, y - size); } } var s = series.points.symbol; if (handlers[s]) series.points.symbol = handlers[s]; } function init(plot) { plot.hooks.processDatapoints.push(processRawData); } $.plot.plugins.push({ init: init, name: 'symbols', version: '1.0' }); })(jQuery);
JavaScript
/* Flot plugin for automatically redrawing plots when the placeholder size changes, e.g. on window resizes. It works by listening for changes on the placeholder div (through the jQuery resize event plugin) - if the size changes, it will redraw the plot. There are no options. If you need to disable the plugin for some plots, you can just fix the size of their placeholders. */ /* Inline dependency: * jQuery resize event - v1.1 - 3/14/2010 * http://benalman.com/projects/jquery-resize-plugin/ * * Copyright (c) 2010 "Cowboy" Ben Alman * Dual licensed under the MIT and GPL licenses. * http://benalman.com/about/license/ */ (function($,h,c){var a=$([]),e=$.resize=$.extend($.resize,{}),i,k="setTimeout",j="resize",d=j+"-special-event",b="delay",f="throttleWindow";e[b]=250;e[f]=true;$.event.special[j]={setup:function(){if(!e[f]&&this[k]){return false}var l=$(this);a=a.add(l);$.data(this,d,{w:l.width(),h:l.height()});if(a.length===1){g()}},teardown:function(){if(!e[f]&&this[k]){return false}var l=$(this);a=a.not(l);l.removeData(d);if(!a.length){clearTimeout(i)}},add:function(l){if(!e[f]&&this[k]){return false}var n;function m(s,o,p){var q=$(this),r=$.data(this,d);r.w=o!==c?o:q.width();r.h=p!==c?p:q.height();n.apply(this,arguments)}if($.isFunction(l)){n=l;return m}else{n=l.handler;l.handler=m}}};function g(){i=h[k](function(){a.each(function(){var n=$(this),m=n.width(),l=n.height(),o=$.data(this,d);if(m!==o.w||l!==o.h){n.trigger(j,[o.w=m,o.h=l])}});g()},e[b])}})(jQuery,this); (function ($) { var options = { }; // no options function init(plot) { function onResize() { var placeholder = plot.getPlaceholder(); // somebody might have hidden us and we can't plot // when we don't have the dimensions if (placeholder.width() == 0 || placeholder.height() == 0) return; plot.resize(); plot.setupGrid(); plot.draw(); } function bindEvents(plot, eventHolder) { plot.getPlaceholder().resize(onResize); } function shutdown(plot, eventHolder) { plot.getPlaceholder().unbind("resize", onResize); } plot.hooks.bindEvents.push(bindEvents); plot.hooks.shutdown.push(shutdown); } $.plot.plugins.push({ init: init, options: options, name: 'resize', version: '1.0' }); })(jQuery);
JavaScript
/* Flot plugin for thresholding data. Controlled through the option "threshold" in either the global series options series: { threshold: { below: number color: colorspec } } or in a specific series $.plot($("#placeholder"), [{ data: [ ... ], threshold: { ... }}]) The data points below "below" are drawn with the specified color. This makes it easy to mark points below 0, e.g. for budget data. Internally, the plugin works by splitting the data into two series, above and below the threshold. The extra series below the threshold will have its label cleared and the special "originSeries" attribute set to the original series. You may need to check for this in hover events. */ (function ($) { var options = { series: { threshold: null } // or { below: number, color: color spec} }; function init(plot) { function thresholdData(plot, s, datapoints) { if (!s.threshold) return; var ps = datapoints.pointsize, i, x, y, p, prevp, thresholded = $.extend({}, s); // note: shallow copy thresholded.datapoints = { points: [], pointsize: ps }; thresholded.label = null; thresholded.color = s.threshold.color; thresholded.threshold = null; thresholded.originSeries = s; thresholded.data = []; var below = s.threshold.below, origpoints = datapoints.points, addCrossingPoints = s.lines.show; threspoints = []; newpoints = []; for (i = 0; i < origpoints.length; i += ps) { x = origpoints[i] y = origpoints[i + 1]; prevp = p; if (y < below) p = threspoints; else p = newpoints; if (addCrossingPoints && prevp != p && x != null && i > 0 && origpoints[i - ps] != null) { var interx = (x - origpoints[i - ps]) / (y - origpoints[i - ps + 1]) * (below - y) + x; prevp.push(interx); prevp.push(below); for (m = 2; m < ps; ++m) prevp.push(origpoints[i + m]); p.push(null); // start new segment p.push(null); for (m = 2; m < ps; ++m) p.push(origpoints[i + m]); p.push(interx); p.push(below); for (m = 2; m < ps; ++m) p.push(origpoints[i + m]); } p.push(x); p.push(y); } datapoints.points = newpoints; thresholded.datapoints.points = threspoints; if (thresholded.datapoints.points.length > 0) plot.getData().push(thresholded); // FIXME: there are probably some edge cases left in bars } plot.hooks.processDatapoints.push(thresholdData); } $.plot.plugins.push({ init: init, options: options, name: 'threshold', version: '1.0' }); })(jQuery);
JavaScript
/* Flot plugin for selecting regions. The plugin defines the following options: selection: { mode: null or "x" or "y" or "xy", color: color } Selection support is enabled by setting the mode to one of "x", "y" or "xy". In "x" mode, the user will only be able to specify the x range, similarly for "y" mode. For "xy", the selection becomes a rectangle where both ranges can be specified. "color" is color of the selection (if you need to change the color later on, you can get to it with plot.getOptions().selection.color). When selection support is enabled, a "plotselected" event will be emitted on the DOM element you passed into the plot function. The event handler gets a parameter with the ranges selected on the axes, like this: placeholder.bind("plotselected", function(event, ranges) { alert("You selected " + ranges.xaxis.from + " to " + ranges.xaxis.to) // similar for yaxis - with multiple axes, the extra ones are in // x2axis, x3axis, ... }); The "plotselected" event is only fired when the user has finished making the selection. A "plotselecting" event is fired during the process with the same parameters as the "plotselected" event, in case you want to know what's happening while it's happening, A "plotunselected" event with no arguments is emitted when the user clicks the mouse to remove the selection. The plugin allso adds the following methods to the plot object: - setSelection(ranges, preventEvent) Set the selection rectangle. The passed in ranges is on the same form as returned in the "plotselected" event. If the selection mode is "x", you should put in either an xaxis range, if the mode is "y" you need to put in an yaxis range and both xaxis and yaxis if the selection mode is "xy", like this: setSelection({ xaxis: { from: 0, to: 10 }, yaxis: { from: 40, to: 60 } }); setSelection will trigger the "plotselected" event when called. If you don't want that to happen, e.g. if you're inside a "plotselected" handler, pass true as the second parameter. If you are using multiple axes, you can specify the ranges on any of those, e.g. as x2axis/x3axis/... instead of xaxis, the plugin picks the first one it sees. - clearSelection(preventEvent) Clear the selection rectangle. Pass in true to avoid getting a "plotunselected" event. - getSelection() Returns the current selection in the same format as the "plotselected" event. If there's currently no selection, the function returns null. */ (function ($) { function init(plot) { var selection = { first: { x: -1, y: -1}, second: { x: -1, y: -1}, show: false, active: false }; // FIXME: The drag handling implemented here should be // abstracted out, there's some similar code from a library in // the navigation plugin, this should be massaged a bit to fit // the Flot cases here better and reused. Doing this would // make this plugin much slimmer. var savedhandlers = {}; var mouseUpHandler = null; function onMouseMove(e) { if (selection.active) { updateSelection(e); plot.getPlaceholder().trigger("plotselecting", [ getSelection() ]); } } function onMouseDown(e) { if (e.which != 1) // only accept left-click return; // cancel out any text selections document.body.focus(); // prevent text selection and drag in old-school browsers if (document.onselectstart !== undefined && savedhandlers.onselectstart == null) { savedhandlers.onselectstart = document.onselectstart; document.onselectstart = function () { return false; }; } if (document.ondrag !== undefined && savedhandlers.ondrag == null) { savedhandlers.ondrag = document.ondrag; document.ondrag = function () { return false; }; } setSelectionPos(selection.first, e); selection.active = true; // this is a bit silly, but we have to use a closure to be // able to whack the same handler again mouseUpHandler = function (e) { onMouseUp(e); }; $(document).one("mouseup", mouseUpHandler); } function onMouseUp(e) { mouseUpHandler = null; // revert drag stuff for old-school browsers if (document.onselectstart !== undefined) document.onselectstart = savedhandlers.onselectstart; if (document.ondrag !== undefined) document.ondrag = savedhandlers.ondrag; // no more dragging selection.active = false; updateSelection(e); if (selectionIsSane()) triggerSelectedEvent(); else { // this counts as a clear plot.getPlaceholder().trigger("plotunselected", [ ]); plot.getPlaceholder().trigger("plotselecting", [ null ]); } return false; } function getSelection() { if (!selectionIsSane()) return null; var r = {}, c1 = selection.first, c2 = selection.second; $.each(plot.getAxes(), function (name, axis) { if (axis.used) { var p1 = axis.c2p(c1[axis.direction]), p2 = axis.c2p(c2[axis.direction]); r[name] = { from: Math.min(p1, p2), to: Math.max(p1, p2) }; } }); return r; } function triggerSelectedEvent() { var r = getSelection(); plot.getPlaceholder().trigger("plotselected", [ r ]); // backwards-compat stuff, to be removed in future if (r.xaxis && r.yaxis) plot.getPlaceholder().trigger("selected", [ { x1: r.xaxis.from, y1: r.yaxis.from, x2: r.xaxis.to, y2: r.yaxis.to } ]); } function clamp(min, value, max) { return value < min ? min: (value > max ? max: value); } function setSelectionPos(pos, e) { var o = plot.getOptions(); var offset = plot.getPlaceholder().offset(); var plotOffset = plot.getPlotOffset(); pos.x = clamp(0, e.pageX - offset.left - plotOffset.left, plot.width()); pos.y = clamp(0, e.pageY - offset.top - plotOffset.top, plot.height()); if (o.selection.mode == "y") pos.x = pos == selection.first ? 0 : plot.width(); if (o.selection.mode == "x") pos.y = pos == selection.first ? 0 : plot.height(); } function updateSelection(pos) { if (pos.pageX == null) return; setSelectionPos(selection.second, pos); if (selectionIsSane()) { selection.show = true; plot.triggerRedrawOverlay(); } else clearSelection(true); } function clearSelection(preventEvent) { if (selection.show) { selection.show = false; plot.triggerRedrawOverlay(); if (!preventEvent) plot.getPlaceholder().trigger("plotunselected", [ ]); } } // function taken from markings support in Flot function extractRange(ranges, coord) { var axis, from, to, key, axes = plot.getAxes(); for (var k in axes) { axis = axes[k]; if (axis.direction == coord) { key = coord + axis.n + "axis"; if (!ranges[key] && axis.n == 1) key = coord + "axis"; // support x1axis as xaxis if (ranges[key]) { from = ranges[key].from; to = ranges[key].to; break; } } } // backwards-compat stuff - to be removed in future if (!ranges[key]) { axis = coord == "x" ? plot.getXAxes()[0] : plot.getYAxes()[0]; from = ranges[coord + "1"]; to = ranges[coord + "2"]; } // auto-reverse as an added bonus if (from != null && to != null && from > to) { var tmp = from; from = to; to = tmp; } return { from: from, to: to, axis: axis }; } function setSelection(ranges, preventEvent) { var axis, range, o = plot.getOptions(); if (o.selection.mode == "y") { selection.first.x = 0; selection.second.x = plot.width(); } else { range = extractRange(ranges, "x"); selection.first.x = range.axis.p2c(range.from); selection.second.x = range.axis.p2c(range.to); } if (o.selection.mode == "x") { selection.first.y = 0; selection.second.y = plot.height(); } else { range = extractRange(ranges, "y"); selection.first.y = range.axis.p2c(range.from); selection.second.y = range.axis.p2c(range.to); } selection.show = true; plot.triggerRedrawOverlay(); if (!preventEvent && selectionIsSane()) triggerSelectedEvent(); } function selectionIsSane() { var minSize = 5; return Math.abs(selection.second.x - selection.first.x) >= minSize && Math.abs(selection.second.y - selection.first.y) >= minSize; } plot.clearSelection = clearSelection; plot.setSelection = setSelection; plot.getSelection = getSelection; plot.hooks.bindEvents.push(function(plot, eventHolder) { var o = plot.getOptions(); if (o.selection.mode != null) { eventHolder.mousemove(onMouseMove); eventHolder.mousedown(onMouseDown); } }); plot.hooks.drawOverlay.push(function (plot, ctx) { // draw selection if (selection.show && selectionIsSane()) { var plotOffset = plot.getPlotOffset(); var o = plot.getOptions(); ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); var c = $.color.parse(o.selection.color); ctx.strokeStyle = c.scale('a', 0.8).toString(); ctx.lineWidth = 1; ctx.lineJoin = "round"; ctx.fillStyle = c.scale('a', 0.4).toString(); var x = Math.min(selection.first.x, selection.second.x), y = Math.min(selection.first.y, selection.second.y), w = Math.abs(selection.second.x - selection.first.x), h = Math.abs(selection.second.y - selection.first.y); ctx.fillRect(x, y, w, h); ctx.strokeRect(x, y, w, h); ctx.restore(); } }); plot.hooks.shutdown.push(function (plot, eventHolder) { eventHolder.unbind("mousemove", onMouseMove); eventHolder.unbind("mousedown", onMouseDown); if (mouseUpHandler) $(document).unbind("mouseup", mouseUpHandler); }); } $.plot.plugins.push({ init: init, options: { selection: { mode: null, // one of null, "x", "y" or "xy" color: "#e8cfac" } }, name: 'selection', version: '1.1' }); })(jQuery);
JavaScript
/* Plugin for jQuery for working with colors. * * Version 1.1. * * Inspiration from jQuery color animation plugin by John Resig. * * Released under the MIT license by Ole Laursen, October 2009. * * Examples: * * $.color.parse("#fff").scale('rgb', 0.25).add('a', -0.5).toString() * var c = $.color.extract($("#mydiv"), 'background-color'); * console.log(c.r, c.g, c.b, c.a); * $.color.make(100, 50, 25, 0.4).toString() // returns "rgba(100,50,25,0.4)" * * Note that .scale() and .add() return the same modified object * instead of making a new one. * * V. 1.1: Fix error handling so e.g. parsing an empty string does * produce a color rather than just crashing. */ (function($) { $.color = {}; // construct color object with some convenient chainable helpers $.color.make = function (r, g, b, a) { var o = {}; o.r = r || 0; o.g = g || 0; o.b = b || 0; o.a = a != null ? a : 1; o.add = function (c, d) { for (var i = 0; i < c.length; ++i) o[c.charAt(i)] += d; return o.normalize(); }; o.scale = function (c, f) { for (var i = 0; i < c.length; ++i) o[c.charAt(i)] *= f; return o.normalize(); }; o.toString = function () { if (o.a >= 1.0) { return "rgb("+[o.r, o.g, o.b].join(",")+")"; } else { return "rgba("+[o.r, o.g, o.b, o.a].join(",")+")"; } }; o.normalize = function () { function clamp(min, value, max) { return value < min ? min: (value > max ? max: value); } o.r = clamp(0, parseInt(o.r), 255); o.g = clamp(0, parseInt(o.g), 255); o.b = clamp(0, parseInt(o.b), 255); o.a = clamp(0, o.a, 1); return o; }; o.clone = function () { return $.color.make(o.r, o.b, o.g, o.a); }; return o.normalize(); } // extract CSS color property from element, going up in the DOM // if it's "transparent" $.color.extract = function (elem, css) { var c; do { c = elem.css(css).toLowerCase(); // keep going until we find an element that has color, or // we hit the body if (c != '' && c != 'transparent') break; elem = elem.parent(); } while (!$.nodeName(elem.get(0), "body")); // catch Safari's way of signalling transparent if (c == "rgba(0, 0, 0, 0)") c = "transparent"; return $.color.parse(c); } // parse CSS color string (like "rgb(10, 32, 43)" or "#fff"), // returns color object, if parsing failed, you get black (0, 0, // 0) out $.color.parse = function (str) { var res, m = $.color.make; // Look for rgb(num,num,num) if (res = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(str)) return m(parseInt(res[1], 10), parseInt(res[2], 10), parseInt(res[3], 10)); // Look for rgba(num,num,num,num) if (res = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str)) return m(parseInt(res[1], 10), parseInt(res[2], 10), parseInt(res[3], 10), parseFloat(res[4])); // Look for rgb(num%,num%,num%) if (res = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(str)) return m(parseFloat(res[1])*2.55, parseFloat(res[2])*2.55, parseFloat(res[3])*2.55); // Look for rgba(num%,num%,num%,num) if (res = /rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str)) return m(parseFloat(res[1])*2.55, parseFloat(res[2])*2.55, parseFloat(res[3])*2.55, parseFloat(res[4])); // Look for #a0b1c2 if (res = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(str)) return m(parseInt(res[1], 16), parseInt(res[2], 16), parseInt(res[3], 16)); // Look for #fff if (res = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(str)) return m(parseInt(res[1]+res[1], 16), parseInt(res[2]+res[2], 16), parseInt(res[3]+res[3], 16)); // Otherwise, we're most likely dealing with a named color var name = $.trim(str).toLowerCase(); if (name == "transparent") return m(255, 255, 255, 0); else { // default to black res = lookupColors[name] || [0, 0, 0]; return m(res[0], res[1], res[2]); } } var lookupColors = { aqua:[0,255,255], azure:[240,255,255], beige:[245,245,220], black:[0,0,0], blue:[0,0,255], brown:[165,42,42], cyan:[0,255,255], darkblue:[0,0,139], darkcyan:[0,139,139], darkgrey:[169,169,169], darkgreen:[0,100,0], darkkhaki:[189,183,107], darkmagenta:[139,0,139], darkolivegreen:[85,107,47], darkorange:[255,140,0], darkorchid:[153,50,204], darkred:[139,0,0], darksalmon:[233,150,122], darkviolet:[148,0,211], fuchsia:[255,0,255], gold:[255,215,0], green:[0,128,0], indigo:[75,0,130], khaki:[240,230,140], lightblue:[173,216,230], lightcyan:[224,255,255], lightgreen:[144,238,144], lightgrey:[211,211,211], lightpink:[255,182,193], lightyellow:[255,255,224], lime:[0,255,0], magenta:[255,0,255], maroon:[128,0,0], navy:[0,0,128], olive:[128,128,0], orange:[255,165,0], pink:[255,192,203], purple:[128,0,128], violet:[128,0,128], red:[255,0,0], silver:[192,192,192], white:[255,255,255], yellow:[255,255,0] }; })(jQuery);
JavaScript
// Copyright 2006 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Known Issues: // // * Patterns only support repeat. // * Radial gradient are not implemented. The VML version of these look very // different from the canvas one. // * Clipping paths are not implemented. // * Coordsize. The width and height attribute have higher priority than the // width and height style values which isn't correct. // * Painting mode isn't implemented. // * Canvas width/height should is using content-box by default. IE in // Quirks mode will draw the canvas using border-box. Either change your // doctype to HTML5 // (http://www.whatwg.org/specs/web-apps/current-work/#the-doctype) // or use Box Sizing Behavior from WebFX // (http://webfx.eae.net/dhtml/boxsizing/boxsizing.html) // * Non uniform scaling does not correctly scale strokes. // * Filling very large shapes (above 5000 points) is buggy. // * Optimize. There is always room for speed improvements. // Only add this code if we do not already have a canvas implementation if (!document.createElement('canvas').getContext) { (function() { // alias some functions to make (compiled) code shorter var m = Math; var mr = m.round; var ms = m.sin; var mc = m.cos; var abs = m.abs; var sqrt = m.sqrt; // this is used for sub pixel precision var Z = 10; var Z2 = Z / 2; /** * This funtion is assigned to the <canvas> elements as element.getContext(). * @this {HTMLElement} * @return {CanvasRenderingContext2D_} */ function getContext() { return this.context_ || (this.context_ = new CanvasRenderingContext2D_(this)); } var slice = Array.prototype.slice; /** * Binds a function to an object. The returned function will always use the * passed in {@code obj} as {@code this}. * * Example: * * g = bind(f, obj, a, b) * g(c, d) // will do f.call(obj, a, b, c, d) * * @param {Function} f The function to bind the object to * @param {Object} obj The object that should act as this when the function * is called * @param {*} var_args Rest arguments that will be used as the initial * arguments when the function is called * @return {Function} A new function that has bound this */ function bind(f, obj, var_args) { var a = slice.call(arguments, 2); return function() { return f.apply(obj, a.concat(slice.call(arguments))); }; } function encodeHtmlAttribute(s) { return String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;'); } function addNamespacesAndStylesheet(doc) { // create xmlns if (!doc.namespaces['g_vml_']) { doc.namespaces.add('g_vml_', 'urn:schemas-microsoft-com:vml', '#default#VML'); } if (!doc.namespaces['g_o_']) { doc.namespaces.add('g_o_', 'urn:schemas-microsoft-com:office:office', '#default#VML'); } // Setup default CSS. Only add one style sheet per document if (!doc.styleSheets['ex_canvas_']) { var ss = doc.createStyleSheet(); ss.owningElement.id = 'ex_canvas_'; ss.cssText = 'canvas{display:inline-block;overflow:hidden;' + // default size is 300x150 in Gecko and Opera 'text-align:left;width:300px;height:150px}'; } } // Add namespaces and stylesheet at startup. addNamespacesAndStylesheet(document); var G_vmlCanvasManager_ = { init: function(opt_doc) { if (/MSIE/.test(navigator.userAgent) && !window.opera) { var doc = opt_doc || document; // Create a dummy element so that IE will allow canvas elements to be // recognized. doc.createElement('canvas'); doc.attachEvent('onreadystatechange', bind(this.init_, this, doc)); } }, init_: function(doc) { // find all canvas elements var els = doc.getElementsByTagName('canvas'); for (var i = 0; i < els.length; i++) { this.initElement(els[i]); } }, /** * Public initializes a canvas element so that it can be used as canvas * element from now on. This is called automatically before the page is * loaded but if you are creating elements using createElement you need to * make sure this is called on the element. * @param {HTMLElement} el The canvas element to initialize. * @return {HTMLElement} the element that was created. */ initElement: function(el) { if (!el.getContext) { el.getContext = getContext; // Add namespaces and stylesheet to document of the element. addNamespacesAndStylesheet(el.ownerDocument); // Remove fallback content. There is no way to hide text nodes so we // just remove all childNodes. We could hide all elements and remove // text nodes but who really cares about the fallback content. el.innerHTML = ''; // do not use inline function because that will leak memory el.attachEvent('onpropertychange', onPropertyChange); el.attachEvent('onresize', onResize); var attrs = el.attributes; if (attrs.width && attrs.width.specified) { // TODO: use runtimeStyle and coordsize // el.getContext().setWidth_(attrs.width.nodeValue); el.style.width = attrs.width.nodeValue + 'px'; } else { el.width = el.clientWidth; } if (attrs.height && attrs.height.specified) { // TODO: use runtimeStyle and coordsize // el.getContext().setHeight_(attrs.height.nodeValue); el.style.height = attrs.height.nodeValue + 'px'; } else { el.height = el.clientHeight; } //el.getContext().setCoordsize_() } return el; } }; function onPropertyChange(e) { var el = e.srcElement; switch (e.propertyName) { case 'width': el.getContext().clearRect(); el.style.width = el.attributes.width.nodeValue + 'px'; // In IE8 this does not trigger onresize. el.firstChild.style.width = el.clientWidth + 'px'; break; case 'height': el.getContext().clearRect(); el.style.height = el.attributes.height.nodeValue + 'px'; el.firstChild.style.height = el.clientHeight + 'px'; break; } } function onResize(e) { var el = e.srcElement; if (el.firstChild) { el.firstChild.style.width = el.clientWidth + 'px'; el.firstChild.style.height = el.clientHeight + 'px'; } } G_vmlCanvasManager_.init(); // precompute "00" to "FF" var decToHex = []; for (var i = 0; i < 16; i++) { for (var j = 0; j < 16; j++) { decToHex[i * 16 + j] = i.toString(16) + j.toString(16); } } function createMatrixIdentity() { return [ [1, 0, 0], [0, 1, 0], [0, 0, 1] ]; } function matrixMultiply(m1, m2) { var result = createMatrixIdentity(); for (var x = 0; x < 3; x++) { for (var y = 0; y < 3; y++) { var sum = 0; for (var z = 0; z < 3; z++) { sum += m1[x][z] * m2[z][y]; } result[x][y] = sum; } } return result; } function copyState(o1, o2) { o2.fillStyle = o1.fillStyle; o2.lineCap = o1.lineCap; o2.lineJoin = o1.lineJoin; o2.lineWidth = o1.lineWidth; o2.miterLimit = o1.miterLimit; o2.shadowBlur = o1.shadowBlur; o2.shadowColor = o1.shadowColor; o2.shadowOffsetX = o1.shadowOffsetX; o2.shadowOffsetY = o1.shadowOffsetY; o2.strokeStyle = o1.strokeStyle; o2.globalAlpha = o1.globalAlpha; o2.font = o1.font; o2.textAlign = o1.textAlign; o2.textBaseline = o1.textBaseline; o2.arcScaleX_ = o1.arcScaleX_; o2.arcScaleY_ = o1.arcScaleY_; o2.lineScale_ = o1.lineScale_; } var colorData = { aliceblue: '#F0F8FF', antiquewhite: '#FAEBD7', aquamarine: '#7FFFD4', azure: '#F0FFFF', beige: '#F5F5DC', bisque: '#FFE4C4', black: '#000000', blanchedalmond: '#FFEBCD', blueviolet: '#8A2BE2', brown: '#A52A2A', burlywood: '#DEB887', cadetblue: '#5F9EA0', chartreuse: '#7FFF00', chocolate: '#D2691E', coral: '#FF7F50', cornflowerblue: '#6495ED', cornsilk: '#FFF8DC', crimson: '#DC143C', cyan: '#00FFFF', darkblue: '#00008B', darkcyan: '#008B8B', darkgoldenrod: '#B8860B', darkgray: '#A9A9A9', darkgreen: '#006400', darkgrey: '#A9A9A9', darkkhaki: '#BDB76B', darkmagenta: '#8B008B', darkolivegreen: '#556B2F', darkorange: '#FF8C00', darkorchid: '#9932CC', darkred: '#8B0000', darksalmon: '#E9967A', darkseagreen: '#8FBC8F', darkslateblue: '#483D8B', darkslategray: '#2F4F4F', darkslategrey: '#2F4F4F', darkturquoise: '#00CED1', darkviolet: '#9400D3', deeppink: '#FF1493', deepskyblue: '#00BFFF', dimgray: '#696969', dimgrey: '#696969', dodgerblue: '#1E90FF', firebrick: '#B22222', floralwhite: '#FFFAF0', forestgreen: '#228B22', gainsboro: '#DCDCDC', ghostwhite: '#F8F8FF', gold: '#FFD700', goldenrod: '#DAA520', grey: '#808080', greenyellow: '#ADFF2F', honeydew: '#F0FFF0', hotpink: '#FF69B4', indianred: '#CD5C5C', indigo: '#4B0082', ivory: '#FFFFF0', khaki: '#F0E68C', lavender: '#E6E6FA', lavenderblush: '#FFF0F5', lawngreen: '#7CFC00', lemonchiffon: '#FFFACD', lightblue: '#ADD8E6', lightcoral: '#F08080', lightcyan: '#E0FFFF', lightgoldenrodyellow: '#FAFAD2', lightgreen: '#90EE90', lightgrey: '#D3D3D3', lightpink: '#FFB6C1', lightsalmon: '#FFA07A', lightseagreen: '#20B2AA', lightskyblue: '#87CEFA', lightslategray: '#778899', lightslategrey: '#778899', lightsteelblue: '#B0C4DE', lightyellow: '#FFFFE0', limegreen: '#32CD32', linen: '#FAF0E6', magenta: '#FF00FF', mediumaquamarine: '#66CDAA', mediumblue: '#0000CD', mediumorchid: '#BA55D3', mediumpurple: '#9370DB', mediumseagreen: '#3CB371', mediumslateblue: '#7B68EE', mediumspringgreen: '#00FA9A', mediumturquoise: '#48D1CC', mediumvioletred: '#C71585', midnightblue: '#191970', mintcream: '#F5FFFA', mistyrose: '#FFE4E1', moccasin: '#FFE4B5', navajowhite: '#FFDEAD', oldlace: '#FDF5E6', olivedrab: '#6B8E23', orange: '#FFA500', orangered: '#FF4500', orchid: '#DA70D6', palegoldenrod: '#EEE8AA', palegreen: '#98FB98', paleturquoise: '#AFEEEE', palevioletred: '#DB7093', papayawhip: '#FFEFD5', peachpuff: '#FFDAB9', peru: '#CD853F', pink: '#FFC0CB', plum: '#DDA0DD', powderblue: '#B0E0E6', rosybrown: '#BC8F8F', royalblue: '#4169E1', saddlebrown: '#8B4513', salmon: '#FA8072', sandybrown: '#F4A460', seagreen: '#2E8B57', seashell: '#FFF5EE', sienna: '#A0522D', skyblue: '#87CEEB', slateblue: '#6A5ACD', slategray: '#708090', slategrey: '#708090', snow: '#FFFAFA', springgreen: '#00FF7F', steelblue: '#4682B4', tan: '#D2B48C', thistle: '#D8BFD8', tomato: '#FF6347', turquoise: '#40E0D0', violet: '#EE82EE', wheat: '#F5DEB3', whitesmoke: '#F5F5F5', yellowgreen: '#9ACD32' }; function getRgbHslContent(styleString) { var start = styleString.indexOf('(', 3); var end = styleString.indexOf(')', start + 1); var parts = styleString.substring(start + 1, end).split(','); // add alpha if needed if (parts.length == 4 && styleString.substr(3, 1) == 'a') { alpha = Number(parts[3]); } else { parts[3] = 1; } return parts; } function percent(s) { return parseFloat(s) / 100; } function clamp(v, min, max) { return Math.min(max, Math.max(min, v)); } function hslToRgb(parts){ var r, g, b; h = parseFloat(parts[0]) / 360 % 360; if (h < 0) h++; s = clamp(percent(parts[1]), 0, 1); l = clamp(percent(parts[2]), 0, 1); if (s == 0) { r = g = b = l; // achromatic } else { var q = l < 0.5 ? l * (1 + s) : l + s - l * s; var p = 2 * l - q; r = hueToRgb(p, q, h + 1 / 3); g = hueToRgb(p, q, h); b = hueToRgb(p, q, h - 1 / 3); } return '#' + decToHex[Math.floor(r * 255)] + decToHex[Math.floor(g * 255)] + decToHex[Math.floor(b * 255)]; } function hueToRgb(m1, m2, h) { if (h < 0) h++; if (h > 1) h--; if (6 * h < 1) return m1 + (m2 - m1) * 6 * h; else if (2 * h < 1) return m2; else if (3 * h < 2) return m1 + (m2 - m1) * (2 / 3 - h) * 6; else return m1; } function processStyle(styleString) { var str, alpha = 1; styleString = String(styleString); if (styleString.charAt(0) == '#') { str = styleString; } else if (/^rgb/.test(styleString)) { var parts = getRgbHslContent(styleString); var str = '#', n; for (var i = 0; i < 3; i++) { if (parts[i].indexOf('%') != -1) { n = Math.floor(percent(parts[i]) * 255); } else { n = Number(parts[i]); } str += decToHex[clamp(n, 0, 255)]; } alpha = parts[3]; } else if (/^hsl/.test(styleString)) { var parts = getRgbHslContent(styleString); str = hslToRgb(parts); alpha = parts[3]; } else { str = colorData[styleString] || styleString; } return {color: str, alpha: alpha}; } var DEFAULT_STYLE = { style: 'normal', variant: 'normal', weight: 'normal', size: 10, family: 'sans-serif' }; // Internal text style cache var fontStyleCache = {}; function processFontStyle(styleString) { if (fontStyleCache[styleString]) { return fontStyleCache[styleString]; } var el = document.createElement('div'); var style = el.style; try { style.font = styleString; } catch (ex) { // Ignore failures to set to invalid font. } return fontStyleCache[styleString] = { style: style.fontStyle || DEFAULT_STYLE.style, variant: style.fontVariant || DEFAULT_STYLE.variant, weight: style.fontWeight || DEFAULT_STYLE.weight, size: style.fontSize || DEFAULT_STYLE.size, family: style.fontFamily || DEFAULT_STYLE.family }; } function getComputedStyle(style, element) { var computedStyle = {}; for (var p in style) { computedStyle[p] = style[p]; } // Compute the size var canvasFontSize = parseFloat(element.currentStyle.fontSize), fontSize = parseFloat(style.size); if (typeof style.size == 'number') { computedStyle.size = style.size; } else if (style.size.indexOf('px') != -1) { computedStyle.size = fontSize; } else if (style.size.indexOf('em') != -1) { computedStyle.size = canvasFontSize * fontSize; } else if(style.size.indexOf('%') != -1) { computedStyle.size = (canvasFontSize / 100) * fontSize; } else if (style.size.indexOf('pt') != -1) { computedStyle.size = fontSize / .75; } else { computedStyle.size = canvasFontSize; } // Different scaling between normal text and VML text. This was found using // trial and error to get the same size as non VML text. computedStyle.size *= 0.981; return computedStyle; } function buildStyle(style) { return style.style + ' ' + style.variant + ' ' + style.weight + ' ' + style.size + 'px ' + style.family; } function processLineCap(lineCap) { switch (lineCap) { case 'butt': return 'flat'; case 'round': return 'round'; case 'square': default: return 'square'; } } /** * This class implements CanvasRenderingContext2D interface as described by * the WHATWG. * @param {HTMLElement} surfaceElement The element that the 2D context should * be associated with */ function CanvasRenderingContext2D_(surfaceElement) { this.m_ = createMatrixIdentity(); this.mStack_ = []; this.aStack_ = []; this.currentPath_ = []; // Canvas context properties this.strokeStyle = '#000'; this.fillStyle = '#000'; this.lineWidth = 1; this.lineJoin = 'miter'; this.lineCap = 'butt'; this.miterLimit = Z * 1; this.globalAlpha = 1; this.font = '10px sans-serif'; this.textAlign = 'left'; this.textBaseline = 'alphabetic'; this.canvas = surfaceElement; var el = surfaceElement.ownerDocument.createElement('div'); el.style.width = surfaceElement.clientWidth + 'px'; el.style.height = surfaceElement.clientHeight + 'px'; el.style.overflow = 'hidden'; el.style.position = 'absolute'; surfaceElement.appendChild(el); this.element_ = el; this.arcScaleX_ = 1; this.arcScaleY_ = 1; this.lineScale_ = 1; } var contextPrototype = CanvasRenderingContext2D_.prototype; contextPrototype.clearRect = function() { if (this.textMeasureEl_) { this.textMeasureEl_.removeNode(true); this.textMeasureEl_ = null; } this.element_.innerHTML = ''; }; contextPrototype.beginPath = function() { // TODO: Branch current matrix so that save/restore has no effect // as per safari docs. this.currentPath_ = []; }; contextPrototype.moveTo = function(aX, aY) { var p = this.getCoords_(aX, aY); this.currentPath_.push({type: 'moveTo', x: p.x, y: p.y}); this.currentX_ = p.x; this.currentY_ = p.y; }; contextPrototype.lineTo = function(aX, aY) { var p = this.getCoords_(aX, aY); this.currentPath_.push({type: 'lineTo', x: p.x, y: p.y}); this.currentX_ = p.x; this.currentY_ = p.y; }; contextPrototype.bezierCurveTo = function(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) { var p = this.getCoords_(aX, aY); var cp1 = this.getCoords_(aCP1x, aCP1y); var cp2 = this.getCoords_(aCP2x, aCP2y); bezierCurveTo(this, cp1, cp2, p); }; // Helper function that takes the already fixed cordinates. function bezierCurveTo(self, cp1, cp2, p) { self.currentPath_.push({ type: 'bezierCurveTo', cp1x: cp1.x, cp1y: cp1.y, cp2x: cp2.x, cp2y: cp2.y, x: p.x, y: p.y }); self.currentX_ = p.x; self.currentY_ = p.y; } contextPrototype.quadraticCurveTo = function(aCPx, aCPy, aX, aY) { // the following is lifted almost directly from // http://developer.mozilla.org/en/docs/Canvas_tutorial:Drawing_shapes var cp = this.getCoords_(aCPx, aCPy); var p = this.getCoords_(aX, aY); var cp1 = { x: this.currentX_ + 2.0 / 3.0 * (cp.x - this.currentX_), y: this.currentY_ + 2.0 / 3.0 * (cp.y - this.currentY_) }; var cp2 = { x: cp1.x + (p.x - this.currentX_) / 3.0, y: cp1.y + (p.y - this.currentY_) / 3.0 }; bezierCurveTo(this, cp1, cp2, p); }; contextPrototype.arc = function(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) { aRadius *= Z; var arcType = aClockwise ? 'at' : 'wa'; var xStart = aX + mc(aStartAngle) * aRadius - Z2; var yStart = aY + ms(aStartAngle) * aRadius - Z2; var xEnd = aX + mc(aEndAngle) * aRadius - Z2; var yEnd = aY + ms(aEndAngle) * aRadius - Z2; // IE won't render arches drawn counter clockwise if xStart == xEnd. if (xStart == xEnd && !aClockwise) { xStart += 0.125; // Offset xStart by 1/80 of a pixel. Use something // that can be represented in binary } var p = this.getCoords_(aX, aY); var pStart = this.getCoords_(xStart, yStart); var pEnd = this.getCoords_(xEnd, yEnd); this.currentPath_.push({type: arcType, x: p.x, y: p.y, radius: aRadius, xStart: pStart.x, yStart: pStart.y, xEnd: pEnd.x, yEnd: pEnd.y}); }; contextPrototype.rect = function(aX, aY, aWidth, aHeight) { this.moveTo(aX, aY); this.lineTo(aX + aWidth, aY); this.lineTo(aX + aWidth, aY + aHeight); this.lineTo(aX, aY + aHeight); this.closePath(); }; contextPrototype.strokeRect = function(aX, aY, aWidth, aHeight) { var oldPath = this.currentPath_; this.beginPath(); this.moveTo(aX, aY); this.lineTo(aX + aWidth, aY); this.lineTo(aX + aWidth, aY + aHeight); this.lineTo(aX, aY + aHeight); this.closePath(); this.stroke(); this.currentPath_ = oldPath; }; contextPrototype.fillRect = function(aX, aY, aWidth, aHeight) { var oldPath = this.currentPath_; this.beginPath(); this.moveTo(aX, aY); this.lineTo(aX + aWidth, aY); this.lineTo(aX + aWidth, aY + aHeight); this.lineTo(aX, aY + aHeight); this.closePath(); this.fill(); this.currentPath_ = oldPath; }; contextPrototype.createLinearGradient = function(aX0, aY0, aX1, aY1) { var gradient = new CanvasGradient_('gradient'); gradient.x0_ = aX0; gradient.y0_ = aY0; gradient.x1_ = aX1; gradient.y1_ = aY1; return gradient; }; contextPrototype.createRadialGradient = function(aX0, aY0, aR0, aX1, aY1, aR1) { var gradient = new CanvasGradient_('gradientradial'); gradient.x0_ = aX0; gradient.y0_ = aY0; gradient.r0_ = aR0; gradient.x1_ = aX1; gradient.y1_ = aY1; gradient.r1_ = aR1; return gradient; }; contextPrototype.drawImage = function(image, var_args) { var dx, dy, dw, dh, sx, sy, sw, sh; // to find the original width we overide the width and height var oldRuntimeWidth = image.runtimeStyle.width; var oldRuntimeHeight = image.runtimeStyle.height; image.runtimeStyle.width = 'auto'; image.runtimeStyle.height = 'auto'; // get the original size var w = image.width; var h = image.height; // and remove overides image.runtimeStyle.width = oldRuntimeWidth; image.runtimeStyle.height = oldRuntimeHeight; if (arguments.length == 3) { dx = arguments[1]; dy = arguments[2]; sx = sy = 0; sw = dw = w; sh = dh = h; } else if (arguments.length == 5) { dx = arguments[1]; dy = arguments[2]; dw = arguments[3]; dh = arguments[4]; sx = sy = 0; sw = w; sh = h; } else if (arguments.length == 9) { sx = arguments[1]; sy = arguments[2]; sw = arguments[3]; sh = arguments[4]; dx = arguments[5]; dy = arguments[6]; dw = arguments[7]; dh = arguments[8]; } else { throw Error('Invalid number of arguments'); } var d = this.getCoords_(dx, dy); var w2 = sw / 2; var h2 = sh / 2; var vmlStr = []; var W = 10; var H = 10; // For some reason that I've now forgotten, using divs didn't work vmlStr.push(' <g_vml_:group', ' coordsize="', Z * W, ',', Z * H, '"', ' coordorigin="0,0"' , ' style="width:', W, 'px;height:', H, 'px;position:absolute;'); // If filters are necessary (rotation exists), create them // filters are bog-slow, so only create them if abbsolutely necessary // The following check doesn't account for skews (which don't exist // in the canvas spec (yet) anyway. if (this.m_[0][0] != 1 || this.m_[0][1] || this.m_[1][1] != 1 || this.m_[1][0]) { var filter = []; // Note the 12/21 reversal filter.push('M11=', this.m_[0][0], ',', 'M12=', this.m_[1][0], ',', 'M21=', this.m_[0][1], ',', 'M22=', this.m_[1][1], ',', 'Dx=', mr(d.x / Z), ',', 'Dy=', mr(d.y / Z), ''); // Bounding box calculation (need to minimize displayed area so that // filters don't waste time on unused pixels. var max = d; var c2 = this.getCoords_(dx + dw, dy); var c3 = this.getCoords_(dx, dy + dh); var c4 = this.getCoords_(dx + dw, dy + dh); max.x = m.max(max.x, c2.x, c3.x, c4.x); max.y = m.max(max.y, c2.y, c3.y, c4.y); vmlStr.push('padding:0 ', mr(max.x / Z), 'px ', mr(max.y / Z), 'px 0;filter:progid:DXImageTransform.Microsoft.Matrix(', filter.join(''), ", sizingmethod='clip');"); } else { vmlStr.push('top:', mr(d.y / Z), 'px;left:', mr(d.x / Z), 'px;'); } vmlStr.push(' ">' , '<g_vml_:image src="', image.src, '"', ' style="width:', Z * dw, 'px;', ' height:', Z * dh, 'px"', ' cropleft="', sx / w, '"', ' croptop="', sy / h, '"', ' cropright="', (w - sx - sw) / w, '"', ' cropbottom="', (h - sy - sh) / h, '"', ' />', '</g_vml_:group>'); this.element_.insertAdjacentHTML('BeforeEnd', vmlStr.join('')); }; contextPrototype.stroke = function(aFill) { var W = 10; var H = 10; // Divide the shape into chunks if it's too long because IE has a limit // somewhere for how long a VML shape can be. This simple division does // not work with fills, only strokes, unfortunately. var chunkSize = 5000; var min = {x: null, y: null}; var max = {x: null, y: null}; for (var j = 0; j < this.currentPath_.length; j += chunkSize) { var lineStr = []; var lineOpen = false; lineStr.push('<g_vml_:shape', ' filled="', !!aFill, '"', ' style="position:absolute;width:', W, 'px;height:', H, 'px;"', ' coordorigin="0,0"', ' coordsize="', Z * W, ',', Z * H, '"', ' stroked="', !aFill, '"', ' path="'); var newSeq = false; for (var i = j; i < Math.min(j + chunkSize, this.currentPath_.length); i++) { if (i % chunkSize == 0 && i > 0) { // move into position for next chunk lineStr.push(' m ', mr(this.currentPath_[i-1].x), ',', mr(this.currentPath_[i-1].y)); } var p = this.currentPath_[i]; var c; switch (p.type) { case 'moveTo': c = p; lineStr.push(' m ', mr(p.x), ',', mr(p.y)); break; case 'lineTo': lineStr.push(' l ', mr(p.x), ',', mr(p.y)); break; case 'close': lineStr.push(' x '); p = null; break; case 'bezierCurveTo': lineStr.push(' c ', mr(p.cp1x), ',', mr(p.cp1y), ',', mr(p.cp2x), ',', mr(p.cp2y), ',', mr(p.x), ',', mr(p.y)); break; case 'at': case 'wa': lineStr.push(' ', p.type, ' ', mr(p.x - this.arcScaleX_ * p.radius), ',', mr(p.y - this.arcScaleY_ * p.radius), ' ', mr(p.x + this.arcScaleX_ * p.radius), ',', mr(p.y + this.arcScaleY_ * p.radius), ' ', mr(p.xStart), ',', mr(p.yStart), ' ', mr(p.xEnd), ',', mr(p.yEnd)); break; } // TODO: Following is broken for curves due to // move to proper paths. // Figure out dimensions so we can do gradient fills // properly if (p) { if (min.x == null || p.x < min.x) { min.x = p.x; } if (max.x == null || p.x > max.x) { max.x = p.x; } if (min.y == null || p.y < min.y) { min.y = p.y; } if (max.y == null || p.y > max.y) { max.y = p.y; } } } lineStr.push(' ">'); if (!aFill) { appendStroke(this, lineStr); } else { appendFill(this, lineStr, min, max); } lineStr.push('</g_vml_:shape>'); this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); } }; function appendStroke(ctx, lineStr) { var a = processStyle(ctx.strokeStyle); var color = a.color; var opacity = a.alpha * ctx.globalAlpha; var lineWidth = ctx.lineScale_ * ctx.lineWidth; // VML cannot correctly render a line if the width is less than 1px. // In that case, we dilute the color to make the line look thinner. if (lineWidth < 1) { opacity *= lineWidth; } lineStr.push( '<g_vml_:stroke', ' opacity="', opacity, '"', ' joinstyle="', ctx.lineJoin, '"', ' miterlimit="', ctx.miterLimit, '"', ' endcap="', processLineCap(ctx.lineCap), '"', ' weight="', lineWidth, 'px"', ' color="', color, '" />' ); } function appendFill(ctx, lineStr, min, max) { var fillStyle = ctx.fillStyle; var arcScaleX = ctx.arcScaleX_; var arcScaleY = ctx.arcScaleY_; var width = max.x - min.x; var height = max.y - min.y; if (fillStyle instanceof CanvasGradient_) { // TODO: Gradients transformed with the transformation matrix. var angle = 0; var focus = {x: 0, y: 0}; // additional offset var shift = 0; // scale factor for offset var expansion = 1; if (fillStyle.type_ == 'gradient') { var x0 = fillStyle.x0_ / arcScaleX; var y0 = fillStyle.y0_ / arcScaleY; var x1 = fillStyle.x1_ / arcScaleX; var y1 = fillStyle.y1_ / arcScaleY; var p0 = ctx.getCoords_(x0, y0); var p1 = ctx.getCoords_(x1, y1); var dx = p1.x - p0.x; var dy = p1.y - p0.y; angle = Math.atan2(dx, dy) * 180 / Math.PI; // The angle should be a non-negative number. if (angle < 0) { angle += 360; } // Very small angles produce an unexpected result because they are // converted to a scientific notation string. if (angle < 1e-6) { angle = 0; } } else { var p0 = ctx.getCoords_(fillStyle.x0_, fillStyle.y0_); focus = { x: (p0.x - min.x) / width, y: (p0.y - min.y) / height }; width /= arcScaleX * Z; height /= arcScaleY * Z; var dimension = m.max(width, height); shift = 2 * fillStyle.r0_ / dimension; expansion = 2 * fillStyle.r1_ / dimension - shift; } // We need to sort the color stops in ascending order by offset, // otherwise IE won't interpret it correctly. var stops = fillStyle.colors_; stops.sort(function(cs1, cs2) { return cs1.offset - cs2.offset; }); var length = stops.length; var color1 = stops[0].color; var color2 = stops[length - 1].color; var opacity1 = stops[0].alpha * ctx.globalAlpha; var opacity2 = stops[length - 1].alpha * ctx.globalAlpha; var colors = []; for (var i = 0; i < length; i++) { var stop = stops[i]; colors.push(stop.offset * expansion + shift + ' ' + stop.color); } // When colors attribute is used, the meanings of opacity and o:opacity2 // are reversed. lineStr.push('<g_vml_:fill type="', fillStyle.type_, '"', ' method="none" focus="100%"', ' color="', color1, '"', ' color2="', color2, '"', ' colors="', colors.join(','), '"', ' opacity="', opacity2, '"', ' g_o_:opacity2="', opacity1, '"', ' angle="', angle, '"', ' focusposition="', focus.x, ',', focus.y, '" />'); } else if (fillStyle instanceof CanvasPattern_) { if (width && height) { var deltaLeft = -min.x; var deltaTop = -min.y; lineStr.push('<g_vml_:fill', ' position="', deltaLeft / width * arcScaleX * arcScaleX, ',', deltaTop / height * arcScaleY * arcScaleY, '"', ' type="tile"', // TODO: Figure out the correct size to fit the scale. //' size="', w, 'px ', h, 'px"', ' src="', fillStyle.src_, '" />'); } } else { var a = processStyle(ctx.fillStyle); var color = a.color; var opacity = a.alpha * ctx.globalAlpha; lineStr.push('<g_vml_:fill color="', color, '" opacity="', opacity, '" />'); } } contextPrototype.fill = function() { this.stroke(true); }; contextPrototype.closePath = function() { this.currentPath_.push({type: 'close'}); }; /** * @private */ contextPrototype.getCoords_ = function(aX, aY) { var m = this.m_; return { x: Z * (aX * m[0][0] + aY * m[1][0] + m[2][0]) - Z2, y: Z * (aX * m[0][1] + aY * m[1][1] + m[2][1]) - Z2 }; }; contextPrototype.save = function() { var o = {}; copyState(this, o); this.aStack_.push(o); this.mStack_.push(this.m_); this.m_ = matrixMultiply(createMatrixIdentity(), this.m_); }; contextPrototype.restore = function() { if (this.aStack_.length) { copyState(this.aStack_.pop(), this); this.m_ = this.mStack_.pop(); } }; function matrixIsFinite(m) { return isFinite(m[0][0]) && isFinite(m[0][1]) && isFinite(m[1][0]) && isFinite(m[1][1]) && isFinite(m[2][0]) && isFinite(m[2][1]); } function setM(ctx, m, updateLineScale) { if (!matrixIsFinite(m)) { return; } ctx.m_ = m; if (updateLineScale) { // Get the line scale. // Determinant of this.m_ means how much the area is enlarged by the // transformation. So its square root can be used as a scale factor // for width. var det = m[0][0] * m[1][1] - m[0][1] * m[1][0]; ctx.lineScale_ = sqrt(abs(det)); } } contextPrototype.translate = function(aX, aY) { var m1 = [ [1, 0, 0], [0, 1, 0], [aX, aY, 1] ]; setM(this, matrixMultiply(m1, this.m_), false); }; contextPrototype.rotate = function(aRot) { var c = mc(aRot); var s = ms(aRot); var m1 = [ [c, s, 0], [-s, c, 0], [0, 0, 1] ]; setM(this, matrixMultiply(m1, this.m_), false); }; contextPrototype.scale = function(aX, aY) { this.arcScaleX_ *= aX; this.arcScaleY_ *= aY; var m1 = [ [aX, 0, 0], [0, aY, 0], [0, 0, 1] ]; setM(this, matrixMultiply(m1, this.m_), true); }; contextPrototype.transform = function(m11, m12, m21, m22, dx, dy) { var m1 = [ [m11, m12, 0], [m21, m22, 0], [dx, dy, 1] ]; setM(this, matrixMultiply(m1, this.m_), true); }; contextPrototype.setTransform = function(m11, m12, m21, m22, dx, dy) { var m = [ [m11, m12, 0], [m21, m22, 0], [dx, dy, 1] ]; setM(this, m, true); }; /** * The text drawing function. * The maxWidth argument isn't taken in account, since no browser supports * it yet. */ contextPrototype.drawText_ = function(text, x, y, maxWidth, stroke) { var m = this.m_, delta = 1000, left = 0, right = delta, offset = {x: 0, y: 0}, lineStr = []; var fontStyle = getComputedStyle(processFontStyle(this.font), this.element_); var fontStyleString = buildStyle(fontStyle); var elementStyle = this.element_.currentStyle; var textAlign = this.textAlign.toLowerCase(); switch (textAlign) { case 'left': case 'center': case 'right': break; case 'end': textAlign = elementStyle.direction == 'ltr' ? 'right' : 'left'; break; case 'start': textAlign = elementStyle.direction == 'rtl' ? 'right' : 'left'; break; default: textAlign = 'left'; } // 1.75 is an arbitrary number, as there is no info about the text baseline switch (this.textBaseline) { case 'hanging': case 'top': offset.y = fontStyle.size / 1.75; break; case 'middle': break; default: case null: case 'alphabetic': case 'ideographic': case 'bottom': offset.y = -fontStyle.size / 2.25; break; } switch(textAlign) { case 'right': left = delta; right = 0.05; break; case 'center': left = right = delta / 2; break; } var d = this.getCoords_(x + offset.x, y + offset.y); lineStr.push('<g_vml_:line from="', -left ,' 0" to="', right ,' 0.05" ', ' coordsize="100 100" coordorigin="0 0"', ' filled="', !stroke, '" stroked="', !!stroke, '" style="position:absolute;width:1px;height:1px;">'); if (stroke) { appendStroke(this, lineStr); } else { // TODO: Fix the min and max params. appendFill(this, lineStr, {x: -left, y: 0}, {x: right, y: fontStyle.size}); } var skewM = m[0][0].toFixed(3) + ',' + m[1][0].toFixed(3) + ',' + m[0][1].toFixed(3) + ',' + m[1][1].toFixed(3) + ',0,0'; var skewOffset = mr(d.x / Z) + ',' + mr(d.y / Z); lineStr.push('<g_vml_:skew on="t" matrix="', skewM ,'" ', ' offset="', skewOffset, '" origin="', left ,' 0" />', '<g_vml_:path textpathok="true" />', '<g_vml_:textpath on="true" string="', encodeHtmlAttribute(text), '" style="v-text-align:', textAlign, ';font:', encodeHtmlAttribute(fontStyleString), '" /></g_vml_:line>'); this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); }; contextPrototype.fillText = function(text, x, y, maxWidth) { this.drawText_(text, x, y, maxWidth, false); }; contextPrototype.strokeText = function(text, x, y, maxWidth) { this.drawText_(text, x, y, maxWidth, true); }; contextPrototype.measureText = function(text) { if (!this.textMeasureEl_) { var s = '<span style="position:absolute;' + 'top:-20000px;left:0;padding:0;margin:0;border:none;' + 'white-space:pre;"></span>'; this.element_.insertAdjacentHTML('beforeEnd', s); this.textMeasureEl_ = this.element_.lastChild; } var doc = this.element_.ownerDocument; this.textMeasureEl_.innerHTML = ''; this.textMeasureEl_.style.font = this.font; // Don't use innerHTML or innerText because they allow markup/whitespace. this.textMeasureEl_.appendChild(doc.createTextNode(text)); return {width: this.textMeasureEl_.offsetWidth}; }; /******** STUBS ********/ contextPrototype.clip = function() { // TODO: Implement }; contextPrototype.arcTo = function() { // TODO: Implement }; contextPrototype.createPattern = function(image, repetition) { return new CanvasPattern_(image, repetition); }; // Gradient / Pattern Stubs function CanvasGradient_(aType) { this.type_ = aType; this.x0_ = 0; this.y0_ = 0; this.r0_ = 0; this.x1_ = 0; this.y1_ = 0; this.r1_ = 0; this.colors_ = []; } CanvasGradient_.prototype.addColorStop = function(aOffset, aColor) { aColor = processStyle(aColor); this.colors_.push({offset: aOffset, color: aColor.color, alpha: aColor.alpha}); }; function CanvasPattern_(image, repetition) { assertImageIsValid(image); switch (repetition) { case 'repeat': case null: case '': this.repetition_ = 'repeat'; break case 'repeat-x': case 'repeat-y': case 'no-repeat': this.repetition_ = repetition; break; default: throwException('SYNTAX_ERR'); } this.src_ = image.src; this.width_ = image.width; this.height_ = image.height; } function throwException(s) { throw new DOMException_(s); } function assertImageIsValid(img) { if (!img || img.nodeType != 1 || img.tagName != 'IMG') { throwException('TYPE_MISMATCH_ERR'); } if (img.readyState != 'complete') { throwException('INVALID_STATE_ERR'); } } function DOMException_(s) { this.code = this[s]; this.message = s +': DOM Exception ' + this.code; } var p = DOMException_.prototype = new Error; p.INDEX_SIZE_ERR = 1; p.DOMSTRING_SIZE_ERR = 2; p.HIERARCHY_REQUEST_ERR = 3; p.WRONG_DOCUMENT_ERR = 4; p.INVALID_CHARACTER_ERR = 5; p.NO_DATA_ALLOWED_ERR = 6; p.NO_MODIFICATION_ALLOWED_ERR = 7; p.NOT_FOUND_ERR = 8; p.NOT_SUPPORTED_ERR = 9; p.INUSE_ATTRIBUTE_ERR = 10; p.INVALID_STATE_ERR = 11; p.SYNTAX_ERR = 12; p.INVALID_MODIFICATION_ERR = 13; p.NAMESPACE_ERR = 14; p.INVALID_ACCESS_ERR = 15; p.VALIDATION_ERR = 16; p.TYPE_MISMATCH_ERR = 17; // set up externs G_vmlCanvasManager = G_vmlCanvasManager_; CanvasRenderingContext2D = CanvasRenderingContext2D_; CanvasGradient = CanvasGradient_; CanvasPattern = CanvasPattern_; DOMException = DOMException_; })(); } // if
JavaScript
/* Flot plugin for computing bottoms for filled line and bar charts. The case: you've got two series that you want to fill the area between. In Flot terms, you need to use one as the fill bottom of the other. You can specify the bottom of each data point as the third coordinate manually, or you can use this plugin to compute it for you. In order to name the other series, you need to give it an id, like this var dataset = [ { data: [ ... ], id: "foo" } , // use default bottom { data: [ ... ], fillBetween: "foo" }, // use first dataset as bottom ]; $.plot($("#placeholder"), dataset, { line: { show: true, fill: true }}); As a convenience, if the id given is a number that doesn't appear as an id in the series, it is interpreted as the index in the array instead (so fillBetween: 0 can also mean the first series). Internally, the plugin modifies the datapoints in each series. For line series, extra data points might be inserted through interpolation. Note that at points where the bottom line is not defined (due to a null point or start/end of line), the current line will show a gap too. The algorithm comes from the jquery.flot.stack.js plugin, possibly some code could be shared. */ (function ($) { var options = { series: { fillBetween: null } // or number }; function init(plot) { function findBottomSeries(s, allseries) { var i; for (i = 0; i < allseries.length; ++i) { if (allseries[i].id == s.fillBetween) return allseries[i]; } if (typeof s.fillBetween == "number") { i = s.fillBetween; if (i < 0 || i >= allseries.length) return null; return allseries[i]; } return null; } function computeFillBottoms(plot, s, datapoints) { if (s.fillBetween == null) return; var other = findBottomSeries(s, plot.getData()); if (!other) return; var ps = datapoints.pointsize, points = datapoints.points, otherps = other.datapoints.pointsize, otherpoints = other.datapoints.points, newpoints = [], px, py, intery, qx, qy, bottom, withlines = s.lines.show, withbottom = ps > 2 && datapoints.format[2].y, withsteps = withlines && s.lines.steps, fromgap = true, i = 0, j = 0, l; while (true) { if (i >= points.length) break; l = newpoints.length; if (points[i] == null) { // copy gaps for (m = 0; m < ps; ++m) newpoints.push(points[i + m]); i += ps; } else if (j >= otherpoints.length) { // for lines, we can't use the rest of the points if (!withlines) { for (m = 0; m < ps; ++m) newpoints.push(points[i + m]); } i += ps; } else if (otherpoints[j] == null) { // oops, got a gap for (m = 0; m < ps; ++m) newpoints.push(null); fromgap = true; j += otherps; } else { // cases where we actually got two points px = points[i]; py = points[i + 1]; qx = otherpoints[j]; qy = otherpoints[j + 1]; bottom = 0; if (px == qx) { for (m = 0; m < ps; ++m) newpoints.push(points[i + m]); //newpoints[l + 1] += qy; bottom = qy; i += ps; j += otherps; } else if (px > qx) { // we got past point below, might need to // insert interpolated extra point if (withlines && i > 0 && points[i - ps] != null) { intery = py + (points[i - ps + 1] - py) * (qx - px) / (points[i - ps] - px); newpoints.push(qx); newpoints.push(intery) for (m = 2; m < ps; ++m) newpoints.push(points[i + m]); bottom = qy; } j += otherps; } else { // px < qx if (fromgap && withlines) { // if we come from a gap, we just skip this point i += ps; continue; } for (m = 0; m < ps; ++m) newpoints.push(points[i + m]); // we might be able to interpolate a point below, // this can give us a better y if (withlines && j > 0 && otherpoints[j - otherps] != null) bottom = qy + (otherpoints[j - otherps + 1] - qy) * (px - qx) / (otherpoints[j - otherps] - qx); //newpoints[l + 1] += bottom; i += ps; } fromgap = false; if (l != newpoints.length && withbottom) newpoints[l + 2] = bottom; } // maintain the line steps invariant if (withsteps && l != newpoints.length && l > 0 && newpoints[l] != null && newpoints[l] != newpoints[l - ps] && newpoints[l + 1] != newpoints[l - ps + 1]) { for (m = 0; m < ps; ++m) newpoints[l + ps + m] = newpoints[l + m]; newpoints[l + 1] = newpoints[l - ps + 1]; } } datapoints.points = newpoints; } plot.hooks.processDatapoints.push(computeFillBottoms); } $.plot.plugins.push({ init: init, options: options, name: 'fillbetween', version: '1.0' }); })(jQuery);
JavaScript
/* Flot plugin for rendering pie charts. The plugin assumes the data is coming is as a single data value for each series, and each of those values is a positive value or zero (negative numbers don't make any sense and will cause strange effects). The data values do NOT need to be passed in as percentage values because it internally calculates the total and percentages. * Created by Brian Medendorp, June 2009 * Updated November 2009 with contributions from: btburnett3, Anthony Aragues and Xavi Ivars * Changes: 2009-10-22: lineJoin set to round 2009-10-23: IE full circle fix, donut 2009-11-11: Added basic hover from btburnett3 - does not work in IE, and center is off in Chrome and Opera 2009-11-17: Added IE hover capability submitted by Anthony Aragues 2009-11-18: Added bug fix submitted by Xavi Ivars (issues with arrays when other JS libraries are included as well) Available options are: series: { pie: { show: true/false radius: 0-1 for percentage of fullsize, or a specified pixel length, or 'auto' innerRadius: 0-1 for percentage of fullsize or a specified pixel length, for creating a donut effect startAngle: 0-2 factor of PI used for starting angle (in radians) i.e 3/2 starts at the top, 0 and 2 have the same result tilt: 0-1 for percentage to tilt the pie, where 1 is no tilt, and 0 is completely flat (nothing will show) offset: { top: integer value to move the pie up or down left: integer value to move the pie left or right, or 'auto' }, stroke: { color: any hexidecimal color value (other formats may or may not work, so best to stick with something like '#FFF') width: integer pixel width of the stroke }, label: { show: true/false, or 'auto' formatter: a user-defined function that modifies the text/style of the label text radius: 0-1 for percentage of fullsize, or a specified pixel length background: { color: any hexidecimal color value (other formats may or may not work, so best to stick with something like '#000') opacity: 0-1 }, threshold: 0-1 for the percentage value at which to hide labels (if they're too small) }, combine: { threshold: 0-1 for the percentage value at which to combine slices (if they're too small) color: any hexidecimal color value (other formats may or may not work, so best to stick with something like '#CCC'), if null, the plugin will automatically use the color of the first slice to be combined label: any text value of what the combined slice should be labeled } highlight: { opacity: 0-1 } } } More detail and specific examples can be found in the included HTML file. */ (function ($) { function init(plot) // this is the "body" of the plugin { var canvas = null; var target = null; var maxRadius = null; var centerLeft = null; var centerTop = null; var total = 0; var redraw = true; var redrawAttempts = 10; var shrink = 0.95; var legendWidth = 0; var processed = false; var raw = false; // interactive variables var highlights = []; // add hook to determine if pie plugin in enabled, and then perform necessary operations plot.hooks.processOptions.push(checkPieEnabled); plot.hooks.bindEvents.push(bindEvents); // check to see if the pie plugin is enabled function checkPieEnabled(plot, options) { if (options.series.pie.show) { //disable grid options.grid.show = false; // set labels.show if (options.series.pie.label.show=='auto') if (options.legend.show) options.series.pie.label.show = false; else options.series.pie.label.show = true; // set radius if (options.series.pie.radius=='auto') if (options.series.pie.label.show) options.series.pie.radius = 3/4; else options.series.pie.radius = 1; // ensure sane tilt if (options.series.pie.tilt>1) options.series.pie.tilt=1; if (options.series.pie.tilt<0) options.series.pie.tilt=0; // add processData hook to do transformations on the data plot.hooks.processDatapoints.push(processDatapoints); plot.hooks.drawOverlay.push(drawOverlay); // add draw hook plot.hooks.draw.push(draw); } } // bind hoverable events function bindEvents(plot, eventHolder) { var options = plot.getOptions(); if (options.series.pie.show && options.grid.hoverable) eventHolder.unbind('mousemove').mousemove(onMouseMove); if (options.series.pie.show && options.grid.clickable) eventHolder.unbind('click').click(onClick); } // debugging function that prints out an object function alertObject(obj) { var msg = ''; function traverse(obj, depth) { if (!depth) depth = 0; for (var i = 0; i < obj.length; ++i) { for (var j=0; j<depth; j++) msg += '\t'; if( typeof obj[i] == "object") { // its an object msg += ''+i+':\n'; traverse(obj[i], depth+1); } else { // its a value msg += ''+i+': '+obj[i]+'\n'; } } } traverse(obj); alert(msg); } function calcTotal(data) { for (var i = 0; i < data.length; ++i) { var item = parseFloat(data[i].data[0][1]); if (item) total += item; } } function processDatapoints(plot, series, data, datapoints) { if (!processed) { processed = true; canvas = plot.getCanvas(); target = $(canvas).parent(); options = plot.getOptions(); plot.setData(combine(plot.getData())); } } function setupPie() { legendWidth = target.children().filter('.legend').children().width(); // calculate maximum radius and center point maxRadius = Math.min(canvas.width,(canvas.height/options.series.pie.tilt))/2; centerTop = (canvas.height/2)+options.series.pie.offset.top; centerLeft = (canvas.width/2); if (options.series.pie.offset.left=='auto') if (options.legend.position.match('w')) centerLeft += legendWidth/2; else centerLeft -= legendWidth/2; else centerLeft += options.series.pie.offset.left; if (centerLeft<maxRadius) centerLeft = maxRadius; else if (centerLeft>canvas.width-maxRadius) centerLeft = canvas.width-maxRadius; } function fixData(data) { for (var i = 0; i < data.length; ++i) { if (typeof(data[i].data)=='number') data[i].data = [[1,data[i].data]]; else if (typeof(data[i].data)=='undefined' || typeof(data[i].data[0])=='undefined') { if (typeof(data[i].data)!='undefined' && typeof(data[i].data.label)!='undefined') data[i].label = data[i].data.label; // fix weirdness coming from flot data[i].data = [[1,0]]; } } return data; } function combine(data) { data = fixData(data); calcTotal(data); var combined = 0; var numCombined = 0; var color = options.series.pie.combine.color; var newdata = []; for (var i = 0; i < data.length; ++i) { // make sure its a number data[i].data[0][1] = parseFloat(data[i].data[0][1]); if (!data[i].data[0][1]) data[i].data[0][1] = 0; if (data[i].data[0][1]/total<=options.series.pie.combine.threshold) { combined += data[i].data[0][1]; numCombined++; if (!color) color = data[i].color; } else { newdata.push({ data: [[1,data[i].data[0][1]]], color: data[i].color, label: data[i].label, angle: (data[i].data[0][1]*(Math.PI*2))/total, percent: (data[i].data[0][1]/total*100) }); } } if (numCombined>0) newdata.push({ data: [[1,combined]], color: color, label: options.series.pie.combine.label, angle: (combined*(Math.PI*2))/total, percent: (combined/total*100) }); return newdata; } function draw(plot, newCtx) { if (!target) return; // if no series were passed ctx = newCtx; setupPie(); var slices = plot.getData(); var attempts = 0; while (redraw && attempts<redrawAttempts) { redraw = false; if (attempts>0) maxRadius *= shrink; attempts += 1; clear(); if (options.series.pie.tilt<=0.8) drawShadow(); drawPie(); } if (attempts >= redrawAttempts) { clear(); target.prepend('<div class="error">Could not draw pie with labels contained inside canvas</div>'); } if ( plot.setSeries && plot.insertLegend ) { plot.setSeries(slices); plot.insertLegend(); } // we're actually done at this point, just defining internal functions at this point function clear() { ctx.clearRect(0,0,canvas.width,canvas.height); target.children().filter('.pieLabel, .pieLabelBackground').remove(); } function drawShadow() { var shadowLeft = 5; var shadowTop = 15; var edge = 10; var alpha = 0.02; // set radius if (options.series.pie.radius>1) var radius = options.series.pie.radius; else var radius = maxRadius * options.series.pie.radius; if (radius>=(canvas.width/2)-shadowLeft || radius*options.series.pie.tilt>=(canvas.height/2)-shadowTop || radius<=edge) return; // shadow would be outside canvas, so don't draw it ctx.save(); ctx.translate(shadowLeft,shadowTop); ctx.globalAlpha = alpha; ctx.fillStyle = '#000'; // center and rotate to starting position ctx.translate(centerLeft,centerTop); ctx.scale(1, options.series.pie.tilt); //radius -= edge; for (var i=1; i<=edge; i++) { ctx.beginPath(); ctx.arc(0,0,radius,0,Math.PI*2,false); ctx.fill(); radius -= i; } ctx.restore(); } function drawPie() { startAngle = Math.PI*options.series.pie.startAngle; // set radius if (options.series.pie.radius>1) var radius = options.series.pie.radius; else var radius = maxRadius * options.series.pie.radius; // center and rotate to starting position ctx.save(); ctx.translate(centerLeft,centerTop); ctx.scale(1, options.series.pie.tilt); //ctx.rotate(startAngle); // start at top; -- This doesn't work properly in Opera // draw slices ctx.save(); var currentAngle = startAngle; for (var i = 0; i < slices.length; ++i) { slices[i].startAngle = currentAngle; drawSlice(slices[i].angle, slices[i].color, true); } ctx.restore(); // draw slice outlines ctx.save(); ctx.lineWidth = options.series.pie.stroke.width; currentAngle = startAngle; for (var i = 0; i < slices.length; ++i) drawSlice(slices[i].angle, options.series.pie.stroke.color, false); ctx.restore(); // draw donut hole drawDonutHole(ctx); // draw labels if (options.series.pie.label.show) drawLabels(); // restore to original state ctx.restore(); function drawSlice(angle, color, fill) { if (angle<=0) return; if (fill) ctx.fillStyle = color; else { ctx.strokeStyle = color; ctx.lineJoin = 'round'; } ctx.beginPath(); if (Math.abs(angle - Math.PI*2) > 0.000000001) ctx.moveTo(0,0); // Center of the pie else if ($.browser.msie) angle -= 0.0001; //ctx.arc(0,0,radius,0,angle,false); // This doesn't work properly in Opera ctx.arc(0,0,radius,currentAngle,currentAngle+angle,false); ctx.closePath(); //ctx.rotate(angle); // This doesn't work properly in Opera currentAngle += angle; if (fill) ctx.fill(); else ctx.stroke(); } function drawLabels() { var currentAngle = startAngle; // set radius if (options.series.pie.label.radius>1) var radius = options.series.pie.label.radius; else var radius = maxRadius * options.series.pie.label.radius; for (var i = 0; i < slices.length; ++i) { if (slices[i].percent >= options.series.pie.label.threshold*100) drawLabel(slices[i], currentAngle, i); currentAngle += slices[i].angle; } function drawLabel(slice, startAngle, index) { if (slice.data[0][1]==0) return; // format label text var lf = options.legend.labelFormatter, text, plf = options.series.pie.label.formatter; if (lf) text = lf(slice.label, slice); else text = slice.label; if (plf) text = plf(text, slice); var halfAngle = ((startAngle+slice.angle) + startAngle)/2; var x = centerLeft + Math.round(Math.cos(halfAngle) * radius); var y = centerTop + Math.round(Math.sin(halfAngle) * radius) * options.series.pie.tilt; var html = '<span class="pieLabel" id="pieLabel'+index+'" style="position:absolute;top:' + y + 'px;left:' + x + 'px;">' + text + "</span>"; target.append(html); var label = target.children('#pieLabel'+index); var labelTop = (y - label.height()/2); var labelLeft = (x - label.width()/2); label.css('top', labelTop); label.css('left', labelLeft); // check to make sure that the label is not outside the canvas if (0-labelTop>0 || 0-labelLeft>0 || canvas.height-(labelTop+label.height())<0 || canvas.width-(labelLeft+label.width())<0) redraw = true; if (options.series.pie.label.background.opacity != 0) { // put in the transparent background separately to avoid blended labels and label boxes var c = options.series.pie.label.background.color; if (c == null) { c = slice.color; } var pos = 'top:'+labelTop+'px;left:'+labelLeft+'px;'; $('<div class="pieLabelBackground" style="position:absolute;width:' + label.width() + 'px;height:' + label.height() + 'px;' + pos +'background-color:' + c + ';"> </div>').insertBefore(label).css('opacity', options.series.pie.label.background.opacity); } } // end individual label function } // end drawLabels function } // end drawPie function } // end draw function // Placed here because it needs to be accessed from multiple locations function drawDonutHole(layer) { // draw donut hole if(options.series.pie.innerRadius > 0) { // subtract the center layer.save(); innerRadius = options.series.pie.innerRadius > 1 ? options.series.pie.innerRadius : maxRadius * options.series.pie.innerRadius; layer.globalCompositeOperation = 'destination-out'; // this does not work with excanvas, but it will fall back to using the stroke color layer.beginPath(); layer.fillStyle = options.series.pie.stroke.color; layer.arc(0,0,innerRadius,0,Math.PI*2,false); layer.fill(); layer.closePath(); layer.restore(); // add inner stroke layer.save(); layer.beginPath(); layer.strokeStyle = options.series.pie.stroke.color; layer.arc(0,0,innerRadius,0,Math.PI*2,false); layer.stroke(); layer.closePath(); layer.restore(); // TODO: add extra shadow inside hole (with a mask) if the pie is tilted. } } //-- Additional Interactive related functions -- function isPointInPoly(poly, pt) { for(var c = false, i = -1, l = poly.length, j = l - 1; ++i < l; j = i) ((poly[i][1] <= pt[1] && pt[1] < poly[j][1]) || (poly[j][1] <= pt[1] && pt[1]< poly[i][1])) && (pt[0] < (poly[j][0] - poly[i][0]) * (pt[1] - poly[i][1]) / (poly[j][1] - poly[i][1]) + poly[i][0]) && (c = !c); return c; } function findNearbySlice(mouseX, mouseY) { var slices = plot.getData(), options = plot.getOptions(), radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius; for (var i = 0; i < slices.length; ++i) { var s = slices[i]; if(s.pie.show) { ctx.save(); ctx.beginPath(); ctx.moveTo(0,0); // Center of the pie //ctx.scale(1, options.series.pie.tilt); // this actually seems to break everything when here. ctx.arc(0,0,radius,s.startAngle,s.startAngle+s.angle,false); ctx.closePath(); x = mouseX-centerLeft; y = mouseY-centerTop; if(ctx.isPointInPath) { if (ctx.isPointInPath(mouseX-centerLeft, mouseY-centerTop)) { //alert('found slice!'); ctx.restore(); return {datapoint: [s.percent, s.data], dataIndex: 0, series: s, seriesIndex: i}; } } else { // excanvas for IE doesn;t support isPointInPath, this is a workaround. p1X = (radius * Math.cos(s.startAngle)); p1Y = (radius * Math.sin(s.startAngle)); p2X = (radius * Math.cos(s.startAngle+(s.angle/4))); p2Y = (radius * Math.sin(s.startAngle+(s.angle/4))); p3X = (radius * Math.cos(s.startAngle+(s.angle/2))); p3Y = (radius * Math.sin(s.startAngle+(s.angle/2))); p4X = (radius * Math.cos(s.startAngle+(s.angle/1.5))); p4Y = (radius * Math.sin(s.startAngle+(s.angle/1.5))); p5X = (radius * Math.cos(s.startAngle+s.angle)); p5Y = (radius * Math.sin(s.startAngle+s.angle)); arrPoly = [[0,0],[p1X,p1Y],[p2X,p2Y],[p3X,p3Y],[p4X,p4Y],[p5X,p5Y]]; arrPoint = [x,y]; // TODO: perhaps do some mathmatical trickery here with the Y-coordinate to compensate for pie tilt? if(isPointInPoly(arrPoly, arrPoint)) { ctx.restore(); return {datapoint: [s.percent, s.data], dataIndex: 0, series: s, seriesIndex: i}; } } ctx.restore(); } } return null; } function onMouseMove(e) { triggerClickHoverEvent('plothover', e); } function onClick(e) { triggerClickHoverEvent('plotclick', e); } // trigger click or hover event (they send the same parameters so we share their code) function triggerClickHoverEvent(eventname, e) { var offset = plot.offset(), canvasX = parseInt(e.pageX - offset.left), canvasY = parseInt(e.pageY - offset.top), item = findNearbySlice(canvasX, canvasY); if (options.grid.autoHighlight) { // clear auto-highlights for (var i = 0; i < highlights.length; ++i) { var h = highlights[i]; if (h.auto == eventname && !(item && h.series == item.series)) unhighlight(h.series); } } // highlight the slice if (item) highlight(item.series, eventname); // trigger any hover bind events var pos = { pageX: e.pageX, pageY: e.pageY }; target.trigger(eventname, [ pos, item ]); } function highlight(s, auto) { if (typeof s == "number") s = series[s]; var i = indexOfHighlight(s); if (i == -1) { highlights.push({ series: s, auto: auto }); plot.triggerRedrawOverlay(); } else if (!auto) highlights[i].auto = false; } function unhighlight(s) { if (s == null) { highlights = []; plot.triggerRedrawOverlay(); } if (typeof s == "number") s = series[s]; var i = indexOfHighlight(s); if (i != -1) { highlights.splice(i, 1); plot.triggerRedrawOverlay(); } } function indexOfHighlight(s) { for (var i = 0; i < highlights.length; ++i) { var h = highlights[i]; if (h.series == s) return i; } return -1; } function drawOverlay(plot, octx) { //alert(options.series.pie.radius); var options = plot.getOptions(); //alert(options.series.pie.radius); var radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius; octx.save(); octx.translate(centerLeft, centerTop); octx.scale(1, options.series.pie.tilt); for (i = 0; i < highlights.length; ++i) drawHighlight(highlights[i].series); drawDonutHole(octx); octx.restore(); function drawHighlight(series) { if (series.angle < 0) return; //octx.fillStyle = parseColor(options.series.pie.highlight.color).scale(null, null, null, options.series.pie.highlight.opacity).toString(); octx.fillStyle = "rgba(255, 255, 255, "+options.series.pie.highlight.opacity+")"; // this is temporary until we have access to parseColor octx.beginPath(); if (Math.abs(series.angle - Math.PI*2) > 0.000000001) octx.moveTo(0,0); // Center of the pie octx.arc(0,0,radius,series.startAngle,series.startAngle+series.angle,false); octx.closePath(); octx.fill(); } } } // end init (plugin body) // define pie specific options and their default values var options = { series: { pie: { show: false, radius: 'auto', // actual radius of the visible pie (based on full calculated radius if <=1, or hard pixel value) innerRadius:0, /* for donut */ startAngle: 3/2, tilt: 1, offset: { top: 0, left: 'auto' }, stroke: { color: '#FFF', width: 1 }, label: { show: 'auto', formatter: function(label, slice){ return '<div style="font-size:x-small;text-align:center;padding:2px;color:'+slice.color+';">'+label+'<br/>'+Math.round(slice.percent)+'%</div>'; }, // formatter function radius: 1, // radius at which to place the labels (based on full calculated radius if <=1, or hard pixel value) background: { color: null, opacity: 0 }, threshold: 0 // percentage at which to hide the label (i.e. the slice is too narrow) }, combine: { threshold: -1, // percentage at which to combine little slices into one larger slice color: null, // color to give the new slice (auto-generated if null) label: 'Other' // label to give the new slice }, highlight: { //color: '#FFF', // will add this functionality once parseColor is available opacity: 0.5 } } } }; $.plot.plugins.push({ init: init, options: options, name: "pie", version: "1.0" }); })(jQuery);
JavaScript
/* Flot plugin for plotting images, e.g. useful for putting ticks on a prerendered complex visualization. The data syntax is [[image, x1, y1, x2, y2], ...] where (x1, y1) and (x2, y2) are where you intend the two opposite corners of the image to end up in the plot. Image must be a fully loaded Javascript image (you can make one with new Image()). If the image is not complete, it's skipped when plotting. There are two helpers included for retrieving images. The easiest work the way that you put in URLs instead of images in the data (like ["myimage.png", 0, 0, 10, 10]), then call $.plot.image.loadData(data, options, callback) where data and options are the same as you pass in to $.plot. This loads the images, replaces the URLs in the data with the corresponding images and calls "callback" when all images are loaded (or failed loading). In the callback, you can then call $.plot with the data set. See the included example. A more low-level helper, $.plot.image.load(urls, callback) is also included. Given a list of URLs, it calls callback with an object mapping from URL to Image object when all images are loaded or have failed loading. Options for the plugin are series: { images: { show: boolean anchor: "corner" or "center" alpha: [0,1] } } which can be specified for a specific series $.plot($("#placeholder"), [{ data: [ ... ], images: { ... } ]) Note that because the data format is different from usual data points, you can't use images with anything else in a specific data series. Setting "anchor" to "center" causes the pixels in the image to be anchored at the corner pixel centers inside of at the pixel corners, effectively letting half a pixel stick out to each side in the plot. A possible future direction could be support for tiling for large images (like Google Maps). */ (function ($) { var options = { series: { images: { show: false, alpha: 1, anchor: "corner" // or "center" } } }; $.plot.image = {}; $.plot.image.loadDataImages = function (series, options, callback) { var urls = [], points = []; var defaultShow = options.series.images.show; $.each(series, function (i, s) { if (!(defaultShow || s.images.show)) return; if (s.data) s = s.data; $.each(s, function (i, p) { if (typeof p[0] == "string") { urls.push(p[0]); points.push(p); } }); }); $.plot.image.load(urls, function (loadedImages) { $.each(points, function (i, p) { var url = p[0]; if (loadedImages[url]) p[0] = loadedImages[url]; }); callback(); }); } $.plot.image.load = function (urls, callback) { var missing = urls.length, loaded = {}; if (missing == 0) callback({}); $.each(urls, function (i, url) { var handler = function () { --missing; loaded[url] = this; if (missing == 0) callback(loaded); }; $('<img />').load(handler).error(handler).attr('src', url); }); } function drawSeries(plot, ctx, series) { var plotOffset = plot.getPlotOffset(); if (!series.images || !series.images.show) return; var points = series.datapoints.points, ps = series.datapoints.pointsize; for (var i = 0; i < points.length; i += ps) { var img = points[i], x1 = points[i + 1], y1 = points[i + 2], x2 = points[i + 3], y2 = points[i + 4], xaxis = series.xaxis, yaxis = series.yaxis, tmp; // actually we should check img.complete, but it // appears to be a somewhat unreliable indicator in // IE6 (false even after load event) if (!img || img.width <= 0 || img.height <= 0) continue; if (x1 > x2) { tmp = x2; x2 = x1; x1 = tmp; } if (y1 > y2) { tmp = y2; y2 = y1; y1 = tmp; } // if the anchor is at the center of the pixel, expand the // image by 1/2 pixel in each direction if (series.images.anchor == "center") { tmp = 0.5 * (x2-x1) / (img.width - 1); x1 -= tmp; x2 += tmp; tmp = 0.5 * (y2-y1) / (img.height - 1); y1 -= tmp; y2 += tmp; } // clip if (x1 == x2 || y1 == y2 || x1 >= xaxis.max || x2 <= xaxis.min || y1 >= yaxis.max || y2 <= yaxis.min) continue; var sx1 = 0, sy1 = 0, sx2 = img.width, sy2 = img.height; if (x1 < xaxis.min) { sx1 += (sx2 - sx1) * (xaxis.min - x1) / (x2 - x1); x1 = xaxis.min; } if (x2 > xaxis.max) { sx2 += (sx2 - sx1) * (xaxis.max - x2) / (x2 - x1); x2 = xaxis.max; } if (y1 < yaxis.min) { sy2 += (sy1 - sy2) * (yaxis.min - y1) / (y2 - y1); y1 = yaxis.min; } if (y2 > yaxis.max) { sy1 += (sy1 - sy2) * (yaxis.max - y2) / (y2 - y1); y2 = yaxis.max; } x1 = xaxis.p2c(x1); x2 = xaxis.p2c(x2); y1 = yaxis.p2c(y1); y2 = yaxis.p2c(y2); // the transformation may have swapped us if (x1 > x2) { tmp = x2; x2 = x1; x1 = tmp; } if (y1 > y2) { tmp = y2; y2 = y1; y1 = tmp; } tmp = ctx.globalAlpha; ctx.globalAlpha *= series.images.alpha; ctx.drawImage(img, sx1, sy1, sx2 - sx1, sy2 - sy1, x1 + plotOffset.left, y1 + plotOffset.top, x2 - x1, y2 - y1); ctx.globalAlpha = tmp; } } function processRawData(plot, series, data, datapoints) { if (!series.images.show) return; // format is Image, x1, y1, x2, y2 (opposite corners) datapoints.format = [ { required: true }, { x: true, number: true, required: true }, { y: true, number: true, required: true }, { x: true, number: true, required: true }, { y: true, number: true, required: true } ]; } function init(plot) { plot.hooks.processRawData.push(processRawData); plot.hooks.drawSeries.push(drawSeries); } $.plot.plugins.push({ init: init, options: options, name: 'image', version: '1.1' }); })(jQuery);
JavaScript
// (c) 2010 Jeff Mesnil -- http://jmesnil.net/ (function(window) { var Stomp = {}; Stomp.frame = function(command, headers, body) { return { command: command, headers: headers, body: body, toString: function() { var out = command + '\n'; if (headers) { for (header in headers) { if(headers.hasOwnProperty(header)) { out = out + header + ': ' + headers[header] + '\n'; } } } out = out + '\n'; if (body) { out = out + body; } return out; } } }; trim = function(str) { return str.replace(/^\s+/g,'').replace(/\s+$/g,''); }; Stomp.unmarshal = function(data) { var divider = data.search(/\n\n/), headerLines = data.substring(0, divider).split('\n'), command = headerLines.shift(), headers = {}, body = ''; // Parse headers var line = idx = null; for (var i = 0; i < headerLines.length; i++) { line = headerLines[i]; idx = line.indexOf(':'); headers[trim(line.substring(0, idx))] = trim(line.substring(idx + 1)); } // Parse body, stopping at the first \0 found. // TODO: Add support for content-length header. var chr = null; for (var i = divider + 2; i < data.length; i++) { chr = data.charAt(i); if (chr === '\0') { break; } body += chr; } return Stomp.frame(command, headers, body); }; Stomp.marshal = function(command, headers, body) { return Stomp.frame(command, headers, body).toString() + '\0'; }; Stomp.client = function (url){ var that, ws, login, passcode; var counter = 0; // used to index subscribers // subscription callbacks indexed by subscriber's ID var subscriptions = {}; debug = function(str) { if (that.debug) { that.debug(str); } }; onmessage = function(evt) { debug('<<< ' + evt.data); var frame = Stomp.unmarshal(evt.data); if (frame.command === "CONNECTED" && that.connectCallback) { that.connectCallback(frame); } else if (frame.command === "MESSAGE") { var onreceive = subscriptions[frame.headers.subscription]; if (onreceive) { onreceive(frame); } } else if (frame.command === "RECEIPT" && that.onreceipt) { that.onreceipt(frame); } else if (frame.command === "ERROR" && that.onerror) { that.onerror(frame); } }; transmit = function(command, headers, body) { var out = Stomp.marshal(command, headers, body); debug(">>> " + out); ws.send(out); }; that = {}; that.connect = function(login_, passcode_, connectCallback, errorCallback) { debug("Opening Web Socket..."); ws = new WebSocket(url); ws.onmessage = onmessage; ws.onclose = function() { var msg = "Whoops! Lost connection to " + url; debug(msg); if (errorCallback) { errorCallback(msg); } }; ws.onopen = function() { debug('Web Socket Opened...'); transmit("CONNECT", {login: login, passcode: passcode}); // connectCallback handler will be called from onmessage when a CONNECTED frame is received }; login = login_; passcode = passcode_; that.connectCallback = connectCallback; }; that.disconnect = function(disconnectCallback) { transmit("DISCONNECT"); ws.close(); if (disconnectCallback) { disconnectCallback(); } }; that.send = function(destination, headers, body) { var headers = headers || {}; headers.destination = destination; transmit("SEND", headers, body); }; that.subscribe = function(destination, callback, headers) { var headers = headers || {}; var id = "sub-" + counter++; headers.destination = destination; headers.id = id; subscriptions[id] = callback; transmit("SUBSCRIBE", headers); return id; }; that.unsubscribe = function(id, headers) { var headers = headers || {}; headers.id = id; delete subscriptions[id]; transmit("UNSUBSCRIBE", headers); }; that.begin = function(transaction, headers) { var headers = headers || {}; headers.transaction = transaction; transmit("BEGIN", headers); }; that.commit = function(transaction, headers) { var headers = headers || {}; headers.transaction = transaction; transmit("COMMIT", headers); }; that.abort = function(transaction, headers) { var headers = headers || {}; headers.transaction = transaction; transmit("ABORT", headers); }; that.ack = function(message_id, headers) { var headers = headers || {}; headers["message-id"] = message_id; transmit("ACK", headers); }; return that; }; window.Stomp = Stomp; })(window);
JavaScript
/* * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/ * * Uses the built in easing capabilities added In jQuery 1.1 * to offer multiple easing options * * TERMS OF USE - jQuery Easing * * Open source under the BSD License. * * Copyright © 2008 George McGinley Smith * 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 author nor the names of 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. * */ // t: current time, b: begInnIng value, c: change In value, d: duration eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('h.i[\'1a\']=h.i[\'z\'];h.O(h.i,{y:\'D\',z:9(x,t,b,c,d){6 h.i[h.i.y](x,t,b,c,d)},17:9(x,t,b,c,d){6 c*(t/=d)*t+b},D:9(x,t,b,c,d){6-c*(t/=d)*(t-2)+b},13:9(x,t,b,c,d){e((t/=d/2)<1)6 c/2*t*t+b;6-c/2*((--t)*(t-2)-1)+b},X:9(x,t,b,c,d){6 c*(t/=d)*t*t+b},U:9(x,t,b,c,d){6 c*((t=t/d-1)*t*t+1)+b},R:9(x,t,b,c,d){e((t/=d/2)<1)6 c/2*t*t*t+b;6 c/2*((t-=2)*t*t+2)+b},N:9(x,t,b,c,d){6 c*(t/=d)*t*t*t+b},M:9(x,t,b,c,d){6-c*((t=t/d-1)*t*t*t-1)+b},L:9(x,t,b,c,d){e((t/=d/2)<1)6 c/2*t*t*t*t+b;6-c/2*((t-=2)*t*t*t-2)+b},K:9(x,t,b,c,d){6 c*(t/=d)*t*t*t*t+b},J:9(x,t,b,c,d){6 c*((t=t/d-1)*t*t*t*t+1)+b},I:9(x,t,b,c,d){e((t/=d/2)<1)6 c/2*t*t*t*t*t+b;6 c/2*((t-=2)*t*t*t*t+2)+b},G:9(x,t,b,c,d){6-c*8.C(t/d*(8.g/2))+c+b},15:9(x,t,b,c,d){6 c*8.n(t/d*(8.g/2))+b},12:9(x,t,b,c,d){6-c/2*(8.C(8.g*t/d)-1)+b},Z:9(x,t,b,c,d){6(t==0)?b:c*8.j(2,10*(t/d-1))+b},Y:9(x,t,b,c,d){6(t==d)?b+c:c*(-8.j(2,-10*t/d)+1)+b},W:9(x,t,b,c,d){e(t==0)6 b;e(t==d)6 b+c;e((t/=d/2)<1)6 c/2*8.j(2,10*(t-1))+b;6 c/2*(-8.j(2,-10*--t)+2)+b},V:9(x,t,b,c,d){6-c*(8.o(1-(t/=d)*t)-1)+b},S:9(x,t,b,c,d){6 c*8.o(1-(t=t/d-1)*t)+b},Q:9(x,t,b,c,d){e((t/=d/2)<1)6-c/2*(8.o(1-t*t)-1)+b;6 c/2*(8.o(1-(t-=2)*t)+1)+b},P:9(x,t,b,c,d){f s=1.l;f p=0;f a=c;e(t==0)6 b;e((t/=d)==1)6 b+c;e(!p)p=d*.3;e(a<8.w(c)){a=c;f s=p/4}m f s=p/(2*8.g)*8.r(c/a);6-(a*8.j(2,10*(t-=1))*8.n((t*d-s)*(2*8.g)/p))+b},H:9(x,t,b,c,d){f s=1.l;f p=0;f a=c;e(t==0)6 b;e((t/=d)==1)6 b+c;e(!p)p=d*.3;e(a<8.w(c)){a=c;f s=p/4}m f s=p/(2*8.g)*8.r(c/a);6 a*8.j(2,-10*t)*8.n((t*d-s)*(2*8.g)/p)+c+b},T:9(x,t,b,c,d){f s=1.l;f p=0;f a=c;e(t==0)6 b;e((t/=d/2)==2)6 b+c;e(!p)p=d*(.3*1.5);e(a<8.w(c)){a=c;f s=p/4}m f s=p/(2*8.g)*8.r(c/a);e(t<1)6-.5*(a*8.j(2,10*(t-=1))*8.n((t*d-s)*(2*8.g)/p))+b;6 a*8.j(2,-10*(t-=1))*8.n((t*d-s)*(2*8.g)/p)*.5+c+b},F:9(x,t,b,c,d,s){e(s==u)s=1.l;6 c*(t/=d)*t*((s+1)*t-s)+b},E:9(x,t,b,c,d,s){e(s==u)s=1.l;6 c*((t=t/d-1)*t*((s+1)*t+s)+1)+b},16:9(x,t,b,c,d,s){e(s==u)s=1.l;e((t/=d/2)<1)6 c/2*(t*t*(((s*=(1.B))+1)*t-s))+b;6 c/2*((t-=2)*t*(((s*=(1.B))+1)*t+s)+2)+b},A:9(x,t,b,c,d){6 c-h.i.v(x,d-t,0,c,d)+b},v:9(x,t,b,c,d){e((t/=d)<(1/2.k)){6 c*(7.q*t*t)+b}m e(t<(2/2.k)){6 c*(7.q*(t-=(1.5/2.k))*t+.k)+b}m e(t<(2.5/2.k)){6 c*(7.q*(t-=(2.14/2.k))*t+.11)+b}m{6 c*(7.q*(t-=(2.18/2.k))*t+.19)+b}},1b:9(x,t,b,c,d){e(t<d/2)6 h.i.A(x,t*2,0,c,d)*.5+b;6 h.i.v(x,t*2-d,0,c,d)*.5+c*.5+b}});',62,74,'||||||return||Math|function|||||if|var|PI|jQuery|easing|pow|75|70158|else|sin|sqrt||5625|asin|||undefined|easeOutBounce|abs||def|swing|easeInBounce|525|cos|easeOutQuad|easeOutBack|easeInBack|easeInSine|easeOutElastic|easeInOutQuint|easeOutQuint|easeInQuint|easeInOutQuart|easeOutQuart|easeInQuart|extend|easeInElastic|easeInOutCirc|easeInOutCubic|easeOutCirc|easeInOutElastic|easeOutCubic|easeInCirc|easeInOutExpo|easeInCubic|easeOutExpo|easeInExpo||9375|easeInOutSine|easeInOutQuad|25|easeOutSine|easeInOutBack|easeInQuad|625|984375|jswing|easeInOutBounce'.split('|'),0,{})) /* * * TERMS OF USE - EASING EQUATIONS * * Open source under the BSD License. * * Copyright © 2001 Robert Penner * 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 author nor the names of 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. * */
JavaScript
// NOTICE!! DO NOT USE ANY OF THIS JAVASCRIPT // IT'S ALL JUST JUNK FOR OUR DOCS! // ++++++++++++++++++++++++++++++++++++++++++ !function ($) { $(function(){ // Disable certain links in docs $('section [href^=#]').click(function (e) { e.preventDefault() }) // make code pretty window.prettyPrint && prettyPrint() // add-ons $('.add-on :checkbox').on('click', function () { var $this = $(this) , method = $this.attr('checked') ? 'addClass' : 'removeClass' $(this).parents('.add-on')[method]('active') }) // position static twipsies for components page if ($(".twipsies a").length) { $(window).on('load resize', function () { $(".twipsies a").each(function () { $(this) .tooltip({ placement: $(this).attr('title') , trigger: 'manual' }) .tooltip('show') }) }) } // add tipsies to grid for scaffolding if ($('#grid-system').length) { $('#grid-system').tooltip({ selector: '.show-grid > div' , title: function () { return $(this).width() + 'px' } }) } // fix sub nav on scroll var $win = $(window) , $nav = $('.subnav') , navTop = $('.subnav').length && $('.subnav').offset().top - 40 , isFixed = 0 processScroll() // hack sad times - holdover until rewrite for 2.1 $nav.on('click', function () { if (!isFixed) setTimeout(function () { $win.scrollTop($win.scrollTop() - 47) }, 10) }) $win.on('scroll', processScroll) function processScroll() { var i, scrollTop = $win.scrollTop() if (scrollTop >= navTop && !isFixed) { isFixed = 1 $nav.addClass('subnav-fixed') } else if (scrollTop <= navTop && isFixed) { isFixed = 0 $nav.removeClass('subnav-fixed') } } // tooltip demo $('.tooltip-demo.well').tooltip({ selector: "a[rel=tooltip]" }) $('.tooltip-test').tooltip() $('.popover-test').popover() // popover demo $("a[rel=popover]") .popover() .click(function(e) { e.preventDefault() }) // button state demo $('#fat-btn') .click(function () { var btn = $(this) btn.button('loading') setTimeout(function () { btn.button('reset') }, 3000) }) // carousel demo $('#myCarousel').carousel() // javascript build logic var inputsComponent = $("#components.download input") , inputsPlugin = $("#plugins.download input") , inputsVariables = $("#variables.download input") // toggle all plugin checkboxes $('#components.download .toggle-all').on('click', function (e) { e.preventDefault() inputsComponent.attr('checked', !inputsComponent.is(':checked')) }) $('#plugins.download .toggle-all').on('click', function (e) { e.preventDefault() inputsPlugin.attr('checked', !inputsPlugin.is(':checked')) }) $('#variables.download .toggle-all').on('click', function (e) { e.preventDefault() inputsVariables.val('') }) // request built javascript $('.download-btn').on('click', function () { var css = $("#components.download input:checked") .map(function () { return this.value }) .toArray() , js = $("#plugins.download input:checked") .map(function () { return this.value }) .toArray() , vars = {} , img = ['glyphicons-halflings.png', 'glyphicons-halflings-white.png'] $("#variables.download input") .each(function () { $(this).val() && (vars[ $(this).prev().text() ] = $(this).val()) }) $.ajax({ type: 'POST' , url: /\?dev/.test(window.location) ? 'http://localhost:3000' : 'http://bootstrap.herokuapp.com' , dataType: 'jsonpi' , params: { js: js , css: css , vars: vars , img: img } }) }) }) // Modified from the original jsonpi https://github.com/benvinegar/jquery-jsonpi $.ajaxTransport('jsonpi', function(opts, originalOptions, jqXHR) { var url = opts.url; return { send: function(_, completeCallback) { var name = 'jQuery_iframe_' + jQuery.now() , iframe, form iframe = $('<iframe>') .attr('name', name) .appendTo('head') form = $('<form>') .attr('method', opts.type) // GET or POST .attr('action', url) .attr('target', name) $.each(opts.params, function(k, v) { $('<input>') .attr('type', 'hidden') .attr('name', k) .attr('value', typeof v == 'string' ? v : JSON.stringify(v)) .appendTo(form) }) form.appendTo('body').submit() } } }) }(window.jQuery)
JavaScript
var scrolltotop={ //startline: Integer. Number of pixels from top of doc scrollbar is scrolled before showing control //scrollto: Keyword (Integer, or "Scroll_to_Element_ID"). How far to scroll document up when control is clicked on (0=top). setting: {startline:100, scrollto: 0, scrollduration:1000, fadeduration:[500, 100]}, controlHTML: '<img src="static/images/scrolltop.png" style="width:107px; height:108px" />', //HTML for control, which is auto wrapped in DIV w/ ID="topcontrol" controlattrs: {offsetx:5, offsety:5}, //offset of control relative to right/ bottom of window corner anchorkeyword: '#top', //Enter href value of HTML anchors on the page that should also act as "Scroll Up" links state: {isvisible:false, shouldvisible:false}, scrollup:function(){ if (!this.cssfixedsupport) //if control is positioned using JavaScript this.$control.css({opacity:0}) //hide control immediately after clicking it var dest=isNaN(this.setting.scrollto)? this.setting.scrollto : parseInt(this.setting.scrollto) if (typeof dest=="string" && jQuery('#'+dest).length==1) //check element set by string exists dest=jQuery('#'+dest).offset().top else dest=0 this.$body.animate({scrollTop: dest}, this.setting.scrollduration); }, keepfixed:function(){ var $window=jQuery(window) var controlx=$window.scrollLeft() + $window.width() - this.$control.width() - this.controlattrs.offsetx var controly=$window.scrollTop() + $window.height() - this.$control.height() - this.controlattrs.offsety this.$control.css({left:controlx+'px', top:controly+'px'}) }, togglecontrol:function(){ var scrolltop=jQuery(window).scrollTop() if (!this.cssfixedsupport) this.keepfixed() this.state.shouldvisible=(scrolltop>=this.setting.startline)? true : false if (this.state.shouldvisible && !this.state.isvisible){ this.$control.stop().animate({opacity:1}, this.setting.fadeduration[0]) this.state.isvisible=true } else if (this.state.shouldvisible==false && this.state.isvisible){ this.$control.stop().animate({opacity:0}, this.setting.fadeduration[1]) this.state.isvisible=false } } }
JavaScript
/*! Copyright (c) 2010 Brandon Aaron (http://brandonaaron.net) * Licensed under the MIT License (LICENSE.txt). * * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers. * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix. * Thanks to: Seamus Leahy for adding deltaX and deltaY * * Version: 3.0.4 * * Requires: 1.2.2+ */ (function(d){function g(a){var b=a||window.event,i=[].slice.call(arguments,1),c=0,h=0,e=0;a=d.event.fix(b);a.type="mousewheel";if(a.wheelDelta)c=a.wheelDelta/120;if(a.detail)c=-a.detail/3;e=c;if(b.axis!==undefined&&b.axis===b.HORIZONTAL_AXIS){e=0;h=-1*c}if(b.wheelDeltaY!==undefined)e=b.wheelDeltaY/120;if(b.wheelDeltaX!==undefined)h=-1*b.wheelDeltaX/120;i.unshift(a,c,h,e);return d.event.handle.apply(this,i)}var f=["DOMMouseScroll","mousewheel"];d.event.special.mousewheel={setup:function(){if(this.addEventListener)for(var a= f.length;a;)this.addEventListener(f[--a],g,false);else this.onmousewheel=g},teardown:function(){if(this.removeEventListener)for(var a=f.length;a;)this.removeEventListener(f[--a],g,false);else this.onmousewheel=null}};d.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}})})(jQuery);
JavaScript
jQuery(document).ready(function($){ //GBin1 Scroll up scrolltotop.controlHTML='<img src="static/images/scrolltop.png"/>'; var mainobj=scrolltotop var iebrws=document.all mainobj.cssfixedsupport=!iebrws || iebrws && document.compatMode=="CSS1Compat" && window.XMLHttpRequest //not IE or IE7+ browsers in standards mode mainobj.$body=(window.opera)? (document.compatMode=="CSS1Compat"? $('html') : $('body')) : $('html,body') mainobj.$control=$('<div id="topcontrol">'+mainobj.controlHTML+'</div>') .css({position:mainobj.cssfixedsupport? 'fixed' : 'absolute', bottom:'125px', right:'0', opacity:0, cursor:'pointer'}) .attr({title:'Scroll Back to Top'}) .click(function(){mainobj.scrollup(); return false}) .appendTo('body') if (document.all && !window.XMLHttpRequest && mainobj.$control.text()!='') //loose check for IE6 and below, plus whether control contains any text mainobj.$control.css({width:mainobj.$control.width()}) //IE6- seems to require an explicit width on a DIV containing text mainobj.togglecontrol() $('a[href="' + mainobj.anchorkeyword +'"]').click(function(){ mainobj.scrollup() return false }) $(window).bind('scroll resize', function(e){ mainobj.togglecontrol() }) });
JavaScript
/* * Superfish v1.4.8 - jQuery menu widget * Copyright (c) 2008 Joel Birch * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * CHANGELOG: http://users.tpg.com.au/j_birch/plugins/superfish/changelog.txt */ ;(function($){ $.fn.superfish = function(op){ var sf = $.fn.superfish, c = sf.c, $arrow = $(['<span class="',c.arrowClass,'"> &#187;</span>'].join('')), over = function(){ var $$ = $(this), menu = getMenu($$); clearTimeout(menu.sfTimer); $$.showSuperfishUl().siblings().hideSuperfishUl(); }, out = function(){ var $$ = $(this), menu = getMenu($$), o = sf.op; clearTimeout(menu.sfTimer); menu.sfTimer=setTimeout(function(){ o.retainPath=($.inArray($$[0],o.$path)>-1); $$.hideSuperfishUl(); if (o.$path.length && $$.parents(['li.',o.hoverClass].join('')).length<1){over.call(o.$path);} },o.delay); }, getMenu = function($menu){ var menu = $menu.parents(['ul.',c.menuClass,':first'].join(''))[0]; sf.op = sf.o[menu.serial]; return menu; }, addArrow = function($a){ $a.addClass(c.anchorClass).append($arrow.clone()); }; return this.each(function() { var s = this.serial = sf.o.length; var o = $.extend({},sf.defaults,op); o.$path = $('li.'+o.pathClass,this).slice(0,o.pathLevels).each(function(){ $(this).addClass([o.hoverClass,c.bcClass].join(' ')) .filter('li:has(ul)').removeClass(o.pathClass); }); sf.o[s] = sf.op = o; $('li:has(ul)',this)[($.fn.hoverIntent && !o.disableHI) ? 'hoverIntent' : 'hover'](over,out).each(function() { if (o.autoArrows) addArrow( $('>a:first-child',this) ); }) .not('.'+c.bcClass) .hideSuperfishUl(); var $a = $('a',this); $a.each(function(i){ var $li = $a.eq(i).parents('li'); $a.eq(i).focus(function(){over.call($li);}).blur(function(){out.call($li);}); }); o.onInit.call(this); }).each(function() { var menuClasses = [c.menuClass]; if (sf.op.dropShadows && !($.browser.msie && $.browser.version < 7)) menuClasses.push(c.shadowClass); $(this).addClass(menuClasses.join(' ')); }); }; var sf = $.fn.superfish; sf.o = []; sf.op = {}; sf.IE7fix = function(){ var o = sf.op; if ($.browser.msie && $.browser.version > 6 && o.dropShadows && o.animation.opacity!=undefined) this.toggleClass(sf.c.shadowClass+'-off'); }; sf.c = { bcClass : 'sf-breadcrumb', menuClass : 'sf-js-enabled', anchorClass : 'sf-with-ul', arrowClass : 'sf-sub-indicator', shadowClass : 'sf-shadow' }; sf.defaults = { hoverClass : 'sfHover', pathClass : 'overideThisToUse', pathLevels : 1, delay : 800, animation : {opacity:'show'}, speed : 'normal', autoArrows : true, dropShadows : true, disableHI : false, // true disables hoverIntent detection onInit : function(){}, // callback functions onBeforeShow: function(){}, onShow : function(){}, onHide : function(){} }; $.fn.extend({ hideSuperfishUl : function(){ var o = sf.op, not = (o.retainPath===true) ? o.$path : ''; o.retainPath = false; var $ul = $(['li.',o.hoverClass].join(''),this).add(this).not(not).removeClass(o.hoverClass) .find('>ul').hide().css('visibility','hidden'); o.onHide.call($ul); return this; }, showSuperfishUl : function(){ var o = sf.op, sh = sf.c.shadowClass+'-off', $ul = this.addClass(o.hoverClass) .find('>ul:hidden').css('visibility','visible'); sf.IE7fix.call($ul); o.onBeforeShow.call($ul); $ul.animate(o.animation,o.speed,function(){ sf.IE7fix.call($ul); o.onShow.call($ul); }); return this; } }); })(jQuery);
JavaScript
/* * FancyBox - jQuery Plugin * Simple and fancy lightbox alternative * * Examples and documentation at: http://fancybox.net * * Copyright (c) 2008 - 2010 Janis Skarnelis * That said, it is hardly a one-person project. Many people have submitted bugs, code, and offered their advice freely. Their support is greatly appreciated. * * Version: 1.3.4 (11/11/2010) * Requires: jQuery v1.3+ * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html */ ;(function($) { var tmp, loading, overlay, wrap, outer, content, close, title, nav_left, nav_right, selectedIndex = 0, selectedOpts = {}, selectedArray = [], currentIndex = 0, currentOpts = {}, currentArray = [], ajaxLoader = null, imgPreloader = new Image(), imgRegExp = /\.(jpg|gif|png|bmp|jpeg)(.*)?$/i, swfRegExp = /[^\.]\.(swf)\s*$/i, loadingTimer, loadingFrame = 1, titleHeight = 0, titleStr = '', start_pos, final_pos, busy = false, fx = $.extend($('<div/>')[0], { prop: 0 }), isIE6 = $.browser.msie && $.browser.version < 7 && !window.XMLHttpRequest, /* * Private methods */ _abort = function() { loading.hide(); imgPreloader.onerror = imgPreloader.onload = null; if (ajaxLoader) { ajaxLoader.abort(); } tmp.empty(); }, _error = function() { if (false === selectedOpts.onError(selectedArray, selectedIndex, selectedOpts)) { loading.hide(); busy = false; return; } selectedOpts.titleShow = false; selectedOpts.width = 'auto'; selectedOpts.height = 'auto'; tmp.html( '<p id="fancybox-error">The requested content cannot be loaded.<br />Please try again later.</p>' ); _process_inline(); }, _start = function() { var obj = selectedArray[ selectedIndex ], href, type, title, str, emb, ret; _abort(); selectedOpts = $.extend({}, $.fn.fancybox.defaults, (typeof $(obj).data('fancybox') == 'undefined' ? selectedOpts : $(obj).data('fancybox'))); ret = selectedOpts.onStart(selectedArray, selectedIndex, selectedOpts); if (ret === false) { busy = false; return; } else if (typeof ret == 'object') { selectedOpts = $.extend(selectedOpts, ret); } title = selectedOpts.title || (obj.nodeName ? $(obj).attr('title') : obj.title) || ''; if (obj.nodeName && !selectedOpts.orig) { selectedOpts.orig = $(obj).children("img:first").length ? $(obj).children("img:first") : $(obj); } if (title === '' && selectedOpts.orig && selectedOpts.titleFromAlt) { title = selectedOpts.orig.attr('alt'); } href = selectedOpts.href || (obj.nodeName ? $(obj).attr('href') : obj.href) || null; if ((/^(?:javascript)/i).test(href) || href == '#') { href = null; } if (selectedOpts.type) { type = selectedOpts.type; if (!href) { href = selectedOpts.content; } } else if (selectedOpts.content) { type = 'html'; } else if (href) { if (href.match(imgRegExp)) { type = 'image'; } else if (href.match(swfRegExp)) { type = 'swf'; } else if ($(obj).hasClass("iframe")) { type = 'iframe'; } else if (href.indexOf("#") === 0) { type = 'inline'; } else { type = 'ajax'; } } if (!type) { _error(); return; } if (type == 'inline') { obj = href.substr(href.indexOf("#")); type = $(obj).length > 0 ? 'inline' : 'ajax'; } selectedOpts.type = type; selectedOpts.href = href; selectedOpts.title = title; if (selectedOpts.autoDimensions) { if (selectedOpts.type == 'html' || selectedOpts.type == 'inline' || selectedOpts.type == 'ajax') { selectedOpts.width = 'auto'; selectedOpts.height = 'auto'; } else { selectedOpts.autoDimensions = false; } } if (selectedOpts.modal) { selectedOpts.overlayShow = true; selectedOpts.hideOnOverlayClick = false; selectedOpts.hideOnContentClick = false; selectedOpts.enableEscapeButton = false; selectedOpts.showCloseButton = false; } selectedOpts.padding = parseInt(selectedOpts.padding, 10); selectedOpts.margin = parseInt(selectedOpts.margin, 10); tmp.css('padding', (selectedOpts.padding + selectedOpts.margin)); $('.fancybox-inline-tmp').unbind('fancybox-cancel').bind('fancybox-change', function() { $(this).replaceWith(content.children()); }); switch (type) { case 'html' : tmp.html( selectedOpts.content ); _process_inline(); break; case 'inline' : if ( $(obj).parent().is('#fancybox-content') === true) { busy = false; return; } $('<div class="fancybox-inline-tmp" />') .hide() .insertBefore( $(obj) ) .bind('fancybox-cleanup', function() { $(this).replaceWith(content.children()); }).bind('fancybox-cancel', function() { $(this).replaceWith(tmp.children()); }); $(obj).appendTo(tmp); _process_inline(); break; case 'image': busy = false; $.fancybox.showActivity(); imgPreloader = new Image(); imgPreloader.onerror = function() { _error(); }; imgPreloader.onload = function() { busy = true; imgPreloader.onerror = imgPreloader.onload = null; _process_image(); }; imgPreloader.src = href; break; case 'swf': selectedOpts.scrolling = 'no'; str = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="' + selectedOpts.width + '" height="' + selectedOpts.height + '"><param name="movie" value="' + href + '"></param>'; emb = ''; $.each(selectedOpts.swf, function(name, val) { str += '<param name="' + name + '" value="' + val + '"></param>'; emb += ' ' + name + '="' + val + '"'; }); str += '<embed src="' + href + '" type="application/x-shockwave-flash" width="' + selectedOpts.width + '" height="' + selectedOpts.height + '"' + emb + '></embed></object>'; tmp.html(str); _process_inline(); break; case 'ajax': busy = false; $.fancybox.showActivity(); selectedOpts.ajax.win = selectedOpts.ajax.success; ajaxLoader = $.ajax($.extend({}, selectedOpts.ajax, { url : href, data : selectedOpts.ajax.data || {}, error : function(XMLHttpRequest, textStatus, errorThrown) { if ( XMLHttpRequest.status > 0 ) { _error(); } }, success : function(data, textStatus, XMLHttpRequest) { var o = typeof XMLHttpRequest == 'object' ? XMLHttpRequest : ajaxLoader; if (o.status == 200) { if ( typeof selectedOpts.ajax.win == 'function' ) { ret = selectedOpts.ajax.win(href, data, textStatus, XMLHttpRequest); if (ret === false) { loading.hide(); return; } else if (typeof ret == 'string' || typeof ret == 'object') { data = ret; } } tmp.html( data ); _process_inline(); } } })); break; case 'iframe': _show(); break; } }, _process_inline = function() { var w = selectedOpts.width, h = selectedOpts.height; if (w.toString().indexOf('%') > -1) { w = parseInt( ($(window).width() - (selectedOpts.margin * 2)) * parseFloat(w) / 100, 10) + 'px'; } else { w = w == 'auto' ? 'auto' : w + 'px'; } if (h.toString().indexOf('%') > -1) { h = parseInt( ($(window).height() - (selectedOpts.margin * 2)) * parseFloat(h) / 100, 10) + 'px'; } else { h = h == 'auto' ? 'auto' : h + 'px'; } tmp.wrapInner('<div style="width:' + w + ';height:' + h + ';overflow: ' + (selectedOpts.scrolling == 'auto' ? 'auto' : (selectedOpts.scrolling == 'yes' ? 'scroll' : 'hidden')) + ';position:relative;"></div>'); selectedOpts.width = tmp.width(); selectedOpts.height = tmp.height(); _show(); }, _process_image = function() { selectedOpts.width = imgPreloader.width; selectedOpts.height = imgPreloader.height; $("<img />").attr({ 'id' : 'fancybox-img', 'src' : imgPreloader.src, 'alt' : selectedOpts.title }).appendTo( tmp ); _show(); }, _show = function() { var pos, equal; loading.hide(); if (wrap.is(":visible") && false === currentOpts.onCleanup(currentArray, currentIndex, currentOpts)) { $.event.trigger('fancybox-cancel'); busy = false; return; } busy = true; $(content.add( overlay )).unbind(); $(window).unbind("resize.fb scroll.fb"); $(document).unbind('keydown.fb'); if (wrap.is(":visible") && currentOpts.titlePosition !== 'outside') { wrap.css('height', wrap.height()); } currentArray = selectedArray; currentIndex = selectedIndex; currentOpts = selectedOpts; if (currentOpts.overlayShow) { overlay.css({ 'background-color' : currentOpts.overlayColor, 'opacity' : currentOpts.overlayOpacity, 'cursor' : currentOpts.hideOnOverlayClick ? 'pointer' : 'auto', 'height' : $(document).height() }); if (!overlay.is(':visible')) { if (isIE6) { $('select:not(#fancybox-tmp select)').filter(function() { return this.style.visibility !== 'hidden'; }).css({'visibility' : 'hidden'}).one('fancybox-cleanup', function() { this.style.visibility = 'inherit'; }); } overlay.show(); } } else { overlay.hide(); } final_pos = _get_zoom_to(); _process_title(); if (wrap.is(":visible")) { $( close.add( nav_left ).add( nav_right ) ).hide(); pos = wrap.position(), start_pos = { top : pos.top, left : pos.left, width : wrap.width(), height : wrap.height() }; equal = (start_pos.width == final_pos.width && start_pos.height == final_pos.height); content.fadeTo(currentOpts.changeFade, 0.3, function() { var finish_resizing = function() { content.html( tmp.contents() ).fadeTo(currentOpts.changeFade, 1, _finish); }; $.event.trigger('fancybox-change'); content .empty() .removeAttr('filter') .css({ 'border-width' : currentOpts.padding, 'width' : final_pos.width - currentOpts.padding * 2, 'height' : selectedOpts.autoDimensions ? 'auto' : final_pos.height - titleHeight - currentOpts.padding * 2 }); if (equal) { finish_resizing(); } else { fx.prop = 0; $(fx).animate({prop: 1}, { duration : currentOpts.changeSpeed, easing : currentOpts.easingChange, step : _draw, complete : finish_resizing }); } }); return; } wrap.removeAttr("style"); content.css('border-width', currentOpts.padding); if (currentOpts.transitionIn == 'elastic') { start_pos = _get_zoom_from(); content.html( tmp.contents() ); wrap.show(); if (currentOpts.opacity) { final_pos.opacity = 0; } fx.prop = 0; $(fx).animate({prop: 1}, { duration : currentOpts.speedIn, easing : currentOpts.easingIn, step : _draw, complete : _finish }); return; } if (currentOpts.titlePosition == 'inside' && titleHeight > 0) { title.show(); } content .css({ 'width' : final_pos.width - currentOpts.padding * 2, 'height' : selectedOpts.autoDimensions ? 'auto' : final_pos.height - titleHeight - currentOpts.padding * 2 }) .html( tmp.contents() ); wrap .css(final_pos) .fadeIn( currentOpts.transitionIn == 'none' ? 0 : currentOpts.speedIn, _finish ); }, _format_title = function(title) { if (title && title.length) { if (currentOpts.titlePosition == 'float') { return '<table id="fancybox-title-float-wrap" cellpadding="0" cellspacing="0"><tr><td id="fancybox-title-float-left"></td><td id="fancybox-title-float-main">' + title + '</td><td id="fancybox-title-float-right"></td></tr></table>'; } return '<div id="fancybox-title-' + currentOpts.titlePosition + '">' + title + '</div>'; } return false; }, _process_title = function() { titleStr = currentOpts.title || ''; titleHeight = 0; title .empty() .removeAttr('style') .removeClass(); if (currentOpts.titleShow === false) { title.hide(); return; } titleStr = $.isFunction(currentOpts.titleFormat) ? currentOpts.titleFormat(titleStr, currentArray, currentIndex, currentOpts) : _format_title(titleStr); if (!titleStr || titleStr === '') { title.hide(); return; } title .addClass('fancybox-title-' + currentOpts.titlePosition) .html( titleStr ) .appendTo( 'body' ) .show(); switch (currentOpts.titlePosition) { case 'inside': title .css({ 'width' : final_pos.width - (currentOpts.padding * 2), 'marginLeft' : currentOpts.padding, 'marginRight' : currentOpts.padding }); titleHeight = title.outerHeight(true); title.appendTo( outer ); final_pos.height += titleHeight; break; case 'over': title .css({ 'marginLeft' : currentOpts.padding, 'width' : final_pos.width - (currentOpts.padding * 2), 'bottom' : currentOpts.padding }) .appendTo( outer ); break; case 'float': title .css('left', parseInt((title.width() - final_pos.width - 40)/ 2, 10) * -1) .appendTo( wrap ); break; default: title .css({ 'width' : final_pos.width - (currentOpts.padding * 2), 'paddingLeft' : currentOpts.padding, 'paddingRight' : currentOpts.padding }) .appendTo( wrap ); break; } title.hide(); }, _set_navigation = function() { if (currentOpts.enableEscapeButton || currentOpts.enableKeyboardNav) { $(document).bind('keydown.fb', function(e) { if (e.keyCode == 27 && currentOpts.enableEscapeButton) { e.preventDefault(); $.fancybox.close(); } else if ((e.keyCode == 37 || e.keyCode == 39) && currentOpts.enableKeyboardNav && e.target.tagName !== 'INPUT' && e.target.tagName !== 'TEXTAREA' && e.target.tagName !== 'SELECT') { e.preventDefault(); $.fancybox[ e.keyCode == 37 ? 'prev' : 'next'](); } }); } if (!currentOpts.showNavArrows) { nav_left.hide(); nav_right.hide(); return; } if ((currentOpts.cyclic && currentArray.length > 1) || currentIndex !== 0) { nav_left.show(); } if ((currentOpts.cyclic && currentArray.length > 1) || currentIndex != (currentArray.length -1)) { nav_right.show(); } }, _finish = function () { if (!$.support.opacity) { content.get(0).style.removeAttribute('filter'); wrap.get(0).style.removeAttribute('filter'); } if (selectedOpts.autoDimensions) { content.css('height', 'auto'); } wrap.css('height', 'auto'); if (titleStr && titleStr.length) { title.show(); } if (currentOpts.showCloseButton) { close.show(); } _set_navigation(); if (currentOpts.hideOnContentClick) { content.bind('click', $.fancybox.close); } if (currentOpts.hideOnOverlayClick) { overlay.bind('click', $.fancybox.close); } $(window).bind("resize.fb", $.fancybox.resize); if (currentOpts.centerOnScroll) { $(window).bind("scroll.fb", $.fancybox.center); } if (currentOpts.type == 'iframe') { $('<iframe id="fancybox-frame" name="fancybox-frame' + new Date().getTime() + '" frameborder="0" hspace="0" ' + ($.browser.msie ? 'allowtransparency="true""' : '') + ' scrolling="' + selectedOpts.scrolling + '" src="' + currentOpts.href + '"></iframe>').appendTo(content); } wrap.show(); busy = false; $.fancybox.center(); currentOpts.onComplete(currentArray, currentIndex, currentOpts); _preload_images(); }, _preload_images = function() { var href, objNext; if ((currentArray.length -1) > currentIndex) { href = currentArray[ currentIndex + 1 ].href; if (typeof href !== 'undefined' && href.match(imgRegExp)) { objNext = new Image(); objNext.src = href; } } if (currentIndex > 0) { href = currentArray[ currentIndex - 1 ].href; if (typeof href !== 'undefined' && href.match(imgRegExp)) { objNext = new Image(); objNext.src = href; } } }, _draw = function(pos) { var dim = { width : parseInt(start_pos.width + (final_pos.width - start_pos.width) * pos, 10), height : parseInt(start_pos.height + (final_pos.height - start_pos.height) * pos, 10), top : parseInt(start_pos.top + (final_pos.top - start_pos.top) * pos, 10), left : parseInt(start_pos.left + (final_pos.left - start_pos.left) * pos, 10) }; if (typeof final_pos.opacity !== 'undefined') { dim.opacity = pos < 0.5 ? 0.5 : pos; } wrap.css(dim); content.css({ 'width' : dim.width - currentOpts.padding * 2, 'height' : dim.height - (titleHeight * pos) - currentOpts.padding * 2 }); }, _get_viewport = function() { return [ $(window).width() - (currentOpts.margin * 2), $(window).height() - (currentOpts.margin * 2), $(document).scrollLeft() + currentOpts.margin, $(document).scrollTop() + currentOpts.margin ]; }, _get_zoom_to = function () { var view = _get_viewport(), to = {}, resize = currentOpts.autoScale, double_padding = currentOpts.padding * 2, ratio; if (currentOpts.width.toString().indexOf('%') > -1) { to.width = parseInt((view[0] * parseFloat(currentOpts.width)) / 100, 10); } else { to.width = currentOpts.width + double_padding; } if (currentOpts.height.toString().indexOf('%') > -1) { to.height = parseInt((view[1] * parseFloat(currentOpts.height)) / 100, 10); } else { to.height = currentOpts.height + double_padding; } if (resize && (to.width > view[0] || to.height > view[1])) { if (selectedOpts.type == 'image' || selectedOpts.type == 'swf') { ratio = (currentOpts.width ) / (currentOpts.height ); if ((to.width ) > view[0]) { to.width = view[0]; to.height = parseInt(((to.width - double_padding) / ratio) + double_padding, 10); } if ((to.height) > view[1]) { to.height = view[1]; to.width = parseInt(((to.height - double_padding) * ratio) + double_padding, 10); } } else { to.width = Math.min(to.width, view[0]); to.height = Math.min(to.height, view[1]); } } to.top = parseInt(Math.max(view[3] - 20, view[3] + ((view[1] - to.height - 40) * 0.5)), 10); to.left = parseInt(Math.max(view[2] - 20, view[2] + ((view[0] - to.width - 40) * 0.5)), 10); return to; }, _get_obj_pos = function(obj) { var pos = obj.offset(); pos.top += parseInt( obj.css('paddingTop'), 10 ) || 0; pos.left += parseInt( obj.css('paddingLeft'), 10 ) || 0; pos.top += parseInt( obj.css('border-top-width'), 10 ) || 0; pos.left += parseInt( obj.css('border-left-width'), 10 ) || 0; pos.width = obj.width(); pos.height = obj.height(); return pos; }, _get_zoom_from = function() { var orig = selectedOpts.orig ? $(selectedOpts.orig) : false, from = {}, pos, view; if (orig && orig.length) { pos = _get_obj_pos(orig); from = { width : pos.width + (currentOpts.padding * 2), height : pos.height + (currentOpts.padding * 2), top : pos.top - currentOpts.padding - 20, left : pos.left - currentOpts.padding - 20 }; } else { view = _get_viewport(); from = { width : currentOpts.padding * 2, height : currentOpts.padding * 2, top : parseInt(view[3] + view[1] * 0.5, 10), left : parseInt(view[2] + view[0] * 0.5, 10) }; } return from; }, _animate_loading = function() { if (!loading.is(':visible')){ clearInterval(loadingTimer); return; } $('div', loading).css('top', (loadingFrame * -40) + 'px'); loadingFrame = (loadingFrame + 1) % 12; }; /* * Public methods */ $.fn.fancybox = function(options) { if (!$(this).length) { return this; } $(this) .data('fancybox', $.extend({}, options, ($.metadata ? $(this).metadata() : {}))) .unbind('click.fb') .bind('click.fb', function(e) { e.preventDefault(); if (busy) { return; } busy = true; $(this).blur(); selectedArray = []; selectedIndex = 0; var rel = $(this).attr('rel') || ''; if (!rel || rel == '' || rel === 'nofollow') { selectedArray.push(this); } else { selectedArray = $("a[rel=" + rel + "], area[rel=" + rel + "]"); selectedIndex = selectedArray.index( this ); } _start(); return; }); return this; }; $.fancybox = function(obj) { var opts; if (busy) { return; } busy = true; opts = typeof arguments[1] !== 'undefined' ? arguments[1] : {}; selectedArray = []; selectedIndex = parseInt(opts.index, 10) || 0; if ($.isArray(obj)) { for (var i = 0, j = obj.length; i < j; i++) { if (typeof obj[i] == 'object') { $(obj[i]).data('fancybox', $.extend({}, opts, obj[i])); } else { obj[i] = $({}).data('fancybox', $.extend({content : obj[i]}, opts)); } } selectedArray = jQuery.merge(selectedArray, obj); } else { if (typeof obj == 'object') { $(obj).data('fancybox', $.extend({}, opts, obj)); } else { obj = $({}).data('fancybox', $.extend({content : obj}, opts)); } selectedArray.push(obj); } if (selectedIndex > selectedArray.length || selectedIndex < 0) { selectedIndex = 0; } _start(); }; $.fancybox.showActivity = function() { clearInterval(loadingTimer); loading.show(); loadingTimer = setInterval(_animate_loading, 66); }; $.fancybox.hideActivity = function() { loading.hide(); }; $.fancybox.next = function() { return $.fancybox.pos( currentIndex + 1); }; $.fancybox.prev = function() { return $.fancybox.pos( currentIndex - 1); }; $.fancybox.pos = function(pos) { if (busy) { return; } pos = parseInt(pos); selectedArray = currentArray; if (pos > -1 && pos < currentArray.length) { selectedIndex = pos; _start(); } else if (currentOpts.cyclic && currentArray.length > 1) { selectedIndex = pos >= currentArray.length ? 0 : currentArray.length - 1; _start(); } return; }; $.fancybox.cancel = function() { if (busy) { return; } busy = true; $.event.trigger('fancybox-cancel'); _abort(); selectedOpts.onCancel(selectedArray, selectedIndex, selectedOpts); busy = false; }; // Note: within an iframe use - parent.$.fancybox.close(); $.fancybox.close = function() { if (busy || wrap.is(':hidden')) { return; } busy = true; if (currentOpts && false === currentOpts.onCleanup(currentArray, currentIndex, currentOpts)) { busy = false; return; } _abort(); $(close.add( nav_left ).add( nav_right )).hide(); $(content.add( overlay )).unbind(); $(window).unbind("resize.fb scroll.fb"); $(document).unbind('keydown.fb'); content.find('iframe').attr('src', isIE6 && /^https/i.test(window.location.href || '') ? 'javascript:void(false)' : 'about:blank'); if (currentOpts.titlePosition !== 'inside') { title.empty(); } wrap.stop(); function _cleanup() { overlay.fadeOut('fast'); title.empty().hide(); wrap.hide(); $.event.trigger('fancybox-cleanup'); content.empty(); currentOpts.onClosed(currentArray, currentIndex, currentOpts); currentArray = selectedOpts = []; currentIndex = selectedIndex = 0; currentOpts = selectedOpts = {}; busy = false; } if (currentOpts.transitionOut == 'elastic') { start_pos = _get_zoom_from(); var pos = wrap.position(); final_pos = { top : pos.top , left : pos.left, width : wrap.width(), height : wrap.height() }; if (currentOpts.opacity) { final_pos.opacity = 1; } title.empty().hide(); fx.prop = 1; $(fx).animate({ prop: 0 }, { duration : currentOpts.speedOut, easing : currentOpts.easingOut, step : _draw, complete : _cleanup }); } else { wrap.fadeOut( currentOpts.transitionOut == 'none' ? 0 : currentOpts.speedOut, _cleanup); } }; $.fancybox.resize = function() { if (overlay.is(':visible')) { overlay.css('height', $(document).height()); } $.fancybox.center(true); }; $.fancybox.center = function() { var view, align; if (busy) { return; } align = arguments[0] === true ? 1 : 0; view = _get_viewport(); if (!align && (wrap.width() > view[0] || wrap.height() > view[1])) { return; } wrap .stop() .animate({ 'top' : parseInt(Math.max(view[3] - 20, view[3] + ((view[1] - content.height() - 40) * 0.5) - currentOpts.padding)), 'left' : parseInt(Math.max(view[2] - 20, view[2] + ((view[0] - content.width() - 40) * 0.5) - currentOpts.padding)) }, typeof arguments[0] == 'number' ? arguments[0] : 200); }; $.fancybox.init = function() { if ($("#fancybox-wrap").length) { return; } $('body').append( tmp = $('<div id="fancybox-tmp"></div>'), loading = $('<div id="fancybox-loading"><div></div></div>'), overlay = $('<div id="fancybox-overlay"></div>'), wrap = $('<div id="fancybox-wrap"></div>') ); outer = $('<div id="fancybox-outer"></div>') .append('<div class="fancybox-bg" id="fancybox-bg-n"></div><div class="fancybox-bg" id="fancybox-bg-ne"></div><div class="fancybox-bg" id="fancybox-bg-e"></div><div class="fancybox-bg" id="fancybox-bg-se"></div><div class="fancybox-bg" id="fancybox-bg-s"></div><div class="fancybox-bg" id="fancybox-bg-sw"></div><div class="fancybox-bg" id="fancybox-bg-w"></div><div class="fancybox-bg" id="fancybox-bg-nw"></div>') .appendTo( wrap ); outer.append( content = $('<div id="fancybox-content"></div>'), close = $('<a id="fancybox-close"></a>'), title = $('<div id="fancybox-title"></div>'), nav_left = $('<a href="javascript:;" id="fancybox-left"><span class="fancy-ico" id="fancybox-left-ico"></span></a>'), nav_right = $('<a href="javascript:;" id="fancybox-right"><span class="fancy-ico" id="fancybox-right-ico"></span></a>') ); close.click($.fancybox.close); loading.click($.fancybox.cancel); nav_left.click(function(e) { e.preventDefault(); $.fancybox.prev(); }); nav_right.click(function(e) { e.preventDefault(); $.fancybox.next(); }); if ($.fn.mousewheel) { wrap.bind('mousewheel.fb', function(e, delta) { if (busy) { e.preventDefault(); } else if ($(e.target).get(0).clientHeight == 0 || $(e.target).get(0).scrollHeight === $(e.target).get(0).clientHeight) { e.preventDefault(); $.fancybox[ delta > 0 ? 'prev' : 'next'](); } }); } if (!$.support.opacity) { wrap.addClass('fancybox-ie'); } if (isIE6) { loading.addClass('fancybox-ie6'); wrap.addClass('fancybox-ie6'); $('<iframe id="fancybox-hide-sel-frame" src="' + (/^https/i.test(window.location.href || '') ? 'javascript:void(false)' : 'about:blank' ) + '" scrolling="no" border="0" frameborder="0" tabindex="-1"></iframe>').prependTo(outer); } }; $.fn.fancybox.defaults = { padding : 10, margin : 40, opacity : false, modal : false, cyclic : false, scrolling : 'auto', // 'auto', 'yes' or 'no' width : 560, height : 340, autoScale : true, autoDimensions : true, centerOnScroll : false, ajax : {}, swf : { wmode: 'transparent' }, hideOnOverlayClick : true, hideOnContentClick : false, overlayShow : true, overlayOpacity : 0.7, overlayColor : '#777', titleShow : true, titlePosition : 'float', // 'float', 'outside', 'inside' or 'over' titleFormat : null, titleFromAlt : false, transitionIn : 'fade', // 'elastic', 'fade' or 'none' transitionOut : 'fade', // 'elastic', 'fade' or 'none' speedIn : 300, speedOut : 300, changeSpeed : 300, changeFade : 'fast', easingIn : 'swing', easingOut : 'swing', showCloseButton : true, showNavArrows : true, enableEscapeButton : true, enableKeyboardNav : true, onStart : function(){}, onCancel : function(){}, onComplete : function(){}, onCleanup : function(){}, onClosed : function(){}, onError : function(){} }; $(document).ready(function() { $.fancybox.init(); }); })(jQuery);
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 unsupported Iris. if ( ! $.support.iris ) 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 ), respWidth; // reset any compensation for submenus near the bottom of the screen $('#adminmenu div.wp-submenu').css('margin-top', ''); // WebKit excludes the width of the vertical scrollbar when applying the CSS "@media screen and (max-width: ...)" // and matches $(window).width(). // Firefox and IE > 8 include the scrollbar width, so after the jQuery normalization // $(window).width() is 884px but window.innerWidth is 900px. // (using window.innerWidth also excludes IE < 9) respWidth = navigator.userAgent.indexOf('AppleWebKit/') > -1 ? $(window).width() : window.innerWidth; if ( respWidth && respWidth < 900 ) { if ( body.hasClass('auto-fold') ) { body.removeClass('auto-fold').removeClass('folded'); setUserSetting('unfold', 1); setUserSetting('mfold', 'o'); } else { body.addClass('auto-fold'); setUserSetting('unfold', 0); } } else { if ( body.hasClass('folded') ) { body.removeClass('folded'); setUserSetting('mfold', 'o'); } 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).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
( function( $ ){ $( document ).ready( function () { // Expand/Collapse on click $( '.accordion-container' ).on( 'click keydown', '.accordion-section-title', function( e ) { if ( e.type === 'keydown' && 13 !== e.which ) // "return" key return; e.preventDefault(); // Keep this AFTER the key filter above accordionSwitch( $( this ) ); }); // Re-initialize accordion when screen options are toggled $( '.hide-postbox-tog' ).click( function () { accordionInit(); }); }); var accordionOptions = $( '.accordion-container li.accordion-section' ), sectionContent = $( '.accordion-section-content' ); function accordionInit () { // Rounded corners accordionOptions.removeClass( 'top bottom' ); accordionOptions.filter( ':visible' ).first().addClass( 'top' ); accordionOptions.filter( ':visible' ).last().addClass( 'bottom' ).find( sectionContent ).addClass( 'bottom' ); } function accordionSwitch ( el ) { var section = el.closest( '.accordion-section' ), siblings = section.closest( '.accordion-container' ).find( '.open' ), content = section.find( sectionContent ); if ( section.hasClass( 'cannot-expand' ) ) return; if ( section.hasClass( 'open' ) ) { section.toggleClass( 'open' ); content.toggle( true ).slideToggle( 150 ); } else { siblings.removeClass( 'open' ); siblings.find( sectionContent ).show().slideUp( 150 ); content.toggle( false ).slideToggle( 150 ); section.toggleClass( 'open' ); } accordionInit(); } // Initialize the accordion (currently just corner fixes) accordionInit(); })(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 ) this.initSortables(); if ( menus.oneThemeLocationNoMenus ) $( '#posttype-page' ).addSelectedToMenu( api.addMenuItemToBottom ); this.initManageLocations(); this.initAccessibility(); this.initToggles(); }, 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; }, shiftHorizontally : function( dir ) { return this.each(function(){ var t = $(this), depth = t.menuItemDepth(), newDepth = depth + dir; // Change .menu-item-depth-n class t.moveHorizontally( newDepth, depth ); }); }, moveHorizontally : function( newDepth, depth ) { return this.each(function(){ var t = $(this), children = t.childMenuItems(), diff = newDepth - depth, subItemText = t.find('.is-submenu'); // Change .menu-item-depth-n class t.updateDepthClass( newDepth, depth ).updateParentMenuItemDBId(); // If it has children, move those too if ( children ) { children.each(function( index ) { var t = $(this), thisDepth = t.menuItemDepth(), newDepth = thisDepth + diff; t.updateDepthClass(newDepth, thisDepth).updateParentMenuItemDBId(); }); } // Show "Sub item" helper text if (0 === newDepth) subItemText.hide(); else subItemText.show(); }); }, updateParentMenuItemDBId : function() { return this.each(function(){ var item = $(this), input = item.find( '.menu-item-data-parent-id' ), depth = parseInt( item.menuItemDepth() ), parentDepth = depth - 1, parent = item.prevAll( '.menu-item-depth-' + parentDepth ).first(); if ( 0 == depth ) { // Item is on the top level, has no parent input.val(0); } else { // Find the parent item, and retrieve its object id. 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 = ( menus.oneThemeLocationNoMenus && 0 == t.find('.tabs-panel-active .categorychecklist li input:checked').length ) ? t.find('#page-all li input[type="checkbox"]') : 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; } }); }, countMenuItems : function( depth ) { return $( '.menu-item-depth-' + depth ).length; }, moveMenuItem : function( $this, dir ) { var menuItems = $('#menu-to-edit li'); menuItemsCount = menuItems.length, thisItem = $this.parents( 'li.menu-item' ), thisItemChildren = thisItem.childMenuItems(), thisItemData = thisItem.getItemData(), thisItemDepth = parseInt( thisItem.menuItemDepth() ), thisItemPosition = parseInt( thisItem.index() ), nextItem = thisItem.next(), nextItemChildren = nextItem.childMenuItems(), nextItemDepth = parseInt( nextItem.menuItemDepth() ) + 1, prevItem = thisItem.prev(), prevItemDepth = parseInt( prevItem.menuItemDepth() ), prevItemId = prevItem.getItemData()['menu-item-db-id']; switch ( dir ) { case 'up': var newItemPosition = thisItemPosition - 1; // Already at top if ( 0 === thisItemPosition ) break; // If a sub item is moved to top, shift it to 0 depth if ( 0 === newItemPosition && 0 !== thisItemDepth ) thisItem.moveHorizontally( 0, thisItemDepth ); // If prev item is sub item, shift to match depth if ( 0 !== prevItemDepth ) thisItem.moveHorizontally( prevItemDepth, thisItemDepth ); // Does this item have sub items? if ( thisItemChildren ) { var items = thisItem.add( thisItemChildren ); // Move the entire block items.detach().insertBefore( menuItems.eq( newItemPosition ) ).updateParentMenuItemDBId(); } else { thisItem.detach().insertBefore( menuItems.eq( newItemPosition ) ).updateParentMenuItemDBId(); } break; case 'down': // Does this item have sub items? if ( thisItemChildren ) { var items = thisItem.add( thisItemChildren ), nextItem = menuItems.eq( items.length + thisItemPosition ), nextItemChildren = 0 !== nextItem.childMenuItems().length; if ( nextItemChildren ) { var newDepth = parseInt( nextItem.menuItemDepth() ) + 1; thisItem.moveHorizontally( newDepth, thisItemDepth ); } // Have we reached the bottom? if ( menuItemsCount === thisItemPosition + items.length ) break; items.detach().insertAfter( menuItems.eq( thisItemPosition + items.length ) ).updateParentMenuItemDBId(); } else { // If next item has sub items, shift depth if ( 0 !== nextItemChildren.length ) thisItem.moveHorizontally( nextItemDepth, thisItemDepth ); // Have we reached the bottom if ( menuItemsCount === thisItemPosition + 1 ) break; thisItem.detach().insertAfter( menuItems.eq( thisItemPosition + 1 ) ).updateParentMenuItemDBId(); } break; case 'top': // Already at top if ( 0 === thisItemPosition ) break; // Does this item have sub items? if ( thisItemChildren ) { var items = thisItem.add( thisItemChildren ); // Move the entire block items.detach().insertBefore( menuItems.eq( 0 ) ).updateParentMenuItemDBId(); } else { thisItem.detach().insertBefore( menuItems.eq( 0 ) ).updateParentMenuItemDBId(); } break; case 'left': // As far left as possible if ( 0 === thisItemDepth ) break; thisItem.shiftHorizontally( -1 ); break; case 'right': // Can't be sub item at top if ( 0 === thisItemPosition ) break; // Already sub item of prevItem if ( thisItemData['menu-item-parent-id'] === prevItemId ) break; thisItem.shiftHorizontally( 1 ); break; } $this.focus(); api.registerChange(); api.refreshKeyboardAccessibility(); api.refreshAdvancedAccessibility(); }, initAccessibility : function() { api.refreshKeyboardAccessibility(); api.refreshAdvancedAccessibility(); // Events $( '.menus-move-up' ).on( 'click', function ( e ) { api.moveMenuItem( $( this ).parents( 'li.menu-item' ).find( 'a.item-edit' ), 'up' ); e.preventDefault(); }); $( '.menus-move-down' ).on( 'click', function ( e ) { api.moveMenuItem( $( this ).parents( 'li.menu-item' ).find( 'a.item-edit' ), 'down' ); e.preventDefault(); }); $( '.menus-move-top' ).on( 'click', function ( e ) { api.moveMenuItem( $( this ).parents( 'li.menu-item' ).find( 'a.item-edit' ), 'top' ); e.preventDefault(); }); $( '.menus-move-left' ).on( 'click', function ( e ) { api.moveMenuItem( $( this ).parents( 'li.menu-item' ).find( 'a.item-edit' ), 'left' ); e.preventDefault(); }); $( '.menus-move-right' ).on( 'click', function ( e ) { api.moveMenuItem( $( this ).parents( 'li.menu-item' ).find( 'a.item-edit' ), 'right' ); e.preventDefault(); }); }, refreshAdvancedAccessibility : function() { // Hide all links by default $( '.menu-item-settings .field-move a' ).hide(); $( '.item-edit' ).each( function() { var $this = $(this), movement = [], availableMovement = '', menuItem = $this.parents( 'li.menu-item' ).first(), depth = menuItem.menuItemDepth(), isPrimaryMenuItem = ( 0 === depth ), itemName = $this.parents( '.menu-item-handle' ).find( '.menu-item-title' ).text(), position = parseInt( menuItem.index() ), prevItemDepth = ( isPrimaryMenuItem ) ? depth : parseInt( depth - 1 ), prevItemNameLeft = menuItem.prevAll('.menu-item-depth-' + prevItemDepth).first().find( '.menu-item-title' ).text(), prevItemNameRight = menuItem.prevAll('.menu-item-depth-' + depth).first().find( '.menu-item-title' ).text(), totalMenuItems = $('#menu-to-edit li').length, hasSameDepthSibling = menuItem.nextAll( '.menu-item-depth-' + depth ).length; // Where can they move this menu item? if ( 0 !== position ) { var thisLink = menuItem.find( '.menus-move-up' ); thisLink.prop( 'title', menus.moveUp ).show(); } if ( 0 !== position && isPrimaryMenuItem ) { var thisLink = menuItem.find( '.menus-move-top' ); thisLink.prop( 'title', menus.moveToTop ).show(); } if ( position + 1 !== totalMenuItems && 0 !== position ) { var thisLink = menuItem.find( '.menus-move-down' ); thisLink.prop( 'title', menus.moveDown ).show(); } if ( 0 === position && 0 !== hasSameDepthSibling ) { var thisLink = menuItem.find( '.menus-move-down' ); thisLink.prop( 'title', menus.moveDown ).show(); } if ( ! isPrimaryMenuItem ) { var thisLink = menuItem.find( '.menus-move-left' ), thisLinkText = menus.outFrom.replace( '%s', prevItemNameLeft ); thisLink.prop( 'title', menus.moveOutFrom.replace( '%s', prevItemNameLeft ) ).html( thisLinkText ).show(); } if ( 0 !== position ) { if ( menuItem.find( '.menu-item-data-parent-id' ).val() !== menuItem.prev().find( '.menu-item-data-db-id' ).val() ) { var thisLink = menuItem.find( '.menus-move-right' ), thisLinkText = menus.under.replace( '%s', prevItemNameRight ); thisLink.prop( 'title', menus.moveUnder.replace( '%s', prevItemNameRight ) ).html( thisLinkText ).show(); } } if ( isPrimaryMenuItem ) { var primaryItems = $( '.menu-item-depth-0' ), itemPosition = primaryItems.index( menuItem ) + 1, totalMenuItems = primaryItems.length, // String together help text for primary menu items title = menus.menuFocus.replace( '%1$s', itemName ).replace( '%2$d', itemPosition ).replace( '%3$d', totalMenuItems ); } else { var parentItem = menuItem.prevAll( '.menu-item-depth-' + parseInt( depth - 1 ) ).first(), parentItemId = parentItem.find( '.menu-item-data-db-id' ).val(), parentItemName = parentItem.find( '.menu-item-title' ).text(), subItems = $( '.menu-item .menu-item-data-parent-id[value="' + parentItemId + '"]' ), itemPosition = $( subItems.parents('.menu-item').get().reverse() ).index( menuItem ) + 1; // String together help text for sub menu items title = menus.subMenuFocus.replace( '%1$s', itemName ).replace( '%2$d', itemPosition ).replace( '%3$s', parentItemName ); } $this.prop('title', title).html( title ); }); }, refreshKeyboardAccessibility : function() { $( '.item-edit' ).off( 'focus' ).on( 'focus', function(){ $(this).off( 'keydown' ).on( 'keydown', function(e){ var $this = $(this); // Bail if it's not an arrow key if ( 37 != e.which && 38 != e.which && 39 != e.which && 40 != e.which ) return; // Avoid multiple keydown events $this.off('keydown'); // Bail if there is only one menu item if ( 1 === $('#menu-to-edit li').length ) return; // If RTL, swap left/right arrows var arrows = { '38' : 'up', '40' : 'down', '37' : 'left', '39' : 'right' }; if ( $('body').hasClass('rtl') ) arrows = { '38' : 'up', '40' : 'down', '39' : 'left', '37' : 'right' }; switch ( arrows[e.which] ) { case 'up': api.moveMenuItem( $this, 'up' ); break; case 'down': api.moveMenuItem( $this, 'down' ); break; case 'left': api.moveMenuItem( $this, 'left' ); break; case 'right': api.moveMenuItem( $this, 'right' ); break; } // Put focus back on same menu item $( '#edit-' + thisItemData['menu-item-db-id'] ).focus(); return false; }); }); }, 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(); $('.hide-postbox-tog').click(function () { var hidden = $( '.accordion-container li.accordion-section' ).filter(':hidden').map(function() { return this.id; }).get().join(','); $.post(ajaxurl, { action: 'closed-postboxes', hidden: hidden, closedpostboxesnonce: jQuery('#closedpostboxesnonce').val(), page: 'nav-menus' }); }); }, initSortables : function() { var currentDepth = 0, originalDepth, minDepth, maxDepth, prev, next, prevBottom, nextThreshold, helperHeight, transport, menuEdge = api.menuList.offset().left, body = $('body'), maxChildDepth, menuMaxDepth = initialMenuMaxDepth(); if( 0 != $( '#menu-to-edit li' ).length ) $( '.drag-instructions' ).show(); // 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); // Add "sub menu" description var subMenuTitle = ui.item.find( '.item-title .is-submenu' ); if ( 0 < currentDepth ) subMenuTitle.show(); else subMenuTitle.hide(); // 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; } api.refreshKeyboardAccessibility(); api.refreshAdvancedAccessibility(); }, 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; } }, initManageLocations : function () { $('#menu-locations-wrap form').submit(function(){ window.onbeforeunload = null; }); $('.menu-location-menus select').on('change', function () { var editLink = $(this).closest('tr').find('.locations-edit-menu-link'); if ($(this).find('option:selected').data('orig')) editLink.show(); else editLink.hide(); }); }, 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) ); }); $( '.blank-slate .input-with-default-title' ).focus(); }, 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); // Make it stand out a bit more visually, by adding a fadeIn $( 'li.pending' ).hide().fadeIn('slow'); $( '.drag-instructions' ).show(); 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 ); api.refreshKeyboardAccessibility(); api.refreshAdvancedAccessibility(); }, addMenuItemToTop : function( menuMarkup, req ) { $(menuMarkup).hideAdvancedMenuItemFields().prependTo( api.targetList ); api.refreshKeyboardAccessibility(); api.refreshAdvancedAccessibility(); }, attachUnsavedChangesListener : function() { $('#menu-management input, #menu-management select, #menu-management, #menu-management textarea, .menu-location-menus select').change(function(){ api.registerChange(); }); if ( 0 != $('#menu-to-edit').length || 0 != $('.menu-location-menus select').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' ).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 = target.data( 'type' ); wrapper = target.parents('.accordion-section-content').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(); e.preventDefault(); } 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; } }); }, 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' ), thisMenuItem = $( clickedEl ).closest( '.menu-item' ); thisMenuItem.removeClass('menu-item-edit-active').addClass('menu-item-edit-inactive'); settings.setItemData( settings.data('menu-item-data') ).hide(); 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( 0 == $( '#menu-to-edit li' ).length ) { $( '.drag-instructions' ).hide(); 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('&nbsp;').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 .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); } } ); }; $(document).on( 'heartbeat-send.refresh-lock', function( e, data ) { var lock = $('#active_post_lock').val(), post_id = $('#post_ID').val(), send = {}; if ( ! post_id || ! $('#post-lock-dialog').length ) return; send['post_id'] = post_id; if ( lock ) send['lock'] = lock; data['wp-refresh-post-lock'] = send; }); // Post locks: update the lock string or show the dialog if somebody has taken over editing $(document).on( 'heartbeat-tick.refresh-lock', function( e, data ) { var received, wrap, avatar; if ( data['wp-refresh-post-lock'] ) { received = data['wp-refresh-post-lock']; if ( received.lock_error ) { // show "editing taken over" message wrap = $('#post-lock-dialog'); if ( wrap.length && ! wrap.is(':visible') ) { if ( typeof autosave == 'function' ) { $(document).on('autosave-disable-buttons.post-lock', function() { wrap.addClass('saving'); }).on('autosave-enable-buttons.post-lock', function() { wrap.removeClass('saving').addClass('saved'); window.onbeforeunload = null; }); // Save the latest changes and disable if ( ! autosave() ) window.onbeforeunload = null; autosave = function(){}; } if ( received.lock_error.avatar_src ) { avatar = $('<img class="avatar avatar-64 photo" width="64" height="64" />').attr( 'src', received.lock_error.avatar_src.replace(/&amp;/g, '&') ); wrap.find('div.post-locked-avatar').empty().append( avatar ); } wrap.show().find('.currently-editing').text( received.lock_error.text ); wrap.find('.wp-tab-first').focus(); } } else if ( received.new_lock ) { $('#active_post_lock').val( received.new_lock ); } } }); }(jQuery)); (function($) { var check, timeout; function schedule() { check = false; window.clearTimeout( timeout ); timeout = window.setTimeout( function(){ check = true; }, 300000 ); } $(document).on( 'heartbeat-send.wp-refresh-nonces', function( e, data ) { var nonce, post_id; if ( check ) { if ( ( post_id = $('#post_ID').val() ) && ( nonce = $('#_wpnonce').val() ) ) { data['wp-refresh-post-nonces'] = { post_id: post_id, post_nonce: nonce }; } } }).on( 'heartbeat-tick.wp-refresh-nonces', function( e, data ) { var nonces = data['wp-refresh-post-nonces']; if ( nonces ) { schedule(); if ( nonces.replace ) { $.each( nonces.replace, function( selector, value ) { $( '#' + selector ).val( value ); }); } if ( nonces.heartbeatNonce ) window.heartbeatSettings.nonce = nonces.heartbeatNonce; } }).ready( function() { schedule(); }); }(jQuery)); jQuery(document).ready( function($) { var stamp, visibility, sticky = '', last = 0, co = $('#content'); postboxes.add_postbox_toggles(pagenow); // Post locks: contain focus inside the dialog. If the dialog is shown, focus the first item. $('#post-lock-dialog .notification-dialog').on( 'keydown', function(e) { if ( e.which != 9 ) return; var target = $(e.target); if ( target.hasClass('wp-tab-first') && e.shiftKey ) { $(this).find('.wp-tab-last').focus(); e.preventDefault(); } else if ( target.hasClass('wp-tab-last') && ! e.shiftKey ) { $(this).find('.wp-tab-first').focus(); e.preventDefault(); } }).filter(':visible').find('.wp-tab-first').focus(); // 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'), catAddBefore, 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(); }); 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, #' + taxonomy + 'checklist-pop').on( 'click', 'li.popular-category > label input[type="checkbox"]', 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>' + postL10n.dateFormat.replace( '%1$s', $('option[value="' + $('#mm').val() + '"]', '#mm').text() ) .replace( '%2$s', jj ) .replace( '%3$s', aa ) .replace( '%4$s', hh ) .replace( '%5$s', 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) { var box = $('#edit-slug-box'); box.html(data); if (box.hasClass('hidden')) { box.fadeIn('fast', function () { box.removeClass('hidden'); }); } 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; } }).keyup(function(e) { 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 ( !textarea.length || 'ontouchstart' in window ) return; function dragging(e) { textarea.height( Math.max(50, offset + e.pageY) + 'px' ); return false; } function endDrag(e) { var height; textarea.focus(); $(document).unbind('mousemove', dragging).unbind('mouseup', endDrag); height = parseInt( textarea.css('height'), 10 ); // sanity check if ( height && height > 50 && height < 5000 ) 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; function getHeight() { var height, node = document.getElementById('content_ifr'), ifr_height = node ? parseInt( node.style.height, 10 ) : 0, tb_height = $('#content_tbl tr.mceFirst').height(); if ( !ifr_height || !tb_height ) return false; // total height including toolbar and statusbar height = ifr_height + tb_height + 21; // textarea height = total height - 33px toolbar height -= 33; return height; } // resize TinyMCE to match the textarea height when switching Text -> Visual ed.onLoadContent.add( function(ed, o) { var ifr_height, node = document.getElementById('content'), height = node ? parseInt( node.style.height, 10 ) : 0, tb_height = $('#content_tbl tr.mceFirst').height() || 33; // height cannot be under 50 or over 5000 if ( !height || height < 50 || height > 5000 ) height = 360; // default height for the main editor if ( getUserSetting( 'ed_size' ) > 5000 ) setUserSetting( 'ed_size', 360 ); // compensate for padding and toolbars ifr_height = ( height - tb_height ) + 12; // 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 = getHeight(); if ( !height || height < 50 || height > 5000 ) return; $('textarea#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; $(document).off('mouseup.wp-mce-resize'); height = getHeight(); // sanity check if ( height && height > 50 && height < 5000 ) setUserSetting( 'ed_size', height ); }); }); }); }); // When changing post formats, change the editor body class $('#post-formats-select input.post-format').on( 'change.set-editor-class', function( event ) { var editor, body, format = this.id; if ( format && $( this ).prop('checked') ) { editor = tinymce.get( 'content' ); if ( editor ) { body = editor.getBody(); body.className = body.className.replace( /\bpost-format-[^ ]+/, '' ); editor.dom.addClass( body, format == 'post-format-0' ? 'post-format-standard' : format ); } } }); } });
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 = '&nbsp; <a href="' + url + '" target="_top" class="tb-theme-preview-link">' + text + '</a>'; } else { text = $(this).attr('title') || ''; link = '&nbsp; <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
window.wp = window.wp || {}; (function($) { var revisions; revisions = wp.revisions = { model: {}, view: {}, controller: {} }; // Link settings. revisions.settings = _.isUndefined( _wpRevisionsSettings ) ? {} : _wpRevisionsSettings; // For debugging revisions.debug = false; revisions.log = function() { if ( window.console && revisions.debug ) console.log.apply( console, arguments ); }; // Handy functions to help with positioning $.fn.allOffsets = function() { var offset = this.offset() || {top: 0, left: 0}, win = $(window); return _.extend( offset, { right: win.width() - offset.left - this.outerWidth(), bottom: win.height() - offset.top - this.outerHeight() }); }; $.fn.allPositions = function() { var position = this.position() || {top: 0, left: 0}, parent = this.parent(); return _.extend( position, { right: parent.outerWidth() - position.left - this.outerWidth(), bottom: parent.outerHeight() - position.top - this.outerHeight() }); }; // wp_localize_script transforms top-level numbers into strings. Undo that. if ( revisions.settings.to ) revisions.settings.to = parseInt( revisions.settings.to, 10 ); if ( revisions.settings.from ) revisions.settings.from = parseInt( revisions.settings.from, 10 ); // wp_localize_script does not allow for top-level booleans. Fix that. if ( revisions.settings.compareTwoMode ) revisions.settings.compareTwoMode = revisions.settings.compareTwoMode === '1'; /** * ======================================================================== * MODELS * ======================================================================== */ revisions.model.Slider = Backbone.Model.extend({ defaults: { value: null, values: null, min: 0, max: 1, step: 1, range: false, compareTwoMode: false }, initialize: function( options ) { this.frame = options.frame; this.revisions = options.revisions; // Listen for changes to the revisions or mode from outside this.listenTo( this.frame, 'update:revisions', this.receiveRevisions ); this.listenTo( this.frame, 'change:compareTwoMode', this.updateMode ); // Listen for internal changes this.listenTo( this, 'change:from', this.handleLocalChanges ); this.listenTo( this, 'change:to', this.handleLocalChanges ); this.listenTo( this, 'change:compareTwoMode', this.updateSliderSettings ); this.listenTo( this, 'update:revisions', this.updateSliderSettings ); // Listen for changes to the hovered revision this.listenTo( this, 'change:hoveredRevision', this.hoverRevision ); this.set({ max: this.revisions.length - 1, compareTwoMode: this.frame.get('compareTwoMode'), from: this.frame.get('from'), to: this.frame.get('to') }); this.updateSliderSettings(); }, getSliderValue: function( a, b ) { return isRtl ? this.revisions.length - this.revisions.indexOf( this.get(a) ) - 1 : this.revisions.indexOf( this.get(b) ); }, updateSliderSettings: function() { if ( this.get('compareTwoMode') ) { this.set({ values: [ this.getSliderValue( 'to', 'from' ), this.getSliderValue( 'from', 'to' ) ], value: null, range: true // ensures handles cannot cross }); } else { this.set({ value: this.getSliderValue( 'to', 'to' ), values: null, range: false }); } this.trigger( 'update:slider' ); }, // Called when a revision is hovered hoverRevision: function( model, value ) { this.trigger( 'hovered:revision', value ); }, // Called when `compareTwoMode` changes updateMode: function( model, value ) { this.set({ compareTwoMode: value }); }, // Called when `from` or `to` changes in the local model handleLocalChanges: function() { this.frame.set({ from: this.get('from'), to: this.get('to') }); }, // Receives revisions changes from outside the model receiveRevisions: function( from, to ) { // Bail if nothing changed if ( this.get('from') === from && this.get('to') === to ) return; this.set({ from: from, to: to }, { silent: true }); this.trigger( 'update:revisions', from, to ); } }); revisions.model.Tooltip = Backbone.Model.extend({ defaults: { revision: null, offset: {}, hovering: false, // Whether the mouse is hovering scrubbing: false // Whether the mouse is scrubbing }, initialize: function( options ) { this.frame = options.frame; this.revisions = options.revisions; this.slider = options.slider; this.listenTo( this.slider, 'hovered:revision', this.updateRevision ); this.listenTo( this.slider, 'change:hovering', this.setHovering ); this.listenTo( this.slider, 'change:scrubbing', this.setScrubbing ); }, updateRevision: function( revision ) { this.set({ revision: revision }); }, setHovering: function( model, value ) { this.set({ hovering: value }); }, setScrubbing: function( model, value ) { this.set({ scrubbing: value }); } }); revisions.model.Revision = Backbone.Model.extend({}); revisions.model.Revisions = Backbone.Collection.extend({ model: revisions.model.Revision, initialize: function() { _.bindAll( this, 'next', 'prev' ); }, next: function( revision ) { var index = this.indexOf( revision ); if ( index !== -1 && index !== this.length - 1 ) return this.at( index + 1 ); }, prev: function( revision ) { var index = this.indexOf( revision ); if ( index !== -1 && index !== 0 ) return this.at( index - 1 ); } }); revisions.model.Field = Backbone.Model.extend({}); revisions.model.Fields = Backbone.Collection.extend({ model: revisions.model.Field }); revisions.model.Diff = Backbone.Model.extend({ initialize: function( attributes, options ) { var fields = this.get('fields'); this.unset('fields'); this.fields = new revisions.model.Fields( fields ); } }); revisions.model.Diffs = Backbone.Collection.extend({ initialize: function( models, options ) { _.bindAll( this, 'getClosestUnloaded' ); this.loadAll = _.once( this._loadAll ); this.revisions = options.revisions; this.requests = {}; }, model: revisions.model.Diff, ensure: function( id, context ) { var diff = this.get( id ); var request = this.requests[ id ]; var deferred = $.Deferred(); var ids = {}; var from = id.split(':')[0]; var to = id.split(':')[1]; ids[id] = true; wp.revisions.log( 'ensure', id ); this.trigger( 'ensure', ids, from, to, deferred.promise() ); if ( diff ) { deferred.resolveWith( context, [ diff ] ); } else { this.trigger( 'ensure:load', ids, from, to, deferred.promise() ); _.each( ids, _.bind( function( id ) { // Remove anything that has an ongoing request if ( this.requests[ id ] ) delete ids[ id ]; // Remove anything we already have if ( this.get( id ) ) delete ids[ id ]; }, this ) ); if ( ! request ) { // Always include the ID that started this ensure ids[ id ] = true; request = this.load( _.keys( ids ) ); } request.done( _.bind( function() { deferred.resolveWith( context, [ this.get( id ) ] ); }, this ) ).fail( _.bind( function() { deferred.reject(); }) ); } return deferred.promise(); }, // Returns an array of proximal diffs getClosestUnloaded: function( ids, centerId ) { var self = this; return _.chain([0].concat( ids )).initial().zip( ids ).sortBy( function( pair ) { return Math.abs( centerId - pair[1] ); }).map( function( pair ) { return pair.join(':'); }).filter( function( diffId ) { return _.isUndefined( self.get( diffId ) ) && ! self.requests[ diffId ]; }).value(); }, _loadAll: function( allRevisionIds, centerId, num ) { var self = this, deferred = $.Deferred(); diffs = _.first( this.getClosestUnloaded( allRevisionIds, centerId ), num ); if ( _.size( diffs ) > 0 ) { this.load( diffs ).done( function() { self._loadAll( allRevisionIds, centerId, num ).done( function() { deferred.resolve(); }); }).fail( function() { if ( 1 === num ) { // Already tried 1. This just isn't working. Give up. deferred.reject(); } else { // Request fewer diffs this time self._loadAll( allRevisionIds, centerId, Math.ceil( num / 2 ) ).done( function() { deferred.resolve(); }); } }); } else { deferred.resolve(); } return deferred; }, load: function( comparisons ) { wp.revisions.log( 'load', comparisons ); // Our collection should only ever grow, never shrink, so remove: false return this.fetch({ data: { compare: comparisons }, remove: false }).done( function(){ wp.revisions.log( 'load:complete', comparisons ); }); }, sync: function( method, model, options ) { if ( 'read' === method ) { options = options || {}; options.context = this; options.data = _.extend( options.data || {}, { action: 'get-revision-diffs', post_id: revisions.settings.postId }); var deferred = wp.ajax.send( options ); var requests = this.requests; // Record that we're requesting each diff. if ( options.data.compare ) { _.each( options.data.compare, function( id ) { requests[ id ] = deferred; }); } // When the request completes, clear the stored request. deferred.always( function() { if ( options.data.compare ) { _.each( options.data.compare, function( id ) { delete requests[ id ]; }); } }); return deferred; // Otherwise, fall back to `Backbone.sync()`. } else { return Backbone.Model.prototype.sync.apply( this, arguments ); } } }); revisions.model.FrameState = Backbone.Model.extend({ defaults: { loading: false, error: false, compareTwoMode: false }, initialize: function( attributes, options ) { var properties = {}; _.bindAll( this, 'receiveDiff' ); this._debouncedEnsureDiff = _.debounce( this._ensureDiff, 200 ); this.revisions = options.revisions; this.diffs = new revisions.model.Diffs( [], { revisions: this.revisions }); // Set the initial diffs collection provided through the settings this.diffs.set( revisions.settings.diffData ); // Set up internal listeners this.listenTo( this, 'change:from', this.changeRevisionHandler ); this.listenTo( this, 'change:to', this.changeRevisionHandler ); this.listenTo( this, 'change:compareTwoMode', this.changeMode ); this.listenTo( this, 'update:revisions', this.updatedRevisions ); this.listenTo( this.diffs, 'ensure:load', this.updateLoadingStatus ); this.listenTo( this, 'update:diff', this.updateLoadingStatus ); // Set the initial revisions, baseUrl, and mode as provided through settings properties.to = this.revisions.get( revisions.settings.to ); properties.from = this.revisions.get( revisions.settings.from ); properties.compareTwoMode = revisions.settings.compareTwoMode; properties.baseUrl = revisions.settings.baseUrl; this.set( properties ); // Start the router if browser supports History API if ( window.history && window.history.pushState ) { this.router = new revisions.Router({ model: this }); Backbone.history.start({ pushState: true }); } }, updateLoadingStatus: function() { this.set( 'error', false ); this.set( 'loading', ! this.diff() ); }, changeMode: function( model, value ) { // If we were on the first revision before switching, we have to bump them over one if ( value && 0 === this.revisions.indexOf( this.get('to') ) ) { this.set({ from: this.revisions.at(0), to: this.revisions.at(1) }); } }, updatedRevisions: function( from, to ) { if ( this.get( 'compareTwoMode' ) ) { // TODO: compare-two loading strategy } else { this.diffs.loadAll( this.revisions.pluck('id'), to.id, 40 ); } }, // Fetch the currently loaded diff. diff: function() { return this.diffs.get( this._diffId ); }, // So long as `from` and `to` are changed at the same time, the diff // will only be updated once. This is because Backbone updates all of // the changed attributes in `set`, and then fires the `change` events. updateDiff: function( options ) { var from, to, diffId, diff; options = options || {}; from = this.get('from'); to = this.get('to'); diffId = ( from ? from.id : 0 ) + ':' + to.id; // Check if we're actually changing the diff id. if ( this._diffId === diffId ) return $.Deferred().reject().promise(); this._diffId = diffId; this.trigger( 'update:revisions', from, to ); diff = this.diffs.get( diffId ); // If we already have the diff, then immediately trigger the update. if ( diff ) { this.receiveDiff( diff ); return $.Deferred().resolve().promise(); // Otherwise, fetch the diff. } else { if ( options.immediate ) { return this._ensureDiff(); } else { this._debouncedEnsureDiff(); return $.Deferred().reject().promise(); } } }, // A simple wrapper around `updateDiff` to prevent the change event's // parameters from being passed through. changeRevisionHandler: function( model, value, options ) { this.updateDiff(); }, receiveDiff: function( diff ) { // Did we actually get a diff? if ( _.isUndefined( diff ) || _.isUndefined( diff.id ) ) { this.set({ loading: false, error: true }); } else if ( this._diffId === diff.id ) { // Make sure the current diff didn't change this.trigger( 'update:diff', diff ); } }, _ensureDiff: function() { return this.diffs.ensure( this._diffId, this ).always( this.receiveDiff ); } }); /** * ======================================================================== * VIEWS * ======================================================================== */ // The frame view. This contains the entire page. revisions.view.Frame = wp.Backbone.View.extend({ className: 'revisions', template: wp.template('revisions-frame'), initialize: function() { this.listenTo( this.model, 'update:diff', this.renderDiff ); this.listenTo( this.model, 'change:compareTwoMode', this.updateCompareTwoMode ); this.listenTo( this.model, 'change:loading', this.updateLoadingStatus ); this.listenTo( this.model, 'change:error', this.updateErrorStatus ); this.views.set( '.revisions-control-frame', new revisions.view.Controls({ model: this.model }) ); }, render: function() { wp.Backbone.View.prototype.render.apply( this, arguments ); $('html').css( 'overflow-y', 'scroll' ); $('#wpbody-content .wrap').append( this.el ); this.updateCompareTwoMode(); this.renderDiff( this.model.diff() ); this.views.ready(); return this; }, renderDiff: function( diff ) { this.views.set( '.revisions-diff-frame', new revisions.view.Diff({ model: diff }) ); }, updateLoadingStatus: function() { this.$el.toggleClass( 'loading', this.model.get('loading') ); }, updateErrorStatus: function() { this.$el.toggleClass( 'diff-error', this.model.get('error') ); }, updateCompareTwoMode: function() { this.$el.toggleClass( 'comparing-two-revisions', this.model.get('compareTwoMode') ); } }); // The control view. // This contains the revision slider, previous/next buttons, the meta info and the compare checkbox. revisions.view.Controls = wp.Backbone.View.extend({ className: 'revisions-controls', initialize: function() { _.bindAll( this, 'setWidth' ); // Add the button view this.views.add( new revisions.view.Buttons({ model: this.model }) ); // Add the checkbox view this.views.add( new revisions.view.Checkbox({ model: this.model }) ); // Prep the slider model var slider = new revisions.model.Slider({ frame: this.model, revisions: this.model.revisions }); // Prep the tooltip model var tooltip = new revisions.model.Tooltip({ frame: this.model, revisions: this.model.revisions, slider: slider }); // Add the tooltip view this.views.add( new revisions.view.Tooltip({ model: tooltip }) ); // Add the tickmarks view this.views.add( new revisions.view.Tickmarks({ model: tooltip }) ); // Add the slider view this.views.add( new revisions.view.Slider({ model: slider }) ); // Add the Metabox view this.views.add( new revisions.view.Metabox({ model: this.model }) ); }, ready: function() { this.top = this.$el.offset().top; this.window = $(window); this.window.on( 'scroll.wp.revisions', {controls: this}, function(e) { var controls = e.data.controls; var container = controls.$el.parent(); var scrolled = controls.window.scrollTop(); var frame = controls.views.parent; if ( scrolled >= controls.top ) { if ( ! frame.$el.hasClass('pinned') ) { controls.setWidth(); container.css('height', container.height() + 'px' ); controls.window.on('resize.wp.revisions.pinning click.wp.revisions.pinning', {controls: controls}, function(e) { e.data.controls.setWidth(); }); } frame.$el.addClass('pinned'); } else if ( frame.$el.hasClass('pinned') ) { controls.window.off('.wp.revisions.pinning'); controls.$el.css('width', 'auto'); frame.$el.removeClass('pinned'); container.css('height', 'auto'); controls.top = controls.$el.offset().top; } else { controls.top = controls.$el.offset().top; } }); }, setWidth: function() { this.$el.css('width', this.$el.parent().width() + 'px'); } }); // The tickmarks view revisions.view.Tickmarks = wp.Backbone.View.extend({ className: 'revisions-tickmarks', direction: isRtl ? 'right' : 'left', initialize: function() { this.listenTo( this.model, 'change:revision', this.reportTickPosition ); }, reportTickPosition: function( model, revision ) { var offset, thisOffset, parentOffset, tick, index = this.model.revisions.indexOf( revision ); thisOffset = this.$el.allOffsets(); parentOffset = this.$el.parent().allOffsets(); if ( index === this.model.revisions.length - 1 ) { // Last one offset = { rightPlusWidth: thisOffset.left - parentOffset.left + 1, leftPlusWidth: thisOffset.right - parentOffset.right + 1 }; } else { // Normal tick tick = this.$('div:nth-of-type(' + (index + 1) + ')'); offset = tick.allPositions(); _.extend( offset, { left: offset.left + thisOffset.left - parentOffset.left, right: offset.right + thisOffset.right - parentOffset.right }); _.extend( offset, { leftPlusWidth: offset.left + tick.outerWidth(), rightPlusWidth: offset.right + tick.outerWidth() }); } this.model.set({ offset: offset }); }, ready: function() { var tickCount, tickWidth; tickCount = this.model.revisions.length - 1; tickWidth = 1 / tickCount; this.$el.css('width', ( this.model.revisions.length * 50 ) + 'px'); _(tickCount).times( function( index ){ this.$el.append( '<div style="' + this.direction + ': ' + ( 100 * tickWidth * index ) + '%"></div>' ); }, this ); } }); // The metabox view revisions.view.Metabox = wp.Backbone.View.extend({ className: 'revisions-meta', initialize: function() { // Add the 'from' view this.views.add( new revisions.view.MetaFrom({ model: this.model, className: 'diff-meta diff-meta-from' }) ); // Add the 'to' view this.views.add( new revisions.view.MetaTo({ model: this.model }) ); } }); // The revision meta view (to be extended) revisions.view.Meta = wp.Backbone.View.extend({ template: wp.template('revisions-meta'), events: { 'click .restore-revision': 'restoreRevision' }, initialize: function() { this.listenTo( this.model, 'update:revisions', this.render ); }, prepare: function() { return _.extend( this.model.toJSON()[this.type] || {}, { type: this.type }); }, restoreRevision: function() { document.location = this.model.get('to').attributes.restoreUrl; } }); // The revision meta 'from' view revisions.view.MetaFrom = revisions.view.Meta.extend({ className: 'diff-meta diff-meta-from', type: 'from' }); // The revision meta 'to' view revisions.view.MetaTo = revisions.view.Meta.extend({ className: 'diff-meta diff-meta-to', type: 'to' }); // The checkbox view. revisions.view.Checkbox = wp.Backbone.View.extend({ className: 'revisions-checkbox', template: wp.template('revisions-checkbox'), events: { 'click .compare-two-revisions': 'compareTwoToggle' }, initialize: function() { this.listenTo( this.model, 'change:compareTwoMode', this.updateCompareTwoMode ); }, ready: function() { if ( this.model.revisions.length < 3 ) $('.revision-toggle-compare-mode').hide(); }, updateCompareTwoMode: function() { this.$('.compare-two-revisions').prop( 'checked', this.model.get('compareTwoMode') ); }, // Toggle the compare two mode feature when the compare two checkbox is checked. compareTwoToggle: function( event ) { // Activate compare two mode? this.model.set({ compareTwoMode: $('.compare-two-revisions').prop('checked') }); } }); // The tooltip view. // Encapsulates the tooltip. revisions.view.Tooltip = wp.Backbone.View.extend({ className: 'revisions-tooltip', template: wp.template('revisions-meta'), initialize: function( options ) { this.listenTo( this.model, 'change:offset', this.render ); this.listenTo( this.model, 'change:hovering', this.toggleVisibility ); this.listenTo( this.model, 'change:scrubbing', this.toggleVisibility ); }, prepare: function() { if ( _.isNull( this.model.get('revision') ) ) return; else return _.extend( { type: 'tooltip' }, { attributes: this.model.get('revision').toJSON() }); }, render: function() { var direction, directionVal, flipped, css = {}, position = this.model.revisions.indexOf( this.model.get('revision') ) + 1; flipped = ( position / this.model.revisions.length ) > 0.5; if ( isRtl ) { direction = flipped ? 'left' : 'right'; directionVal = flipped ? 'leftPlusWidth' : direction; } else { direction = flipped ? 'right' : 'left'; directionVal = flipped ? 'rightPlusWidth' : direction; } otherDirection = 'right' === direction ? 'left': 'right'; wp.Backbone.View.prototype.render.apply( this, arguments ); css[direction] = this.model.get('offset')[directionVal] + 'px'; css[otherDirection] = ''; this.$el.toggleClass( 'flipped', flipped ).css( css ); }, visible: function() { return this.model.get( 'scrubbing' ) || this.model.get( 'hovering' ); }, toggleVisibility: function( options ) { if ( this.visible() ) this.$el.stop().show().fadeTo( 100 - this.el.style.opacity * 100, 1 ); else this.$el.stop().fadeTo( this.el.style.opacity * 300, 0, function(){ $(this).hide(); } ); return; } }); // The buttons view. // Encapsulates all of the configuration for the previous/next buttons. revisions.view.Buttons = wp.Backbone.View.extend({ className: 'revisions-buttons', template: wp.template('revisions-buttons'), events: { 'click .revisions-next .button': 'nextRevision', 'click .revisions-previous .button': 'previousRevision' }, initialize: function() { this.listenTo( this.model, 'update:revisions', this.disabledButtonCheck ); }, ready: function() { this.disabledButtonCheck(); }, // Go to a specific model index gotoModel: function( toIndex ) { var attributes = { to: this.model.revisions.at( toIndex ) }; // If we're at the first revision, unset 'from'. if ( toIndex ) attributes.from = this.model.revisions.at( toIndex - 1 ); else this.model.unset('from', { silent: true }); this.model.set( attributes ); }, // Go to the 'next' revision nextRevision: function() { var toIndex = this.model.revisions.indexOf( this.model.get('to') ) + 1; this.gotoModel( toIndex ); }, // Go to the 'previous' revision previousRevision: function() { var toIndex = this.model.revisions.indexOf( this.model.get('to') ) - 1; this.gotoModel( toIndex ); }, // Check to see if the Previous or Next buttons need to be disabled or enabled. disabledButtonCheck: function() { var maxVal = this.model.revisions.length - 1, minVal = 0, next = $('.revisions-next .button'), previous = $('.revisions-previous .button'), val = this.model.revisions.indexOf( this.model.get('to') ); // Disable "Next" button if you're on the last node. next.prop( 'disabled', ( maxVal === val ) ); // Disable "Previous" button if you're on the first node. previous.prop( 'disabled', ( minVal === val ) ); } }); // The slider view. revisions.view.Slider = wp.Backbone.View.extend({ className: 'wp-slider', direction: isRtl ? 'right' : 'left', events: { 'mousemove' : 'mouseMove' }, initialize: function() { _.bindAll( this, 'start', 'slide', 'stop', 'mouseMove', 'mouseEnter', 'mouseLeave' ); this.listenTo( this.model, 'update:slider', this.applySliderSettings ); }, ready: function() { this.$el.css('width', ( this.model.revisions.length * 50 ) + 'px'); this.$el.slider( _.extend( this.model.toJSON(), { start: this.start, slide: this.slide, stop: this.stop }) ); this.$el.hoverIntent({ over: this.mouseEnter, out: this.mouseLeave, timeout: 800 }); this.applySliderSettings(); }, mouseMove: function( e ) { var zoneCount = this.model.revisions.length - 1, // One fewer zone than models sliderFrom = this.$el.allOffsets()[this.direction], // "From" edge of slider sliderWidth = this.$el.width(), // Width of slider tickWidth = sliderWidth / zoneCount, // Calculated width of zone actualX = isRtl? $(window).width() - e.pageX : e.pageX; // Flipped for RTL - sliderFrom; actualX = actualX - sliderFrom; // Offset of mouse position in slider var currentModelIndex = Math.floor( ( actualX + ( tickWidth / 2 ) ) / tickWidth ); // Calculate the model index // Ensure sane value for currentModelIndex. if ( currentModelIndex < 0 ) currentModelIndex = 0; else if ( currentModelIndex >= this.model.revisions.length ) currentModelIndex = this.model.revisions.length - 1; // Update the tooltip mode this.model.set({ hoveredRevision: this.model.revisions.at( currentModelIndex ) }); }, mouseLeave: function() { this.model.set({ hovering: false }); }, mouseEnter: function() { this.model.set({ hovering: true }); }, applySliderSettings: function() { this.$el.slider( _.pick( this.model.toJSON(), 'value', 'values', 'range' ) ); var handles = this.$('a.ui-slider-handle'); if ( this.model.get('compareTwoMode') ) { // in RTL mode the 'left handle' is the second in the slider, 'right' is first handles.first() .toggleClass( 'to-handle', !! isRtl ) .toggleClass( 'from-handle', ! isRtl ); handles.last() .toggleClass( 'from-handle', !! isRtl ) .toggleClass( 'to-handle', ! isRtl ); } else { handles.removeClass('from-handle to-handle'); } }, start: function( event, ui ) { this.model.set({ scrubbing: true }); // Track the mouse position to enable smooth dragging, // overrides default jQuery UI step behavior. $( window ).on( 'mousemove.wp.revisions', { view: this }, function( e ) { var view = e.data.view, leftDragBoundary = view.$el.offset().left, sliderOffset = leftDragBoundary, sliderRightEdge = leftDragBoundary + view.$el.width(), rightDragBoundary = sliderRightEdge, leftDragReset = '0', rightDragReset = '100%', handle = $( ui.handle ); // In two handle mode, ensure handles can't be dragged past each other. // Adjust left/right boundaries and reset points. if ( view.model.get('compareTwoMode') ) { var handles = handle.parent().find('.ui-slider-handle'); if ( handle.is( handles.first() ) ) { // We're the left handle rightDragBoundary = handles.last().offset().left; rightDragReset = rightDragBoundary - sliderOffset; } else { // We're the right handle leftDragBoundary = handles.first().offset().left + handles.first().width(); leftDragReset = leftDragBoundary - sliderOffset; } } // Follow mouse movements, as long as handle remains inside slider. if ( e.pageX < leftDragBoundary ) { handle.css( 'left', leftDragReset ); // Mouse to left of slider. } else if ( e.pageX > rightDragBoundary ) { handle.css( 'left', rightDragReset ); // Mouse to right of slider. } else { handle.css( 'left', e.pageX - sliderOffset ); // Mouse in slider. } } ); }, getPosition: function( position ) { return isRtl ? this.model.revisions.length - position - 1: position; }, // Responds to slide events slide: function( event, ui ) { var attributes, movedRevision; // Compare two revisions mode if ( this.model.get('compareTwoMode') ) { // Prevent sliders from occupying same spot if ( ui.values[1] === ui.values[0] ) return false; if ( isRtl ) ui.values.reverse(); attributes = { from: this.model.revisions.at( this.getPosition( ui.values[0] ) ), to: this.model.revisions.at( this.getPosition( ui.values[1] ) ) }; } else { attributes = { to: this.model.revisions.at( this.getPosition( ui.value ) ) }; // If we're at the first revision, unset 'from'. if ( this.getPosition( ui.value ) > 0 ) attributes.from = this.model.revisions.at( this.getPosition( ui.value ) - 1 ); else attributes.from = undefined; } movedRevision = this.model.revisions.at( this.getPosition( ui.value ) ); // If we are scrubbing, a scrub to a revision is considered a hover if ( this.model.get('scrubbing') ) attributes.hoveredRevision = movedRevision; this.model.set( attributes ); }, stop: function( event, ui ) { $( window ).off('mousemove.wp.revisions'); this.model.updateSliderSettings(); // To snap us back to a tick mark this.model.set({ scrubbing: false }); } }); // The diff view. // This is the view for the current active diff. revisions.view.Diff = wp.Backbone.View.extend({ className: 'revisions-diff', template: wp.template('revisions-diff'), // Generate the options to be passed to the template. prepare: function() { return _.extend({ fields: this.model.fields.toJSON() }, this.options ); } }); // The revisions router // takes URLs with #hash fragments and routes them revisions.Router = Backbone.Router.extend({ initialize: function( options ) { this.model = options.model; this.routes = _.object([ [ this.baseUrl( '?from=:from&to=:to' ), 'handleRoute' ], [ this.baseUrl( '?from=:from&to=:to' ), 'handleRoute' ] ]); // Maintain state and history when navigating this.listenTo( this.model, 'update:diff', _.debounce( this.updateUrl, 250 ) ); this.listenTo( this.model, 'change:compareTwoMode', this.updateUrl ); }, baseUrl: function( url ) { return this.model.get('baseUrl') + url; }, updateUrl: function() { var from = this.model.has('from') ? this.model.get('from').id : 0; var to = this.model.get('to').id; if ( this.model.get('compareTwoMode' ) ) this.navigate( this.baseUrl( '?from=' + from + '&to=' + to ) ); else this.navigate( this.baseUrl( '?revision=' + to ) ); }, handleRoute: function( a, b ) { var from, to, compareTwo = _.isUndefined( b ); if ( ! compareTwo ) { b = this.model.revisions.get( a ); a = this.model.revisions.prev( b ); b = b ? b.id : 0; a = a ? a.id : 0; } this.model.set({ from: this.model.revisions.get( parseInt( a, 10 ) ), to: this.model.revisions.get( parseInt( a, 10 ) ), compareTwoMode: compareTwo }); } }); // Initialize the revisions UI. revisions.init = function() { revisions.view.frame = new revisions.view.Frame({ model: new revisions.model.FrameState({}, { revisions: new revisions.model.Revisions( revisions.settings.revisionData ) }) }).render(); }; $( revisions.init ); }(jQuery));
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 + ' &times; ' + 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
(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, '&lt;').replace(/>/g, '&gt;'); $(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; }()); // 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(); }); $('.upload-dropzone a.upload').keydown( function( event ) { if ( 13 === event.which ) // enter this.click(); }); $('.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( /&nbsp;|&#160;/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+'-'; $('#the-list').on('click', 'a.editinline', 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($) { $('#the-list').on('click', '.delete-tag', 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 += '&nbsp;&nbsp;&nbsp;'; 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(); } else { // The TinyMCE instance doesn't exist, run the content through "pre_wpautop()" and show the textarea if ( tinyMCEPreInit.mceInit[id] && tinyMCEPreInit.mceInit[id].wpautop ) txtarea_el.value = t.pre_wpautop( txtarea_el.value ); dom.setStyles(txtarea_el, {'display': '', 'visibility': ''}); } 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|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, .plugins').on( 'click', 'a.thickbox', function() { tb_click.call(this); $('#TB_title').css({'background-color':'#222','color':'#cfcfcf'}); $('#TB_ajaxWindowTitle').html('<strong>' + plugininstallL10n.plugin_information + '</strong>&nbsp;' + $(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 $('#the-list').on('click', 'a.editinline', 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() ); $('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(); } ); // Show/hide locks on posts $( document ).on( 'heartbeat-tick.wp-check-locked-posts', function( e, data ) { var locked = data['wp-check-locked-posts'] || {}; $('#the-list tr').each( function(i, el) { var key = el.id, row = $(el), lock_data, avatar; if ( locked.hasOwnProperty( key ) ) { if ( ! row.hasClass('wp-locked') ) { lock_data = locked[key]; row.find('.column-title .locked-text').text( lock_data.text ); row.find('.check-column checkbox').prop('checked', false); if ( lock_data.avatar_src ) { avatar = $('<img class="avatar avatar-18 photo" width="18" height="18" />').attr( 'src', lock_data.avatar_src.replace(/&amp;/g, '&') ); row.find('.column-title .locked-avatar').empty().append( avatar ); } row.addClass('wp-locked'); } } else if ( row.hasClass('wp-locked') ) { // Make room for the CSS animation row.removeClass('wp-locked').delay(1000).find('.locked-info span').empty(); } }); }).on( 'heartbeat-send.wp-check-locked-posts', function( e, data ) { var check = []; $('#the-list tr').each( function(i, el) { if ( el.id ) check.push( el.id ); }); if ( check.length ) data['wp-check-locked-posts'] = check; }); }(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 Browser Thickbox * * Aligns theme browser thickbox. */ var tb_position; jQuery(document).ready( function($) { tb_position = function() { var tbWindow = $('#TB_window'), width = $(window).width(), H = $(window).height(), W = ( 1040 < width ) ? 1040 : 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'}); }; }; $(window).resize(function(){ tb_position(); }); }); /** * 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 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-link_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, autosaveDelayPreview = false, notSaved = true, blockSave = false, fullscreen, autosaveLockRelease = true; jQuery(document).ready( function($) { if ( $('#wp-content-wrap').hasClass('tmce-active') && typeof switchEditors != 'undefined' ) { autosaveLast = wp.autosave.getCompareString({ post_title : $('#title').val() || '', content : switchEditors.pre_wpautop( $('#content').val() ) || '', excerpt : $('#excerpt').val() || '' }); } else { autosaveLast = wp.autosave.getCompareString(); } 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 editor = typeof(tinymce) != 'undefined' ? tinymce.activeEditor : false, compareString; if ( editor && ! editor.isHidden() ) { if ( editor.isDirty() ) return autosaveL10n.saveAlert; } else { if ( fullscreen && fullscreen.settings.visible ) { compareString = wp.autosave.getCompareString({ post_title: $('#wp-fullscreen-title').val() || '', content: $('#wp_mce_fullscreen').val() || '', excerpt: $('#excerpt').val() || '' }); } else { compareString = wp.autosave.getCompareString(); } if ( compareString != 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 */ var ua = navigator.userAgent.toLowerCase(); if ( ua.indexOf('safari') != -1 && ua.indexOf('chrome') == -1 ) { $('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(); }); } // When connection is lost, keep user from submitting changes. $(document).on('heartbeat-connection-lost.autosave', function( e, error ) { if ( 'timeout' === error ) { var notice = $('#lost-connection-notice'); if ( ! wp.autosave.local.hasStorage ) { notice.find('.hide-if-no-sessionstorage').hide(); } notice.show(); autosave_disable_buttons(); } }).on('heartbeat-connection-restored.autosave', function() { $('#lost-connection-notice').hide(); autosave_enable_buttons(); }); }); function autosave_parse_response( response ) { var res = wpAjax.parseAjaxResponse(response, 'autosave'), post_id, sup; if ( res && res.responses && res.responses.length ) { if ( res.responses[0].supplemental ) { sup = res.responses[0].supplemental; jQuery.each( sup, function( selector, value ) { if ( selector.match(/^replace-/) ) jQuery( '#' + selector.replace('replace-', '') ).val( value ); }); } // if no errors: add slug UI and update autosave-message if ( !res.errors ) { if ( post_id = parseInt( res.responses[0].id, 10 ) ) autosave_update_slug( post_id ); if ( res.responses[0].data ) // update autosave message jQuery('.autosave-message').text( res.responses[0].data ); } } 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), post_id; if ( res && res.responses.length && !res.errors ) { // An ID is sent only for real auto-saves, not for autosave=0 "keepalive" saves post_id = parseInt( res.responses[0].id, 10 ); if ( post_id ) { 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' ) { var box = jQuery('#edit-slug-box'); box.html(data); if (box.hasClass('hidden')) { box.fadeIn('fast', function () { box.removeClass('hidden'); }); } makeSlugeditClickable(); } } ); } } function autosave_loading() { jQuery('.autosave-message').html(autosaveL10n.savingText); } function autosave_enable_buttons() { jQuery(document).trigger('autosave-enable-buttons'); if ( ! wp.heartbeat || ! wp.heartbeat.hasConnectionError() ) { // delay that a bit to avoid some rare collisions while the DOM is being updated. setTimeout(function(){ var parent = jQuery('#submitpost'); parent.find(':button, :submit').removeAttr('disabled'); parent.find('.spinner').hide(); }, 500); } } function autosave_disable_buttons() { jQuery(document).trigger('autosave-disable-buttons'); jQuery('#submitpost').find(':button, :submit').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() { var post_data = wp.autosave.getPostData(), compareString, successCallback; blockSave = true; // post_data.content cannot be retrieved at the moment if ( ! post_data.autosave ) return false; // No autosave while thickbox is open (media buttons) if ( jQuery("#TB_window").css('display') == 'block' ) return false; compareString = wp.autosave.getCompareString( post_data ); // Nothing to save or no change. if ( compareString == autosaveLast ) return false; autosaveLast = compareString; jQuery(document).triggerHandler('wpcountwords', [ post_data["content"] ]); // Disable buttons until we know the save completed. autosave_disable_buttons(); if ( post_data["auto_draft"] == '1' ) { successCallback = autosave_saved_new; // new post } else { successCallback = autosave_saved; // pre-existing post } jQuery.ajax({ data: post_data, beforeSend: autosave_loading, type: "POST", url: ajaxurl, success: successCallback }); return true; } // Autosave in localStorage // set as simple object/mixin for now window.wp = window.wp || {}; wp.autosave = wp.autosave || {}; (function($){ // Returns the data for saving in both localStorage and autosaves to the server wp.autosave.getPostData = function() { var ed = typeof tinymce != 'undefined' ? tinymce.activeEditor : null, post_name, parent_id, cats = [], data = { action: 'autosave', autosave: true, post_id: $('#post_ID').val() || 0, autosavenonce: $('#autosavenonce').val() || '', post_type: $('#post_type').val() || '', post_author: $('#post_author').val() || '', excerpt: $('#excerpt').val() || '' }; if ( ed && !ed.isHidden() ) { // Don't run while the tinymce spellcheck is on. It resets all found words. if ( ed.plugins.spellchecker && ed.plugins.spellchecker.active ) { data.autosave = false; return data; } else { if ( 'mce_fullscreen' == ed.id ) tinymce.get('content').setContent(ed.getContent({format : 'raw'}), {format : 'raw'}); tinymce.triggerSave(); } } if ( typeof fullscreen != 'undefined' && fullscreen.settings.visible ) { data['post_title'] = $('#wp-fullscreen-title').val() || ''; data['content'] = $('#wp_mce_fullscreen').val() || ''; } else { data['post_title'] = $('#title').val() || ''; data['content'] = $('#content').val() || ''; } /* // We haven't been saving tags with autosave since 2.8... Start again? $('.the-tags').each( function() { data[this.name] = this.value; }); */ $('input[id^="in-category-"]:checked').each( function() { cats.push(this.value); }); data['catslist'] = cats.join(','); if ( post_name = $('#post_name').val() ) data['post_name'] = post_name; if ( parent_id = $('#parent_id').val() ) data['parent_id'] = parent_id; if ( $('#comment_status').prop('checked') ) data['comment_status'] = 'open'; if ( $('#ping_status').prop('checked') ) data['ping_status'] = 'open'; if ( $('#auto_draft').val() == '1' ) data['auto_draft'] = '1'; return data; }; // Concatenate title, content and excerpt. Used to track changes when auto-saving. wp.autosave.getCompareString = function( post_data ) { if ( typeof post_data === 'object' ) { return ( post_data.post_title || '' ) + '::' + ( post_data.content || '' ) + '::' + ( post_data.excerpt || '' ); } return ( $('#title').val() || '' ) + '::' + ( $('#content').val() || '' ) + '::' + ( $('#excerpt').val() || '' ); }; wp.autosave.local = { lastSavedData: '', blog_id: 0, hasStorage: false, // Check if the browser supports sessionStorage and it's not disabled checkStorage: function() { var test = Math.random(), result = false; try { sessionStorage.setItem('wp-test', test); result = sessionStorage.getItem('wp-test') == test; sessionStorage.removeItem('wp-test'); } catch(e) {} this.hasStorage = result; return result; }, /** * Initialize the local storage * * @return mixed False if no sessionStorage in the browser or an Object containing all post_data for this blog */ getStorage: function() { var stored_obj = false; // Separate local storage containers for each blog_id if ( this.hasStorage && this.blog_id ) { stored_obj = sessionStorage.getItem( 'wp-autosave-' + this.blog_id ); if ( stored_obj ) stored_obj = JSON.parse( stored_obj ); else stored_obj = {}; } return stored_obj; }, /** * Set the storage for this blog * * Confirms that the data was saved successfully. * * @return bool */ setStorage: function( stored_obj ) { var key; if ( this.hasStorage && this.blog_id ) { key = 'wp-autosave-' + this.blog_id; sessionStorage.setItem( key, JSON.stringify( stored_obj ) ); return sessionStorage.getItem( key ) !== null; } return false; }, /** * Get the saved post data for the current post * * @return mixed False if no storage or no data or the post_data as an Object */ getData: function() { var stored = this.getStorage(), post_id = $('#post_ID').val(); if ( !stored || !post_id ) return false; return stored[ 'post_' + post_id ] || false; }, /** * Set (save or delete) post data in the storage. * * If stored_data evaluates to 'false' the storage key for the current post will be removed * * $param stored_data The post data to store or null/false/empty to delete the key * @return bool */ setData: function( stored_data ) { var stored = this.getStorage(), post_id = $('#post_ID').val(); if ( !stored || !post_id ) return false; if ( stored_data ) stored[ 'post_' + post_id ] = stored_data; else if ( stored.hasOwnProperty( 'post_' + post_id ) ) delete stored[ 'post_' + post_id ]; else return false; return this.setStorage(stored); }, /** * Save post data for the current post * * Runs on a 15 sec. schedule, saves when there are differences in the post title or content. * When the optional data is provided, updates the last saved post data. * * $param data optional Object The post data for saving, minimum 'post_title' and 'content' * @return bool */ save: function( data ) { var result = false, post_data, compareString; if ( ! data ) { post_data = wp.autosave.getPostData(); } else { post_data = this.getData() || {}; $.extend( post_data, data ); post_data.autosave = true; } // Cannot get the post data at the moment if ( ! post_data.autosave ) return false; compareString = wp.autosave.getCompareString( post_data ); // If the content, title and excerpt did not change since the last save, don't save again if ( compareString == this.lastSavedData ) return false; post_data['save_time'] = (new Date()).getTime(); post_data['status'] = $('#post_status').val() || ''; result = this.setData( post_data ); if ( result ) this.lastSavedData = compareString; return result; }, // Initialize and run checkPost() on loading the script (before TinyMCE init) init: function( settings ) { var self = this; // Check if the browser supports sessionStorage and it's not disabled if ( ! this.checkStorage() ) return; // Don't run if the post type supports neither 'editor' (textarea#content) nor 'excerpt'. if ( ! $('#content').length && ! $('#excerpt').length ) return; if ( settings ) $.extend( this, settings ); if ( !this.blog_id ) this.blog_id = typeof window.autosaveL10n != 'undefined' ? window.autosaveL10n.blog_id : 0; $(document).ready( function(){ self.run(); } ); }, // Run on DOM ready run: function() { var self = this; // Check if the local post data is different than the loaded post data. this.checkPost(); // Set the schedule this.schedule = $.schedule({ time: 15 * 1000, func: function() { wp.autosave.local.save(); }, repeat: true, protect: true }); $('form#post').on('submit.autosave-local', function() { var editor = typeof tinymce != 'undefined' && tinymce.get('content'), post_id = $('#post_ID').val() || 0; if ( editor && ! editor.isHidden() ) { // Last onSubmit event in the editor, needs to run after the content has been moved to the textarea. editor.onSubmit.add( function() { wp.autosave.local.save({ post_title: $('#title').val() || '', content: $('#content').val() || '', excerpt: $('#excerpt').val() || '' }); }); } else { self.save({ post_title: $('#title').val() || '', content: $('#content').val() || '', excerpt: $('#excerpt').val() || '' }); } wpCookies.set( 'wp-saving-post-' + post_id, 'check' ); }); }, // Strip whitespace and compare two strings compare: function( str1, str2 ) { function remove( string ) { return string.toString().replace(/[\x20\t\r\n\f]+/g, ''); } return ( remove( str1 || '' ) == remove( str2 || '' ) ); }, /** * Check if the saved data for the current post (if any) is different than the loaded post data on the screen * * Shows a standard message letting the user restore the post data if different. * * @return void */ checkPost: function() { var self = this, post_data = this.getData(), content, post_title, excerpt, notice, post_id = $('#post_ID').val() || 0, cookie = wpCookies.get( 'wp-saving-post-' + post_id ); if ( ! post_data ) return; if ( cookie ) { wpCookies.remove( 'wp-saving-post-' + post_id ); if ( cookie == 'saved' ) { // The post was saved properly, remove old data and bail this.setData( false ); return; } } // There is a newer autosave. Don't show two "restore" notices at the same time. if ( $('#has-newer-autosave').length ) return; content = $('#content').val() || ''; post_title = $('#title').val() || ''; excerpt = $('#excerpt').val() || ''; if ( $('#wp-content-wrap').hasClass('tmce-active') && typeof switchEditors != 'undefined' ) content = switchEditors.pre_wpautop( content ); // cookie == 'check' means the post was not saved properly, always show #local-storage-notice if ( cookie != 'check' && this.compare( content, post_data.content ) && this.compare( post_title, post_data.post_title ) && this.compare( excerpt, post_data.excerpt ) ) { return; } this.restore_post_data = post_data; this.undo_post_data = { content: content, post_title: post_title, excerpt: excerpt }; notice = $('#local-storage-notice'); $('.wrap h2').first().after( notice.addClass('updated').show() ); notice.on( 'click', function(e) { var target = $( e.target ); if ( target.hasClass('restore-backup') ) { self.restorePost( self.restore_post_data ); target.parent().hide(); $(this).find('p.undo-restore').show(); } else if ( target.hasClass('undo-restore-backup') ) { self.restorePost( self.undo_post_data ); target.parent().hide(); $(this).find('p.local-restore').show(); } e.preventDefault(); }); }, // Restore the current title, content and excerpt from post_data. restorePost: function( post_data ) { var editor; if ( post_data ) { // Set the last saved data this.lastSavedData = wp.autosave.getCompareString( post_data ); if ( $('#title').val() != post_data.post_title ) $('#title').focus().val( post_data.post_title || '' ); $('#excerpt').val( post_data.excerpt || '' ); editor = typeof tinymce != 'undefined' && tinymce.get('content'); if ( editor && ! editor.isHidden() && typeof switchEditors != 'undefined' ) { // Make sure there's an undo level in the editor editor.undoManager.add(); editor.setContent( post_data.content ? switchEditors.wpautop( post_data.content ) : '' ); } else { // Make sure the Text editor is selected $('#content-html').click(); $('#content').val( post_data.content ); } return true; } return false; } }; wp.autosave.local.init(); }(jQuery));
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('<div class="media-item">') .attr( 'id', 'media-item-' + fileObj.id ) .addClass('child-of-' + postid) .append('<div class="progress"><div class="percent">0%</div><div class="bar"></div></div>', jQuery('<div class="filename original">').text( ' ' + fileObj.name )) .appendTo( jQuery('#media-items' ) ); // 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
window.wp = window.wp || {}; (function ($) { // Create the WordPress Backbone namespace. wp.Backbone = {}; // wp.Backbone.Subviews // -------------------- // // A subview manager. wp.Backbone.Subviews = function( view, views ) { this.view = view; this._views = _.isArray( views ) ? { '': views } : views || {}; }; wp.Backbone.Subviews.extend = Backbone.Model.extend; _.extend( wp.Backbone.Subviews.prototype, { // ### Fetch all of the subviews // // Returns an array of all subviews. all: function() { return _.flatten( this._views ); }, // ### Get a selector's subviews // // Fetches all subviews that match a given `selector`. // // If no `selector` is provided, it will grab all subviews attached // to the view's root. get: function( selector ) { selector = selector || ''; return this._views[ selector ]; }, // ### Get a selector's first subview // // Fetches the first subview that matches a given `selector`. // // If no `selector` is provided, it will grab the first subview // attached to the view's root. // // Useful when a selector only has one subview at a time. first: function( selector ) { var views = this.get( selector ); return views && views.length ? views[0] : null; }, // ### Register subview(s) // // Registers any number of `views` to a `selector`. // // When no `selector` is provided, the root selector (the empty string) // is used. `views` accepts a `Backbone.View` instance or an array of // `Backbone.View` instances. // // --- // // Accepts an `options` object, which has a significant effect on the // resulting behavior. // // `options.silent` &ndash; *boolean, `false`* // > If `options.silent` is true, no DOM modifications will be made. // // `options.add` &ndash; *boolean, `false`* // > Use `Views.add()` as a shortcut for setting `options.add` to true. // // > By default, the provided `views` will replace // any existing views associated with the selector. If `options.add` // is true, the provided `views` will be added to the existing views. // // `options.at` &ndash; *integer, `undefined`* // > When adding, to insert `views` at a specific index, use // `options.at`. By default, `views` are added to the end of the array. set: function( selector, views, options ) { var existing, next; if ( ! _.isString( selector ) ) { options = views; views = selector; selector = ''; } options = options || {}; views = _.isArray( views ) ? views : [ views ]; existing = this.get( selector ); next = views; if ( existing ) { if ( options.add ) { if ( _.isUndefined( options.at ) ) { next = existing.concat( views ); } else { next = existing; next.splice.apply( next, [ options.at, 0 ].concat( views ) ); } } else { _.each( next, function( view ) { view.__detach = true; }); _.each( existing, function( view ) { if ( view.__detach ) view.$el.detach(); else view.remove(); }); _.each( next, function( view ) { delete view.__detach; }); } } this._views[ selector ] = next; _.each( views, function( subview ) { var constructor = subview.Views || wp.Backbone.Subviews, subviews = subview.views = subview.views || new constructor( subview ); subviews.parent = this.view; subviews.selector = selector; }, this ); if ( ! options.silent ) this._attach( selector, views, _.extend({ ready: this._isReady() }, options ) ); return this; }, // ### Add subview(s) to existing subviews // // An alias to `Views.set()`, which defaults `options.add` to true. // // Adds any number of `views` to a `selector`. // // When no `selector` is provided, the root selector (the empty string) // is used. `views` accepts a `Backbone.View` instance or an array of // `Backbone.View` instances. // // Use `Views.set()` when setting `options.add` to `false`. // // Accepts an `options` object. By default, provided `views` will be // inserted at the end of the array of existing views. To insert // `views` at a specific index, use `options.at`. If `options.silent` // is true, no DOM modifications will be made. // // For more information on the `options` object, see `Views.set()`. add: function( selector, views, options ) { if ( ! _.isString( selector ) ) { options = views; views = selector; selector = ''; } return this.set( selector, views, _.extend({ add: true }, options ) ); }, // ### Stop tracking subviews // // Stops tracking `views` registered to a `selector`. If no `views` are // set, then all of the `selector`'s subviews will be unregistered and // removed. // // Accepts an `options` object. If `options.silent` is set, `remove` // will *not* be triggered on the unregistered views. unset: function( selector, views, options ) { var existing; if ( ! _.isString( selector ) ) { options = views; views = selector; selector = ''; } views = views || []; if ( existing = this.get( selector ) ) { views = _.isArray( views ) ? views : [ views ]; this._views[ selector ] = views.length ? _.difference( existing, views ) : []; } if ( ! options || ! options.silent ) _.invoke( views, 'remove' ); return this; }, // ### Detach all subviews // // Detaches all subviews from the DOM. // // Helps to preserve all subview events when re-rendering the master // view. Used in conjunction with `Views.render()`. detach: function() { $( _.pluck( this.all(), 'el' ) ).detach(); return this; }, // ### Render all subviews // // Renders all subviews. Used in conjunction with `Views.detach()`. render: function() { var options = { ready: this._isReady() }; _.each( this._views, function( views, selector ) { this._attach( selector, views, options ); }, this ); this.rendered = true; return this; }, // ### Remove all subviews // // Triggers the `remove()` method on all subviews. Detaches the master // view from its parent. Resets the internals of the views manager. // // Accepts an `options` object. If `options.silent` is set, `unset` // will *not* be triggered on the master view's parent. remove: function( options ) { if ( ! options || ! options.silent ) { if ( this.parent && this.parent.views ) this.parent.views.unset( this.selector, this.view, { silent: true }); delete this.parent; delete this.selector; } _.invoke( this.all(), 'remove' ); this._views = []; return this; }, // ### Replace a selector's subviews // // By default, sets the `$target` selector's html to the subview `els`. // // Can be overridden in subclasses. replace: function( $target, els ) { $target.html( els ); return this; }, // ### Insert subviews into a selector // // By default, appends the subview `els` to the end of the `$target` // selector. If `options.at` is set, inserts the subview `els` at the // provided index. // // Can be overridden in subclasses. insert: function( $target, els, options ) { var at = options && options.at, $children; if ( _.isNumber( at ) && ($children = $target.children()).length > at ) $children.eq( at ).before( els ); else $target.append( els ); return this; }, // ### Trigger the ready event // // **Only use this method if you know what you're doing.** // For performance reasons, this method does not check if the view is // actually attached to the DOM. It's taking your word for it. // // Fires the ready event on the current view and all attached subviews. ready: function() { this.view.trigger('ready'); // Find all attached subviews, and call ready on them. _.chain( this.all() ).map( function( view ) { return view.views; }).flatten().where({ attached: true }).invoke('ready'); }, // #### Internal. Attaches a series of views to a selector. // // Checks to see if a matching selector exists, renders the views, // performs the proper DOM operation, and then checks if the view is // attached to the document. _attach: function( selector, views, options ) { var $selector = selector ? this.view.$( selector ) : this.view.$el, managers; // Check if we found a location to attach the views. if ( ! $selector.length ) return this; managers = _.chain( views ).pluck('views').flatten().value(); // Render the views if necessary. _.each( managers, function( manager ) { if ( manager.rendered ) return; manager.view.render(); manager.rendered = true; }, this ); // Insert or replace the views. this[ options.add ? 'insert' : 'replace' ]( $selector, _.pluck( views, 'el' ), options ); // Set attached and trigger ready if the current view is already // attached to the DOM. _.each( managers, function( manager ) { manager.attached = true; if ( options.ready ) manager.ready(); }, this ); return this; }, // #### Internal. Checks if the current view is in the DOM. _isReady: function() { var node = this.view.el; while ( node ) { if ( node === document.body ) return true; node = node.parentNode; } return false; } }); // wp.Backbone.View // ---------------- // // The base view class. wp.Backbone.View = Backbone.View.extend({ // The constructor for the `Views` manager. Subviews: wp.Backbone.Subviews, constructor: function() { this.views = new this.Subviews( this, this.views ); this.on( 'ready', this.ready, this ); Backbone.View.apply( this, arguments ); }, remove: function() { var result = Backbone.View.prototype.remove.apply( this, arguments ); // Recursively remove child views. if ( this.views ) this.views.remove(); return result; }, render: function() { var options; if ( this.prepare ) options = this.prepare(); this.views.detach(); if ( this.template ) { options = options || {}; this.trigger( 'prepare', options ); this.$el.html( this.template( options ) ); } this.views.render(); return this; }, prepare: function() { return this.options; }, ready: function() {} }); }(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' }); } 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. inputs.openInNewTab.prop('checked', ( "_blank" == ed.dom.getAttrib( e, 'target' ) ) ); // 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
addComment = { moveForm : function(commId, parentId, respondId, postId) { var t = this, div, comm = t.I(commId), respond = t.I(respondId), cancel = t.I('cancel-comment-reply-link'), parent = t.I('comment_parent'), post = t.I('comment_post_ID'); if ( ! comm || ! respond || ! cancel || ! parent ) return; t.respondId = respondId; postId = postId || false; if ( ! t.I('wp-temp-form-div') ) { div = document.createElement('div'); div.id = 'wp-temp-form-div'; div.style.display = 'none'; respond.parentNode.insertBefore(div, respond); } comm.parentNode.insertBefore(respond, comm.nextSibling); if ( post && postId ) post.value = postId; parent.value = parentId; cancel.style.display = ''; cancel.onclick = function() { var t = addComment, temp = t.I('wp-temp-form-div'), respond = t.I(t.respondId); if ( ! temp || ! respond ) return; t.I('comment_parent').value = '0'; temp.parentNode.insertBefore(respond, temp); temp.parentNode.removeChild(temp); this.style.display = 'none'; this.onclick = null; return false; } try { t.I('comment').focus(); } catch(e) {} return false; }, I : function(e) { return document.getElementById(e); } }
JavaScript
// Interim login dialog (function($){ var wrap, check, next; function show() { var parent = $('#wp-auth-check'), form = $('#wp-auth-check-form'), noframe = wrap.find('.wp-auth-fallback-expired'), frame, loaded = false; if ( form.length ) { // Add unload confirmation to counter (frame-busting) JS redirects $(window).on( 'beforeunload.wp-auth-check', function(e) { e.originalEvent.returnValue = window.authcheckL10n.beforeunload; }); frame = $('<iframe id="wp-auth-check-frame" frameborder="0">').attr( 'title', noframe.text() ); frame.load( function(e) { var height, body; loaded = true; try { body = $(this).contents().find('body'); height = body.height(); } catch(e) { wrap.addClass('fallback'); parent.css( 'max-height', '' ); form.remove(); noframe.focus(); return; } if ( height ) { if ( body && body.hasClass('interim-login-success') ) hide(); else parent.css( 'max-height', height + 40 + 'px' ); } else if ( ! body || ! body.length ) { // Catch "silent" iframe origin exceptions in WebKit after another page is loaded in the iframe wrap.addClass('fallback'); parent.css( 'max-height', '' ); form.remove(); noframe.focus(); } }).attr( 'src', form.data('src') ); $('#wp-auth-check-form').append( frame ); } wrap.removeClass('hidden'); if ( frame ) { frame.focus(); // WebKit doesn't throw an error if the iframe fails to load because of "X-Frame-Options: DENY" header. // Wait for 10 sec. and switch to the fallback text. setTimeout( function() { if ( ! loaded ) { wrap.addClass('fallback'); form.remove(); noframe.focus(); } }, 10000 ); } else { noframe.focus(); } } function hide() { $(window).off( 'beforeunload.wp-auth-check' ); // When on the Edit Post screen, speed up heartbeat after the user logs in to quickly refresh nonces if ( typeof adminpage != 'undefined' && ( adminpage == 'post-php' || adminpage == 'post-new-php' ) && typeof wp != 'undefined' && wp.heartbeat ) { wp.heartbeat.interval( 'fast', 1 ); } wrap.fadeOut( 200, function() { wrap.addClass('hidden').css('display', ''); $('#wp-auth-check-frame').remove(); }); } function schedule() { var interval = parseInt( window.authcheckL10n.interval, 10 ) || 180; // in seconds, default 3 min. next = ( new Date() ).getTime() + ( interval * 1000 ); } $( document ).on( 'heartbeat-tick.wp-auth-check', function( e, data ) { if ( 'wp-auth-check' in data ) { schedule(); if ( ! data['wp-auth-check'] && wrap.hasClass('hidden') ) show(); else if ( data['wp-auth-check'] && ! wrap.hasClass('hidden') ) hide(); } }).on( 'heartbeat-send.wp-auth-check', function( e, data ) { if ( ( new Date() ).getTime() > next ) data['wp-auth-check'] = true; }).ready( function() { schedule(); wrap = $('#wp-auth-check-wrap'); wrap.find('.wp-auth-check-close').on( 'click', function(e) { hide(); }); }); }(jQuery));
JavaScript
// Ensure the global `wp` object exists. window.wp = window.wp || {}; (function($){ var views = {}, instances = {}; // Create the `wp.mce` object if necessary. wp.mce = wp.mce || {}; // wp.mce.view // ----------- // A set of utilities that simplifies adding custom UI within a TinyMCE editor. // At its core, it serves as a series of converters, transforming text to a // custom UI, and back again. wp.mce.view = { // ### defaults defaults: { // The default properties used for objects with the `pattern` key in // `wp.mce.view.add()`. pattern: { view: Backbone.View, text: function( instance ) { return instance.options.original; }, toView: function( content ) { if ( ! this.pattern ) return; this.pattern.lastIndex = 0; var match = this.pattern.exec( content ); if ( ! match ) return; return { index: match.index, content: match[0], options: { original: match[0], results: match } }; } }, // The default properties used for objects with the `shortcode` key in // `wp.mce.view.add()`. shortcode: { view: Backbone.View, text: function( instance ) { return instance.options.shortcode.string(); }, toView: function( content ) { var match = wp.shortcode.next( this.shortcode, content ); if ( ! match ) return; return { index: match.index, content: match.content, options: { shortcode: match.shortcode } }; } } }, // ### add( id, options ) // Registers a new TinyMCE view. // // Accepts a unique `id` and an `options` object. // // `options` accepts the following properties: // // * `pattern` is the regular expression used to scan the content and // detect matching views. // // * `view` is a `Backbone.View` constructor. If a plain object is // provided, it will automatically extend the parent constructor // (usually `Backbone.View`). Views are instantiated when the `pattern` // is successfully matched. The instance's `options` object is provided // with the `original` matched value, the match `results` including // capture groups, and the `viewType`, which is the constructor's `id`. // // * `extend` an existing view by passing in its `id`. The current // view will inherit all properties from the parent view, and if // `view` is set to a plain object, it will extend the parent `view` // constructor. // // * `text` is a method that accepts an instance of the `view` // constructor and transforms it into a text representation. add: function( id, options ) { var parent, remove, base, properties; // Fetch the parent view or the default options. if ( options.extend ) parent = wp.mce.view.get( options.extend ); else if ( options.shortcode ) parent = wp.mce.view.defaults.shortcode; else parent = wp.mce.view.defaults.pattern; // Extend the `options` object with the parent's properties. _.defaults( options, parent ); options.id = id; // Create properties used to enhance the view for use in TinyMCE. properties = { // Ensure the wrapper element and references to the view are // removed. Otherwise, removed views could randomly restore. remove: function() { delete instances[ this.el.id ]; this.$el.parent().remove(); // Trigger the inherited `remove` method. if ( remove ) remove.apply( this, arguments ); return this; } }; // If the `view` provided was an object, use the parent's // `view` constructor as a base. If a `view` constructor // was provided, treat that as the base. if ( _.isFunction( options.view ) ) { base = options.view; } else { base = parent.view; remove = options.view.remove; _.defaults( properties, options.view ); } // If there's a `remove` method on the `base` view that wasn't // created by this method, inherit it. if ( ! remove && ! base._mceview ) remove = base.prototype.remove; // Automatically create the new `Backbone.View` constructor. options.view = base.extend( properties, { // Flag that the new view has been created by `wp.mce.view`. _mceview: true }); views[ id ] = options; }, // ### get( id ) // Returns a TinyMCE view options object. get: function( id ) { return views[ id ]; }, // ### remove( id ) // Unregisters a TinyMCE view. remove: function( id ) { delete views[ id ]; }, // ### toViews( content ) // Scans a `content` string for each view's pattern, replacing any // matches with wrapper elements, and creates a new view instance for // every match. // // To render the views, call `wp.mce.view.render( scope )`. toViews: function( content ) { var pieces = [ { content: content } ], current; _.each( views, function( view, viewType ) { current = pieces.slice(); pieces = []; _.each( current, function( piece ) { var remaining = piece.content, result; // Ignore processed pieces, but retain their location. if ( piece.processed ) { pieces.push( piece ); return; } // Iterate through the string progressively matching views // and slicing the string as we go. while ( remaining && (result = view.toView( remaining )) ) { // Any text before the match becomes an unprocessed piece. if ( result.index ) pieces.push({ content: remaining.substring( 0, result.index ) }); // Add the processed piece for the match. pieces.push({ content: wp.mce.view.toView( viewType, result.options ), processed: true }); // Update the remaining content. remaining = remaining.slice( result.index + result.content.length ); } // There are no additional matches. If any content remains, // add it as an unprocessed piece. if ( remaining ) pieces.push({ content: remaining }); }); }); return _.pluck( pieces, 'content' ).join(''); }, toView: function( viewType, options ) { var view = wp.mce.view.get( viewType ), instance, id; if ( ! view ) return ''; // Create a new view instance. instance = new view.view( _.extend( options || {}, { viewType: viewType }) ); // Use the view's `id` if it already exists. Otherwise, // create a new `id`. id = instance.el.id = instance.el.id || _.uniqueId('__wpmce-'); instances[ id ] = instance; // Create a dummy `$wrapper` property to allow `$wrapper` to be // called in the view's `render` method without a conditional. instance.$wrapper = $(); return wp.html.string({ // If the view is a span, wrap it in a span. tag: 'span' === instance.tagName ? 'span' : 'div', attrs: { 'class': 'wp-view-wrap wp-view-type-' + viewType, 'data-wp-view': id, 'contenteditable': false } }); }, // ### render( scope ) // Renders any view instances inside a DOM node `scope`. // // View instances are detected by the presence of wrapper elements. // To generate wrapper elements, pass your content through // `wp.mce.view.toViews( content )`. render: function( scope ) { $( '.wp-view-wrap', scope ).each( function() { var wrapper = $(this), view = wp.mce.view.instance( this ); if ( ! view ) return; // Link the real wrapper to the view. view.$wrapper = wrapper; // Render the view. view.render(); // Detach the view element to ensure events are not unbound. view.$el.detach(); // Empty the wrapper, attach the view element to the wrapper, // and add an ending marker to the wrapper to help regexes // scan the HTML string. wrapper.empty().append( view.el ).append('<span data-wp-view-end class="wp-view-end"></span>'); }); }, // ### toText( content ) // Scans an HTML `content` string and replaces any view instances with // their respective text representations. toText: function( content ) { return content.replace( /<(?:div|span)[^>]+data-wp-view="([^"]+)"[^>]*>.*?<span[^>]+data-wp-view-end[^>]*><\/span><\/(?:div|span)>/g, function( match, id ) { var instance = instances[ id ], view; if ( instance ) view = wp.mce.view.get( instance.options.viewType ); return instance && view ? view.text( instance ) : ''; }); }, // ### Remove internal TinyMCE attributes. removeInternalAttrs: function( attrs ) { var result = {}; _.each( attrs, function( value, attr ) { if ( -1 === attr.indexOf('data-mce') ) result[ attr ] = value; }); return result; }, // ### Parse an attribute string and removes internal TinyMCE attributes. attrs: function( content ) { return wp.mce.view.removeInternalAttrs( wp.html.attrs( content ) ); }, // ### instance( scope ) // // Accepts a MCE view wrapper `node` (i.e. a node with the // `wp-view-wrap` class). instance: function( node ) { var id = $( node ).data('wp-view'); if ( id ) return instances[ id ]; }, // ### Select a view. // // Accepts a MCE view wrapper `node` (i.e. a node with the // `wp-view-wrap` class). select: function( node ) { var $node = $(node); // Bail if node is already selected. if ( $node.hasClass('selected') ) return; $node.addClass('selected'); $( node.firstChild ).trigger('select'); }, // ### Deselect a view. // // Accepts a MCE view wrapper `node` (i.e. a node with the // `wp-view-wrap` class). deselect: function( node ) { var $node = $(node); // Bail if node is already selected. if ( ! $node.hasClass('selected') ) return; $node.removeClass('selected'); $( node.firstChild ).trigger('deselect'); } }; }(jQuery));
JavaScript
/** * Pointer jQuery widget. */ (function($){ var identifier = 0, zindex = 9999; $.widget("wp.pointer", { options: { pointerClass: 'wp-pointer', pointerWidth: 320, content: function( respond, event, t ) { return $(this).text(); }, buttons: function( event, t ) { var close = ( wpPointerL10n ) ? wpPointerL10n.dismiss : 'Dismiss', button = $('<a class="close" href="#">' + close + '</a>'); return button.bind( 'click.pointer', function(e) { e.preventDefault(); t.element.pointer('close'); }); }, position: 'top', show: function( event, t ) { t.pointer.show(); t.opened(); }, hide: function( event, t ) { t.pointer.hide(); t.closed(); }, document: document }, _create: function() { var positioning, family; this.content = $('<div class="wp-pointer-content"></div>'); this.arrow = $('<div class="wp-pointer-arrow"><div class="wp-pointer-arrow-inner"></div></div>'); family = this.element.parents().add( this.element ); positioning = 'absolute'; if ( family.filter(function(){ return 'fixed' === $(this).css('position'); }).length ) positioning = 'fixed'; this.pointer = $('<div />') .append( this.content ) .append( this.arrow ) .attr('id', 'wp-pointer-' + identifier++) .addClass( this.options.pointerClass ) .css({'position': positioning, 'width': this.options.pointerWidth+'px', 'display': 'none'}) .appendTo( this.options.document.body ); }, _setOption: function( key, value ) { var o = this.options, tip = this.pointer; // Handle document transfer if ( key === "document" && value !== o.document ) { tip.detach().appendTo( value.body ); // Handle class change } else if ( key === "pointerClass" ) { tip.removeClass( o.pointerClass ).addClass( value ); } // Call super method. $.Widget.prototype._setOption.apply( this, arguments ); // Reposition automatically if ( key === "position" ) { this.reposition(); // Update content automatically if pointer is open } else if ( key === "content" && this.active ) { this.update(); } }, destroy: function() { this.pointer.remove(); $.Widget.prototype.destroy.call( this ); }, widget: function() { return this.pointer; }, update: function( event ) { var self = this, o = this.options, dfd = $.Deferred(), content; if ( o.disabled ) return; dfd.done( function( content ) { self._update( event, content ); }) // Either o.content is a string... if ( typeof o.content === 'string' ) { content = o.content; // ...or o.content is a callback. } else { content = o.content.call( this.element[0], dfd.resolve, event, this._handoff() ); } // If content is set, then complete the update. if ( content ) dfd.resolve( content ); return dfd.promise(); }, /** * Update is separated into two functions to allow events to defer * updating the pointer (e.g. fetch content with ajax, etc). */ _update: function( event, content ) { var buttons, o = this.options; if ( ! content ) return; this.pointer.stop(); // Kill any animations on the pointer. this.content.html( content ); buttons = o.buttons.call( this.element[0], event, this._handoff() ); if ( buttons ) { buttons.wrap('<div class="wp-pointer-buttons" />').parent().appendTo( this.content ); } this.reposition(); }, reposition: function() { var position; if ( this.options.disabled ) return; position = this._processPosition( this.options.position ); // Reposition pointer. this.pointer.css({ top: 0, left: 0, zIndex: zindex++ // Increment the z-index so that it shows above other opened pointers. }).show().position($.extend({ of: this.element, collision: 'fit none' }, position )); // the object comes before this.options.position so the user can override position.of. this.repoint(); }, repoint: function() { var o = this.options, edge; if ( o.disabled ) return; edge = ( typeof o.position == 'string' ) ? o.position : o.position.edge; // Remove arrow classes. this.pointer[0].className = this.pointer[0].className.replace( /wp-pointer-[^\s'"]*/, '' ); // Add arrow class. this.pointer.addClass( 'wp-pointer-' + edge ); }, _processPosition: function( position ) { var opposite = { top: 'bottom', bottom: 'top', left: 'right', right: 'left' }, result; // If the position object is a string, it is shorthand for position.edge. if ( typeof position == 'string' ) { result = { edge: position + '' }; } else { result = $.extend( {}, position ); } if ( ! result.edge ) return result; if ( result.edge == 'top' || result.edge == 'bottom' ) { result.align = result.align || 'left'; result.at = result.at || result.align + ' ' + opposite[ result.edge ]; result.my = result.my || result.align + ' ' + result.edge; } else { result.align = result.align || 'top'; result.at = result.at || opposite[ result.edge ] + ' ' + result.align; result.my = result.my || result.edge + ' ' + result.align; } return result; }, open: function( event ) { var self = this, o = this.options; if ( this.active || o.disabled || this.element.is(':hidden') ) return; this.update().done( function() { self._open( event ); }); }, _open: function( event ) { var self = this, o = this.options; if ( this.active || o.disabled || this.element.is(':hidden') ) return; this.active = true; this._trigger( "open", event, this._handoff() ); this._trigger( "show", event, this._handoff({ opened: function() { self._trigger( "opened", event, self._handoff() ); } })); }, close: function( event ) { if ( !this.active || this.options.disabled ) return; var self = this; this.active = false; this._trigger( "close", event, this._handoff() ); this._trigger( "hide", event, this._handoff({ closed: function() { self._trigger( "closed", event, self._handoff() ); } })); }, sendToTop: function( event ) { if ( this.active ) this.pointer.css( 'z-index', zindex++ ); }, toggle: function( event ) { if ( this.pointer.is(':hidden') ) this.open( event ); else this.close( event ); }, _handoff: function( extend ) { return $.extend({ pointer: this.pointer, element: this.element }, extend); } }); })(jQuery);
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
var topWin = window.dialogArguments || opener || parent || top; 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(); // Collapse a single item if ( jQuery('form.type-form #media-items').children().length == 1 && jQuery('.hidden', '#media-items').length > 0 ) { jQuery('.describe-toggle-on').show(); jQuery('.describe-toggle-off').hide(); jQuery('.slidetoggle').slideUp(200).siblings().removeClass('hidden'); } // Create a progress bar containing the filename jQuery('<div class="media-item">') .attr( 'id', 'media-item-' + fileObj.id ) .addClass('child-of-' + post_id) .append('<div class="progress"><div class="bar"></div></div>', jQuery('<div class="filename original"><span class="percent"></span>').text( ' ' + fileObj.name )) .appendTo( jQuery('#media-items' ) ); // Display the progress div jQuery('.progress', '#media-item-' + fileObj.id).show(); // Disable submit and enable cancel jQuery('#insert-gallery').prop('disabled', true); jQuery('#cancel-upload').prop('disabled', false); } function uploadStart(fileObj) { try { if ( typeof topWin.tb_remove != 'undefined' ) topWin.jQuery('#TB_overlay').unbind('click', topWin.tb_remove); } catch(e){} return true; } function uploadProgress(fileObj, bytesDone, bytesTotal) { // Lengthen the progress bar var w = jQuery('#media-items').width() - 2, item = jQuery('#media-item-' + fileObj.id); jQuery('.bar', item).width( w * bytesDone / bytesTotal ); jQuery('.percent', item).html( Math.ceil(bytesDone / bytesTotal * 100) + '%' ); if ( bytesDone == bytesTotal ) jQuery('.bar', item).html('<strong class="crunching">' + swfuploadL10n.crunching + '</strong>'); } function prepareMediaItem(fileObj, serverData) { var f = ( typeof shortform == 'undefined' ) ? 1 : 2, item = jQuery('#media-item-' + fileObj.id); // Move the progress bar to 100% jQuery('.bar', item).remove(); jQuery('.progress', item).hide(); try { if ( typeof topWin.tb_remove != 'undefined' ) topWin.jQuery('#TB_overlay').click(topWin.tb_remove); } catch(e){} // Old style: Append the HTML returned by the server -- thumbnail and form inputs if ( isNaN(serverData) || !serverData ) { item.append(serverData); prepareMediaItemInit(fileObj); } // New style: server data is just the attachment ID, fetch the thumbnail and form html from the server else { 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) ); // Also bind toggle to the links jQuery('a.toggle', item).click(function(){ jQuery(this).siblings('.slidetoggle').slideToggle(350, function(){ var w = jQuery(window).height(), t = jQuery(this).offset().top, h = jQuery(this).height(), b; if ( w && t && h ) { b = t + h; if ( b > w && (h + 48) < w ) window.scrollBy(0, b - w + 13); else if ( b > w ) window.scrollTo(0, t - 36); } }); jQuery(this).siblings('.toggle').andSelf().toggle(); jQuery(this).siblings('a.toggle').focus(); return false; }); // 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 ( 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('a.describe-toggle-on, .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').slideToggle(500).siblings('.toggle').toggle(); } function itemAjaxError(id, html) { var item = jQuery('#media-item-' + id); var filename = jQuery('.filename', item).text(); item.html('<div class="error-div">' + '<a class="dismiss" href="#">' + swfuploadL10n.dismiss + '</a>' + '<strong>' + swfuploadL10n.error_uploading.replace('%s', filename) + '</strong><br />' + html + '</div>'); item.find('a.dismiss').click(function(){jQuery(this).parents('.media-item').slideUp(200, function(){jQuery(this).remove();})}); } 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 ( 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"> ' + swfuploadL10n.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 updateMediaForm() { var one = jQuery('form.type-form #media-items').children(), items = jQuery('#media-items').children(); // Just one file, no need for collapsible part if ( one.length == 1 ) { jQuery('.slidetoggle', one).slideDown(500).siblings().addClass('hidden').filter('.toggle').toggle(); } // 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(); // Only show Gallery button when there are at least two files. if ( items.length > 1 ) jQuery('.insert-gallery').show(); else jQuery('.insert-gallery').hide(); } function uploadSuccess(fileObj, serverData) { // if async-upload returned an error message, place it in the media item div and return if ( serverData.match('media-upload-error') ) { jQuery('#media-item-' + fileObj.id).html(serverData); return; } prepareMediaItem(fileObj, serverData); updateMediaForm(); // Increment the counter. if ( jQuery('#media-item-' + fileObj.id).hasClass('child-of-' + post_id) ) jQuery('#attachments-count').text(1 * jQuery('#attachments-count').text() + 1); } function uploadComplete(fileObj) { // If no more uploads queued, enable the submit button if ( swfu.getStats().files_queued == 0 ) { jQuery('#cancel-upload').prop('disabled', true); jQuery('#insert-gallery').prop('disabled', false); } } // wp-specific error handlers // generic message function wpQueueError(message) { jQuery('#media-upload-error').show().text(message); } // file-specific message function wpFileError(fileObj, message) { var item = jQuery('#media-item-' + fileObj.id); var filename = jQuery('.filename', item).text(); item.html('<div class="error-div">' + '<a class="dismiss" href="#">' + swfuploadL10n.dismiss + '</a>' + '<strong>' + swfuploadL10n.error_uploading.replace('%s', filename) + '</strong><br />' + message + '</div>'); item.find('a.dismiss').click(function(){jQuery(this).parents('.media-item').slideUp(200, function(){jQuery(this).remove();})}); } function fileQueueError(fileObj, error_code, message) { // Handle this error separately because we don't want to create a FileProgress element for it. if ( error_code == SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED ) { wpQueueError(swfuploadL10n.queue_limit_exceeded); } else if ( error_code == SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT ) { fileQueued(fileObj); wpFileError(fileObj, swfuploadL10n.file_exceeds_size_limit); } else if ( error_code == SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE ) { fileQueued(fileObj); wpFileError(fileObj, swfuploadL10n.zero_byte_file); } else if ( error_code == SWFUpload.QUEUE_ERROR.INVALID_FILETYPE ) { fileQueued(fileObj); wpFileError(fileObj, swfuploadL10n.invalid_filetype); } else { wpQueueError(swfuploadL10n.default_error); } } function fileDialogComplete(num_files_queued) { try { if (num_files_queued > 0) { this.startUpload(); } } catch (ex) { this.debug(ex); } } function switchUploader(s) { var f = document.getElementById(swfu.customSettings.swfupload_element_id), h = document.getElementById(swfu.customSettings.degraded_element_id); if ( s ) { f.style.display = 'block'; h.style.display = 'none'; } else { f.style.display = 'none'; h.style.display = 'block'; } } function swfuploadPreLoad() { if ( !uploaderMode ) { switchUploader(1); } else { switchUploader(0); } } function swfuploadLoadFailed() { switchUploader(0); jQuery('.upload-html-bypass').hide(); } function uploadError(fileObj, errorCode, message) { switch (errorCode) { case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL: wpFileError(fileObj, swfuploadL10n.missing_upload_url); break; case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED: wpFileError(fileObj, swfuploadL10n.upload_limit_exceeded); break; case SWFUpload.UPLOAD_ERROR.HTTP_ERROR: wpQueueError(swfuploadL10n.http_error); break; case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED: wpQueueError(swfuploadL10n.upload_failed); break; case SWFUpload.UPLOAD_ERROR.IO_ERROR: wpQueueError(swfuploadL10n.io_error); break; case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR: wpQueueError(swfuploadL10n.security_error); break; case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED: case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED: jQuery('#media-item-' + fileObj.id).remove(); break; default: wpFileError(fileObj, swfuploadL10n.default_error); } } function cancelUpload() { swfu.cancelQueue(); } // remember the last used image size, alignment and url jQuery(document).ready(function($){ $('input[type="radio"]', '#media-items').live('click', function(){ var tr = $(this).closest('tr'); if ( $(tr).hasClass('align') ) setUserSetting('align', $(this).val()); else if ( $(tr).hasClass('image-size') ) setUserSetting('imgsize', $(this).val()); }); $('button.button', '#media-items').live('click', function(){ var c = this.className || ''; c = c.match(/url([^ '"]+)/); if ( c && c[1] ) { setUserSetting('urlbutton', c[1]); $(this).siblings('.urlfield').val( $(this).attr('title') ); } }); });
JavaScript
/* SWFUpload.SWFObject Plugin Summary: This plugin uses SWFObject to embed SWFUpload dynamically in the page. SWFObject provides accurate Flash Player detection and DOM Ready loading. This plugin replaces the Graceful Degradation plugin. Features: * swfupload_load_failed_hander event * swfupload_pre_load_handler event * minimum_flash_version setting (default: "9.0.28") * SWFUpload.onload event for early loading Usage: Provide handlers and settings as needed. When using the SWFUpload.SWFObject plugin you should initialize SWFUploading in SWFUpload.onload rather than in window.onload. When initialized this way SWFUpload can load earlier preventing the UI flicker that was seen using the Graceful Degradation plugin. <script type="text/javascript"> var swfu; SWFUpload.onload = function () { swfu = new SWFUpload({ minimum_flash_version: "9.0.28", swfupload_pre_load_handler: swfuploadPreLoad, swfupload_load_failed_handler: swfuploadLoadFailed }); }; </script> Notes: You must provide set minimum_flash_version setting to "8" if you are using SWFUpload for Flash Player 8. The swfuploadLoadFailed event is only fired if the minimum version of Flash Player is not met. Other issues such as missing SWF files, browser bugs or corrupt Flash Player installations will not trigger this event. The swfuploadPreLoad event is fired as soon as the minimum version of Flash Player is found. It does not wait for SWFUpload to load and can be used to prepare the SWFUploadUI and hide alternate content. swfobject's onDomReady event is cross-browser safe but will default to the window.onload event when DOMReady is not supported by the browser. Early DOM Loading is supported in major modern browsers but cannot be guaranteed for every browser ever made. */ // SWFObject v2.1 must be loaded var SWFUpload; if (typeof(SWFUpload) === "function") { SWFUpload.onload = function () {}; swfobject.addDomLoadEvent(function () { if (typeof(SWFUpload.onload) === "function") { setTimeout(function(){SWFUpload.onload.call(window);}, 200); } }); SWFUpload.prototype.initSettings = (function (oldInitSettings) { return function () { if (typeof(oldInitSettings) === "function") { oldInitSettings.call(this); } this.ensureDefault = function (settingName, defaultValue) { this.settings[settingName] = (this.settings[settingName] == undefined) ? defaultValue : this.settings[settingName]; }; this.ensureDefault("minimum_flash_version", "9.0.28"); this.ensureDefault("swfupload_pre_load_handler", null); this.ensureDefault("swfupload_load_failed_handler", null); delete this.ensureDefault; }; })(SWFUpload.prototype.initSettings); SWFUpload.prototype.loadFlash = function (oldLoadFlash) { return function () { var hasFlash = swfobject.hasFlashPlayerVersion(this.settings.minimum_flash_version); if (hasFlash) { this.queueEvent("swfupload_pre_load_handler"); if (typeof(oldLoadFlash) === "function") { oldLoadFlash.call(this); } } else { this.queueEvent("swfupload_load_failed_handler"); } }; }(SWFUpload.prototype.loadFlash); SWFUpload.prototype.displayDebugInfo = function (oldDisplayDebugInfo) { return function () { if (typeof(oldDisplayDebugInfo) === "function") { oldDisplayDebugInfo.call(this); } this.debug( [ "SWFUpload.SWFObject Plugin settings:", "\n", "\t", "minimum_flash_version: ", this.settings.minimum_flash_version, "\n", "\t", "swfupload_pre_load_handler assigned: ", (typeof(this.settings.swfupload_pre_load_handler) === "function").toString(), "\n", "\t", "swfupload_load_failed_handler assigned: ", (typeof(this.settings.swfupload_load_failed_handler) === "function").toString(), "\n", ].join("") ); }; }(SWFUpload.prototype.displayDebugInfo); }
JavaScript
/* Cookie Plug-in This plug in automatically gets all the cookies for this site and adds them to the post_params. Cookies are loaded only on initialization. The refreshCookies function can be called to update the post_params. The cookies will override any other post params with the same name. */ var SWFUpload; if (typeof(SWFUpload) === "function") { SWFUpload.prototype.initSettings = function (oldInitSettings) { return function () { if (typeof(oldInitSettings) === "function") { oldInitSettings.call(this); } this.refreshCookies(false); // The false parameter must be sent since SWFUpload has not initialzed at this point }; }(SWFUpload.prototype.initSettings); // refreshes the post_params and updates SWFUpload. The sendToFlash parameters is optional and defaults to True SWFUpload.prototype.refreshCookies = function (sendToFlash) { if (sendToFlash === undefined) { sendToFlash = true; } sendToFlash = !!sendToFlash; // Get the post_params object var postParams = this.settings.post_params; // Get the cookies var i, cookieArray = document.cookie.split(';'), caLength = cookieArray.length, c, eqIndex, name, value; for (i = 0; i < caLength; i++) { c = cookieArray[i]; // Left Trim spaces while (c.charAt(0) === " ") { c = c.substring(1, c.length); } eqIndex = c.indexOf("="); if (eqIndex > 0) { name = c.substring(0, eqIndex); value = c.substring(eqIndex + 1); postParams[name] = value; } } if (sendToFlash) { this.setPostParams(postParams); } }; }
JavaScript
/* Queue Plug-in Features: *Adds a cancelQueue() method for cancelling the entire queue. *All queued files are uploaded when startUpload() is called. *If false is returned from uploadComplete then the queue upload is stopped. If false is not returned (strict comparison) then the queue upload is continued. *Adds a QueueComplete event that is fired when all the queued files have finished uploading. Set the event handler with the queue_complete_handler setting. */ var SWFUpload; if (typeof(SWFUpload) === "function") { SWFUpload.queue = {}; SWFUpload.prototype.initSettings = (function (oldInitSettings) { return function () { if (typeof(oldInitSettings) === "function") { oldInitSettings.call(this); } this.queueSettings = {}; this.queueSettings.queue_cancelled_flag = false; this.queueSettings.queue_upload_count = 0; this.queueSettings.user_upload_complete_handler = this.settings.upload_complete_handler; this.queueSettings.user_upload_start_handler = this.settings.upload_start_handler; this.settings.upload_complete_handler = SWFUpload.queue.uploadCompleteHandler; this.settings.upload_start_handler = SWFUpload.queue.uploadStartHandler; this.settings.queue_complete_handler = this.settings.queue_complete_handler || null; }; })(SWFUpload.prototype.initSettings); SWFUpload.prototype.startUpload = function (fileID) { this.queueSettings.queue_cancelled_flag = false; this.callFlash("StartUpload", [fileID]); }; SWFUpload.prototype.cancelQueue = function () { this.queueSettings.queue_cancelled_flag = true; this.stopUpload(); var stats = this.getStats(); while (stats.files_queued > 0) { this.cancelUpload(); stats = this.getStats(); } }; SWFUpload.queue.uploadStartHandler = function (file) { var returnValue; if (typeof(this.queueSettings.user_upload_start_handler) === "function") { returnValue = this.queueSettings.user_upload_start_handler.call(this, file); } // To prevent upload a real "FALSE" value must be returned, otherwise default to a real "TRUE" value. returnValue = (returnValue === false) ? false : true; this.queueSettings.queue_cancelled_flag = !returnValue; return returnValue; }; SWFUpload.queue.uploadCompleteHandler = function (file) { var user_upload_complete_handler = this.queueSettings.user_upload_complete_handler; var continueUpload; if (file.filestatus === SWFUpload.FILE_STATUS.COMPLETE) { this.queueSettings.queue_upload_count++; } if (typeof(user_upload_complete_handler) === "function") { continueUpload = (user_upload_complete_handler.call(this, file) === false) ? false : true; } else if (file.filestatus === SWFUpload.FILE_STATUS.QUEUED) { // If the file was stopped and re-queued don't restart the upload continueUpload = false; } else { continueUpload = true; } if (continueUpload) { var stats = this.getStats(); if (stats.files_queued > 0 && this.queueSettings.queue_cancelled_flag === false) { this.startUpload(); } else if (this.queueSettings.queue_cancelled_flag === false) { this.queueEvent("queue_complete_handler", [this.queueSettings.queue_upload_count]); this.queueSettings.queue_upload_count = 0; } else { this.queueSettings.queue_cancelled_flag = false; this.queueSettings.queue_upload_count = 0; } } }; }
JavaScript
/* Speed Plug-in Features: *Adds several properties to the 'file' object indicated upload speed, time left, upload time, etc. - currentSpeed -- String indicating the upload speed, bytes per second - averageSpeed -- Overall average upload speed, bytes per second - movingAverageSpeed -- Speed over averaged over the last several measurements, bytes per second - timeRemaining -- Estimated remaining upload time in seconds - timeElapsed -- Number of seconds passed for this upload - percentUploaded -- Percentage of the file uploaded (0 to 100) - sizeUploaded -- Formatted size uploaded so far, bytes *Adds setting 'moving_average_history_size' for defining the window size used to calculate the moving average speed. *Adds several Formatting functions for formatting that values provided on the file object. - SWFUpload.speed.formatBPS(bps) -- outputs string formatted in the best units (Gbps, Mbps, Kbps, bps) - SWFUpload.speed.formatTime(seconds) -- outputs string formatted in the best units (x Hr y M z S) - SWFUpload.speed.formatSize(bytes) -- outputs string formatted in the best units (w GB x MB y KB z B ) - SWFUpload.speed.formatPercent(percent) -- outputs string formatted with a percent sign (x.xx %) - SWFUpload.speed.formatUnits(baseNumber, divisionArray, unitLabelArray, fractionalBoolean) - Formats a number using the division array to determine how to apply the labels in the Label Array - factionalBoolean indicates whether the number should be returned as a single fractional number with a unit (speed) or as several numbers labeled with units (time) */ var SWFUpload; if (typeof(SWFUpload) === "function") { SWFUpload.speed = {}; SWFUpload.prototype.initSettings = (function (oldInitSettings) { return function () { if (typeof(oldInitSettings) === "function") { oldInitSettings.call(this); } this.ensureDefault = function (settingName, defaultValue) { this.settings[settingName] = (this.settings[settingName] == undefined) ? defaultValue : this.settings[settingName]; }; // List used to keep the speed stats for the files we are tracking this.fileSpeedStats = {}; this.speedSettings = {}; this.ensureDefault("moving_average_history_size", "10"); this.speedSettings.user_file_queued_handler = this.settings.file_queued_handler; this.speedSettings.user_file_queue_error_handler = this.settings.file_queue_error_handler; this.speedSettings.user_upload_start_handler = this.settings.upload_start_handler; this.speedSettings.user_upload_error_handler = this.settings.upload_error_handler; this.speedSettings.user_upload_progress_handler = this.settings.upload_progress_handler; this.speedSettings.user_upload_success_handler = this.settings.upload_success_handler; this.speedSettings.user_upload_complete_handler = this.settings.upload_complete_handler; this.settings.file_queued_handler = SWFUpload.speed.fileQueuedHandler; this.settings.file_queue_error_handler = SWFUpload.speed.fileQueueErrorHandler; this.settings.upload_start_handler = SWFUpload.speed.uploadStartHandler; this.settings.upload_error_handler = SWFUpload.speed.uploadErrorHandler; this.settings.upload_progress_handler = SWFUpload.speed.uploadProgressHandler; this.settings.upload_success_handler = SWFUpload.speed.uploadSuccessHandler; this.settings.upload_complete_handler = SWFUpload.speed.uploadCompleteHandler; delete this.ensureDefault; }; })(SWFUpload.prototype.initSettings); SWFUpload.speed.fileQueuedHandler = function (file) { if (typeof this.speedSettings.user_file_queued_handler === "function") { file = SWFUpload.speed.extendFile(file); return this.speedSettings.user_file_queued_handler.call(this, file); } }; SWFUpload.speed.fileQueueErrorHandler = function (file, errorCode, message) { if (typeof this.speedSettings.user_file_queue_error_handler === "function") { file = SWFUpload.speed.extendFile(file); return this.speedSettings.user_file_queue_error_handler.call(this, file, errorCode, message); } }; SWFUpload.speed.uploadStartHandler = function (file) { if (typeof this.speedSettings.user_upload_start_handler === "function") { file = SWFUpload.speed.extendFile(file, this.fileSpeedStats); return this.speedSettings.user_upload_start_handler.call(this, file); } }; SWFUpload.speed.uploadErrorHandler = function (file, errorCode, message) { file = SWFUpload.speed.extendFile(file, this.fileSpeedStats); SWFUpload.speed.removeTracking(file, this.fileSpeedStats); if (typeof this.speedSettings.user_upload_error_handler === "function") { return this.speedSettings.user_upload_error_handler.call(this, file, errorCode, message); } }; SWFUpload.speed.uploadProgressHandler = function (file, bytesComplete, bytesTotal) { this.updateTracking(file, bytesComplete); file = SWFUpload.speed.extendFile(file, this.fileSpeedStats); if (typeof this.speedSettings.user_upload_progress_handler === "function") { return this.speedSettings.user_upload_progress_handler.call(this, file, bytesComplete, bytesTotal); } }; SWFUpload.speed.uploadSuccessHandler = function (file, serverData) { if (typeof this.speedSettings.user_upload_success_handler === "function") { file = SWFUpload.speed.extendFile(file, this.fileSpeedStats); return this.speedSettings.user_upload_success_handler.call(this, file, serverData); } }; SWFUpload.speed.uploadCompleteHandler = function (file) { file = SWFUpload.speed.extendFile(file, this.fileSpeedStats); SWFUpload.speed.removeTracking(file, this.fileSpeedStats); if (typeof this.speedSettings.user_upload_complete_handler === "function") { return this.speedSettings.user_upload_complete_handler.call(this, file); } }; // Private: extends the file object with the speed plugin values SWFUpload.speed.extendFile = function (file, trackingList) { var tracking; if (trackingList) { tracking = trackingList[file.id]; } if (tracking) { file.currentSpeed = tracking.currentSpeed; file.averageSpeed = tracking.averageSpeed; file.movingAverageSpeed = tracking.movingAverageSpeed; file.timeRemaining = tracking.timeRemaining; file.timeElapsed = tracking.timeElapsed; file.percentUploaded = tracking.percentUploaded; file.sizeUploaded = tracking.bytesUploaded; } else { file.currentSpeed = 0; file.averageSpeed = 0; file.movingAverageSpeed = 0; file.timeRemaining = 0; file.timeElapsed = 0; file.percentUploaded = 0; file.sizeUploaded = 0; } return file; }; // Private: Updates the speed tracking object, or creates it if necessary SWFUpload.prototype.updateTracking = function (file, bytesUploaded) { var tracking = this.fileSpeedStats[file.id]; if (!tracking) { this.fileSpeedStats[file.id] = tracking = {}; } // Sanity check inputs bytesUploaded = bytesUploaded || tracking.bytesUploaded || 0; if (bytesUploaded < 0) { bytesUploaded = 0; } if (bytesUploaded > file.size) { bytesUploaded = file.size; } var tickTime = (new Date()).getTime(); if (!tracking.startTime) { tracking.startTime = (new Date()).getTime(); tracking.lastTime = tracking.startTime; tracking.currentSpeed = 0; tracking.averageSpeed = 0; tracking.movingAverageSpeed = 0; tracking.movingAverageHistory = []; tracking.timeRemaining = 0; tracking.timeElapsed = 0; tracking.percentUploaded = bytesUploaded / file.size; tracking.bytesUploaded = bytesUploaded; } else if (tracking.startTime > tickTime) { this.debug("When backwards in time"); } else { // Get time and deltas var now = (new Date()).getTime(); var lastTime = tracking.lastTime; var deltaTime = now - lastTime; var deltaBytes = bytesUploaded - tracking.bytesUploaded; if (deltaBytes === 0 || deltaTime === 0) { return tracking; } // Update tracking object tracking.lastTime = now; tracking.bytesUploaded = bytesUploaded; // Calculate speeds tracking.currentSpeed = (deltaBytes * 8 ) / (deltaTime / 1000); tracking.averageSpeed = (tracking.bytesUploaded * 8) / ((now - tracking.startTime) / 1000); // Calculate moving average tracking.movingAverageHistory.push(tracking.currentSpeed); if (tracking.movingAverageHistory.length > this.settings.moving_average_history_size) { tracking.movingAverageHistory.shift(); } tracking.movingAverageSpeed = SWFUpload.speed.calculateMovingAverage(tracking.movingAverageHistory); // Update times tracking.timeRemaining = (file.size - tracking.bytesUploaded) * 8 / tracking.movingAverageSpeed; tracking.timeElapsed = (now - tracking.startTime) / 1000; // Update percent tracking.percentUploaded = (tracking.bytesUploaded / file.size * 100); } return tracking; }; SWFUpload.speed.removeTracking = function (file, trackingList) { try { trackingList[file.id] = null; delete trackingList[file.id]; } catch (ex) { } }; SWFUpload.speed.formatUnits = function (baseNumber, unitDivisors, unitLabels, singleFractional) { var i, unit, unitDivisor, unitLabel; if (baseNumber === 0) { return "0 " + unitLabels[unitLabels.length - 1]; } if (singleFractional) { unit = baseNumber; unitLabel = unitLabels.length >= unitDivisors.length ? unitLabels[unitDivisors.length - 1] : ""; for (i = 0; i < unitDivisors.length; i++) { if (baseNumber >= unitDivisors[i]) { unit = (baseNumber / unitDivisors[i]).toFixed(2); unitLabel = unitLabels.length >= i ? " " + unitLabels[i] : ""; break; } } return unit + unitLabel; } else { var formattedStrings = []; var remainder = baseNumber; for (i = 0; i < unitDivisors.length; i++) { unitDivisor = unitDivisors[i]; unitLabel = unitLabels.length > i ? " " + unitLabels[i] : ""; unit = remainder / unitDivisor; if (i < unitDivisors.length -1) { unit = Math.floor(unit); } else { unit = unit.toFixed(2); } if (unit > 0) { remainder = remainder % unitDivisor; formattedStrings.push(unit + unitLabel); } } return formattedStrings.join(" "); } }; SWFUpload.speed.formatBPS = function (baseNumber) { var bpsUnits = [1073741824, 1048576, 1024, 1], bpsUnitLabels = ["Gbps", "Mbps", "Kbps", "bps"]; return SWFUpload.speed.formatUnits(baseNumber, bpsUnits, bpsUnitLabels, true); }; SWFUpload.speed.formatTime = function (baseNumber) { var timeUnits = [86400, 3600, 60, 1], timeUnitLabels = ["d", "h", "m", "s"]; return SWFUpload.speed.formatUnits(baseNumber, timeUnits, timeUnitLabels, false); }; SWFUpload.speed.formatBytes = function (baseNumber) { var sizeUnits = [1073741824, 1048576, 1024, 1], sizeUnitLabels = ["GB", "MB", "KB", "bytes"]; return SWFUpload.speed.formatUnits(baseNumber, sizeUnits, sizeUnitLabels, true); }; SWFUpload.speed.formatPercent = function (baseNumber) { return baseNumber.toFixed(2) + " %"; }; SWFUpload.speed.calculateMovingAverage = function (history) { var vals = [], size, sum = 0.0, mean = 0.0, varianceTemp = 0.0, variance = 0.0, standardDev = 0.0; var i; var mSum = 0, mCount = 0; size = history.length; // Check for sufficient data if (size >= 8) { // Clone the array and Calculate sum of the values for (i = 0; i < size; i++) { vals[i] = history[i]; sum += vals[i]; } mean = sum / size; // Calculate variance for the set for (i = 0; i < size; i++) { varianceTemp += Math.pow((vals[i] - mean), 2); } variance = varianceTemp / size; standardDev = Math.sqrt(variance); //Standardize the Data for (i = 0; i < size; i++) { vals[i] = (vals[i] - mean) / standardDev; } // Calculate the average excluding outliers var deviationRange = 2.0; for (i = 0; i < size; i++) { if (vals[i] <= deviationRange && vals[i] >= -deviationRange) { mCount++; mSum += history[i]; } } } else { // Calculate the average (not enough data points to remove outliers) mCount = size; for (i = 0; i < size; i++) { mSum += history[i]; } } return mSum / mCount; }; }
JavaScript
/*! * hoverIntent r7 // 2013.03.11 // jQuery 1.9.1+ * http://cherne.net/brian/resources/jquery.hoverIntent.html * * You may use hoverIntent under the terms of the MIT license. Basically that * means you are free to use hoverIntent as long as this header is left intact. * Copyright 2007, 2013 Brian Cherne */ /* hoverIntent is similar to jQuery's built-in "hover" method except that * instead of firing the handlerIn function immediately, hoverIntent checks * to see if the user's mouse has slowed down (beneath the sensitivity * threshold) before firing the event. The handlerOut function is only * called after a matching handlerIn. * * // basic usage ... just like .hover() * .hoverIntent( handlerIn, handlerOut ) * .hoverIntent( handlerInOut ) * * // basic usage ... with event delegation! * .hoverIntent( handlerIn, handlerOut, selector ) * .hoverIntent( handlerInOut, selector ) * * // using a basic configuration object * .hoverIntent( config ) * * @param handlerIn function OR configuration object * @param handlerOut function OR selector for delegation OR undefined * @param selector selector OR undefined * @author Brian Cherne <brian(at)cherne(dot)net> */ (function($) { $.fn.hoverIntent = function(handlerIn,handlerOut,selector) { // default configuration values var cfg = { interval: 100, sensitivity: 7, timeout: 0 }; if ( typeof handlerIn === "object" ) { cfg = $.extend(cfg, handlerIn ); } else if ($.isFunction(handlerOut)) { cfg = $.extend(cfg, { over: handlerIn, out: handlerOut, selector: selector } ); } else { cfg = $.extend(cfg, { over: handlerIn, out: handlerIn, selector: handlerOut } ); } // instantiate variables // cX, cY = current X and Y position of mouse, updated by mousemove event // pX, pY = previous X and Y position of mouse, set by mouseover and polling interval var cX, cY, pX, pY; // A private function for getting mouse position var track = function(ev) { cX = ev.pageX; cY = ev.pageY; }; // A private function for comparing current and previous mouse position var compare = function(ev,ob) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); // compare mouse positions to see if they've crossed the threshold if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) { $(ob).off("mousemove.hoverIntent",track); // set hoverIntent state to true (so mouseOut can be called) ob.hoverIntent_s = 1; return cfg.over.apply(ob,[ev]); } else { // set previous coordinates for next time pX = cX; pY = cY; // use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs) ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval ); } }; // A private function for delaying the mouseOut function var delay = function(ev,ob) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); ob.hoverIntent_s = 0; return cfg.out.apply(ob,[ev]); }; // A private function for handling mouse 'hovering' var handleHover = function(e) { // copy objects to be passed into t (required for event object to be passed in IE) var ev = jQuery.extend({},e); var ob = this; // cancel hoverIntent timer if it exists if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); } // if e.type == "mouseenter" if (e.type == "mouseenter") { // set "previous" X and Y position based on initial entry point pX = ev.pageX; pY = ev.pageY; // update "current" X and Y position based on mousemove $(ob).on("mousemove.hoverIntent",track); // start polling interval (self-calling timeout) to compare mouse coordinates over time if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );} // else e.type == "mouseleave" } else { // unbind expensive mousemove event $(ob).off("mousemove.hoverIntent",track); // if hoverIntent state is true, then call the mouseOut function after the specified delay if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );} } }; // listen for mouseenter and mouseleave return this.on({'mouseenter.hoverIntent':handleHover,'mouseleave.hoverIntent':handleHover}, cfg.selector); }; })(jQuery);
JavaScript
/* * imgAreaSelect jQuery plugin * version 0.9.9 * * Copyright (c) 2008-2011 Michal Wojciechowski (odyniec.net) * * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * http://odyniec.net/projects/imgareaselect/ * */ (function($) { /* * Math functions will be used extensively, so it's convenient to make a few * shortcuts */ var abs = Math.abs, max = Math.max, min = Math.min, round = Math.round; /** * Create a new HTML div element * * @return A jQuery object representing the new element */ function div() { return $('<div/>'); } /** * imgAreaSelect initialization * * @param img * A HTML image element to attach the plugin to * @param options * An options object */ $.imgAreaSelect = function (img, options) { var /* jQuery object representing the image */ $img = $(img), /* Has the image finished loading? */ imgLoaded, /* Plugin elements */ /* Container box */ $box = div(), /* Selection area */ $area = div(), /* Border (four divs) */ $border = div().add(div()).add(div()).add(div()), /* Outer area (four divs) */ $outer = div().add(div()).add(div()).add(div()), /* Handles (empty by default, initialized in setOptions()) */ $handles = $([]), /* * Additional element to work around a cursor problem in Opera * (explained later) */ $areaOpera, /* Image position (relative to viewport) */ left, top, /* Image offset (as returned by .offset()) */ imgOfs = { left: 0, top: 0 }, /* Image dimensions (as returned by .width() and .height()) */ imgWidth, imgHeight, /* * jQuery object representing the parent element that the plugin * elements are appended to */ $parent, /* Parent element offset (as returned by .offset()) */ parOfs = { left: 0, top: 0 }, /* Base z-index for plugin elements */ zIndex = 0, /* Plugin elements position */ position = 'absolute', /* X/Y coordinates of the starting point for move/resize operations */ startX, startY, /* Horizontal and vertical scaling factors */ scaleX, scaleY, /* Current resize mode ("nw", "se", etc.) */ resize, /* Selection area constraints */ minWidth, minHeight, maxWidth, maxHeight, /* Aspect ratio to maintain (floating point number) */ aspectRatio, /* Are the plugin elements currently displayed? */ shown, /* Current selection (relative to parent element) */ x1, y1, x2, y2, /* Current selection (relative to scaled image) */ selection = { x1: 0, y1: 0, x2: 0, y2: 0, width: 0, height: 0 }, /* Document element */ docElem = document.documentElement, /* Various helper variables used throughout the code */ $p, d, i, o, w, h, adjusted; /* * Translate selection coordinates (relative to scaled image) to viewport * coordinates (relative to parent element) */ /** * Translate selection X to viewport X * * @param x * Selection X * @return Viewport X */ function viewX(x) { return x + imgOfs.left - parOfs.left; } /** * Translate selection Y to viewport Y * * @param y * Selection Y * @return Viewport Y */ function viewY(y) { return y + imgOfs.top - parOfs.top; } /* * Translate viewport coordinates to selection coordinates */ /** * Translate viewport X to selection X * * @param x * Viewport X * @return Selection X */ function selX(x) { return x - imgOfs.left + parOfs.left; } /** * Translate viewport Y to selection Y * * @param y * Viewport Y * @return Selection Y */ function selY(y) { return y - imgOfs.top + parOfs.top; } /* * Translate event coordinates (relative to document) to viewport * coordinates */ /** * Get event X and translate it to viewport X * * @param event * The event object * @return Viewport X */ function evX(event) { return event.pageX - parOfs.left; } /** * Get event Y and translate it to viewport Y * * @param event * The event object * @return Viewport Y */ function evY(event) { return event.pageY - parOfs.top; } /** * Get the current selection * * @param noScale * If set to <code>true</code>, scaling is not applied to the * returned selection * @return Selection object */ function getSelection(noScale) { var sx = noScale || scaleX, sy = noScale || scaleY; return { x1: round(selection.x1 * sx), y1: round(selection.y1 * sy), x2: round(selection.x2 * sx), y2: round(selection.y2 * sy), width: round(selection.x2 * sx) - round(selection.x1 * sx), height: round(selection.y2 * sy) - round(selection.y1 * sy) }; } /** * Set the current selection * * @param x1 * X coordinate of the upper left corner of the selection area * @param y1 * Y coordinate of the upper left corner of the selection area * @param x2 * X coordinate of the lower right corner of the selection area * @param y2 * Y coordinate of the lower right corner of the selection area * @param noScale * If set to <code>true</code>, scaling is not applied to the * new selection */ function setSelection(x1, y1, x2, y2, noScale) { var sx = noScale || scaleX, sy = noScale || scaleY; selection = { x1: round(x1 / sx || 0), y1: round(y1 / sy || 0), x2: round(x2 / sx || 0), y2: round(y2 / sy || 0) }; selection.width = selection.x2 - selection.x1; selection.height = selection.y2 - selection.y1; } /** * Recalculate image and parent offsets */ function adjust() { /* * Do not adjust if image width is not a positive number. This might * happen when imgAreaSelect is put on a parent element which is then * hidden. */ if (!$img.width()) return; /* * Get image offset. The .offset() method returns float values, so they * need to be rounded. */ imgOfs = { left: round($img.offset().left), top: round($img.offset().top) }; /* Get image dimensions */ imgWidth = $img.innerWidth(); imgHeight = $img.innerHeight(); imgOfs.top += ($img.outerHeight() - imgHeight) >> 1; imgOfs.left += ($img.outerWidth() - imgWidth) >> 1; /* Set minimum and maximum selection area dimensions */ minWidth = round(options.minWidth / scaleX) || 0; minHeight = round(options.minHeight / scaleY) || 0; maxWidth = round(min(options.maxWidth / scaleX || 1<<24, imgWidth)); maxHeight = round(min(options.maxHeight / scaleY || 1<<24, imgHeight)); /* * Workaround for jQuery 1.3.2 incorrect offset calculation, originally * observed in Safari 3. Firefox 2 is also affected. */ if ($().jquery == '1.3.2' && position == 'fixed' && !docElem['getBoundingClientRect']) { imgOfs.top += max(document.body.scrollTop, docElem.scrollTop); imgOfs.left += max(document.body.scrollLeft, docElem.scrollLeft); } /* Determine parent element offset */ parOfs = /absolute|relative/.test($parent.css('position')) ? { left: round($parent.offset().left) - $parent.scrollLeft(), top: round($parent.offset().top) - $parent.scrollTop() } : position == 'fixed' ? { left: $(document).scrollLeft(), top: $(document).scrollTop() } : { left: 0, top: 0 }; left = viewX(0); top = viewY(0); /* * Check if selection area is within image boundaries, adjust if * necessary */ if (selection.x2 > imgWidth || selection.y2 > imgHeight) doResize(); } /** * Update plugin elements * * @param resetKeyPress * If set to <code>false</code>, this instance's keypress * event handler is not activated */ function update(resetKeyPress) { /* If plugin elements are hidden, do nothing */ if (!shown) return; /* * Set the position and size of the container box and the selection area * inside it */ $box.css({ left: viewX(selection.x1), top: viewY(selection.y1) }) .add($area).width(w = selection.width).height(h = selection.height); /* * Reset the position of selection area, borders, and handles (IE6/IE7 * position them incorrectly if we don't do this) */ $area.add($border).add($handles).css({ left: 0, top: 0 }); /* Set border dimensions */ $border .width(max(w - $border.outerWidth() + $border.innerWidth(), 0)) .height(max(h - $border.outerHeight() + $border.innerHeight(), 0)); /* Arrange the outer area elements */ $($outer[0]).css({ left: left, top: top, width: selection.x1, height: imgHeight }); $($outer[1]).css({ left: left + selection.x1, top: top, width: w, height: selection.y1 }); $($outer[2]).css({ left: left + selection.x2, top: top, width: imgWidth - selection.x2, height: imgHeight }); $($outer[3]).css({ left: left + selection.x1, top: top + selection.y2, width: w, height: imgHeight - selection.y2 }); w -= $handles.outerWidth(); h -= $handles.outerHeight(); /* Arrange handles */ switch ($handles.length) { case 8: $($handles[4]).css({ left: w >> 1 }); $($handles[5]).css({ left: w, top: h >> 1 }); $($handles[6]).css({ left: w >> 1, top: h }); $($handles[7]).css({ top: h >> 1 }); case 4: $handles.slice(1,3).css({ left: w }); $handles.slice(2,4).css({ top: h }); } if (resetKeyPress !== false) { /* * Need to reset the document keypress event handler -- unbind the * current handler */ if ($.imgAreaSelect.keyPress != docKeyPress) $(document).unbind($.imgAreaSelect.keyPress, $.imgAreaSelect.onKeyPress); if (options.keys) /* * Set the document keypress event handler to this instance's * docKeyPress() function */ $(document)[$.imgAreaSelect.keyPress]( $.imgAreaSelect.onKeyPress = docKeyPress); } /* * Internet Explorer displays 1px-wide dashed borders incorrectly by * filling the spaces between dashes with white. Toggling the margin * property between 0 and "auto" fixes this in IE6 and IE7 (IE8 is still * broken). This workaround is not perfect, as it requires setTimeout() * and thus causes the border to flicker a bit, but I haven't found a * better solution. * * Note: This only happens with CSS borders, set with the borderWidth, * borderOpacity, borderColor1, and borderColor2 options (which are now * deprecated). Borders created with GIF background images are fine. */ if ($.browser.msie && $border.outerWidth() - $border.innerWidth() == 2) { $border.css('margin', 0); setTimeout(function () { $border.css('margin', 'auto'); }, 0); } } /** * Do the complete update sequence: recalculate offsets, update the * elements, and set the correct values of x1, y1, x2, and y2. * * @param resetKeyPress * If set to <code>false</code>, this instance's keypress * event handler is not activated */ function doUpdate(resetKeyPress) { adjust(); update(resetKeyPress); x1 = viewX(selection.x1); y1 = viewY(selection.y1); x2 = viewX(selection.x2); y2 = viewY(selection.y2); } /** * Hide or fade out an element (or multiple elements) * * @param $elem * A jQuery object containing the element(s) to hide/fade out * @param fn * Callback function to be called when fadeOut() completes */ function hide($elem, fn) { options.fadeSpeed ? $elem.fadeOut(options.fadeSpeed, fn) : $elem.hide(); } /** * Selection area mousemove event handler * * @param event * The event object */ function areaMouseMove(event) { var x = selX(evX(event)) - selection.x1, y = selY(evY(event)) - selection.y1; if (!adjusted) { adjust(); adjusted = true; $box.one('mouseout', function () { adjusted = false; }); } /* Clear the resize mode */ resize = ''; if (options.resizable) { /* * Check if the mouse pointer is over the resize margin area and set * the resize mode accordingly */ if (y <= options.resizeMargin) resize = 'n'; else if (y >= selection.height - options.resizeMargin) resize = 's'; if (x <= options.resizeMargin) resize += 'w'; else if (x >= selection.width - options.resizeMargin) resize += 'e'; } $box.css('cursor', resize ? resize + '-resize' : options.movable ? 'move' : ''); if ($areaOpera) $areaOpera.toggle(); } /** * Document mouseup event handler * * @param event * The event object */ function docMouseUp(event) { /* Set back the default cursor */ $('body').css('cursor', ''); /* * If autoHide is enabled, or if the selection has zero width/height, * hide the selection and the outer area */ if (options.autoHide || selection.width * selection.height == 0) hide($box.add($outer), function () { $(this).hide(); }); $(document).unbind('mousemove', selectingMouseMove); $box.mousemove(areaMouseMove); options.onSelectEnd(img, getSelection()); } /** * Selection area mousedown event handler * * @param event * The event object * @return false */ function areaMouseDown(event) { if (event.which != 1) return false; adjust(); if (resize) { /* Resize mode is in effect */ $('body').css('cursor', resize + '-resize'); x1 = viewX(selection[/w/.test(resize) ? 'x2' : 'x1']); y1 = viewY(selection[/n/.test(resize) ? 'y2' : 'y1']); $(document).mousemove(selectingMouseMove) .one('mouseup', docMouseUp); $box.unbind('mousemove', areaMouseMove); } else if (options.movable) { startX = left + selection.x1 - evX(event); startY = top + selection.y1 - evY(event); $box.unbind('mousemove', areaMouseMove); $(document).mousemove(movingMouseMove) .one('mouseup', function () { options.onSelectEnd(img, getSelection()); $(document).unbind('mousemove', movingMouseMove); $box.mousemove(areaMouseMove); }); } else $img.mousedown(event); return false; } /** * Adjust the x2/y2 coordinates to maintain aspect ratio (if defined) * * @param xFirst * If set to <code>true</code>, calculate x2 first. Otherwise, * calculate y2 first. */ function fixAspectRatio(xFirst) { if (aspectRatio) if (xFirst) { x2 = max(left, min(left + imgWidth, x1 + abs(y2 - y1) * aspectRatio * (x2 > x1 || -1))); y2 = round(max(top, min(top + imgHeight, y1 + abs(x2 - x1) / aspectRatio * (y2 > y1 || -1)))); x2 = round(x2); } else { y2 = max(top, min(top + imgHeight, y1 + abs(x2 - x1) / aspectRatio * (y2 > y1 || -1))); x2 = round(max(left, min(left + imgWidth, x1 + abs(y2 - y1) * aspectRatio * (x2 > x1 || -1)))); y2 = round(y2); } } /** * Resize the selection area respecting the minimum/maximum dimensions and * aspect ratio */ function doResize() { /* * Make sure the top left corner of the selection area stays within * image boundaries (it might not if the image source was dynamically * changed). */ x1 = min(x1, left + imgWidth); y1 = min(y1, top + imgHeight); if (abs(x2 - x1) < minWidth) { /* Selection width is smaller than minWidth */ x2 = x1 - minWidth * (x2 < x1 || -1); if (x2 < left) x1 = left + minWidth; else if (x2 > left + imgWidth) x1 = left + imgWidth - minWidth; } if (abs(y2 - y1) < minHeight) { /* Selection height is smaller than minHeight */ y2 = y1 - minHeight * (y2 < y1 || -1); if (y2 < top) y1 = top + minHeight; else if (y2 > top + imgHeight) y1 = top + imgHeight - minHeight; } x2 = max(left, min(x2, left + imgWidth)); y2 = max(top, min(y2, top + imgHeight)); fixAspectRatio(abs(x2 - x1) < abs(y2 - y1) * aspectRatio); if (abs(x2 - x1) > maxWidth) { /* Selection width is greater than maxWidth */ x2 = x1 - maxWidth * (x2 < x1 || -1); fixAspectRatio(); } if (abs(y2 - y1) > maxHeight) { /* Selection height is greater than maxHeight */ y2 = y1 - maxHeight * (y2 < y1 || -1); fixAspectRatio(true); } selection = { x1: selX(min(x1, x2)), x2: selX(max(x1, x2)), y1: selY(min(y1, y2)), y2: selY(max(y1, y2)), width: abs(x2 - x1), height: abs(y2 - y1) }; update(); options.onSelectChange(img, getSelection()); } /** * Mousemove event handler triggered when the user is selecting an area * * @param event * The event object * @return false */ function selectingMouseMove(event) { x2 = /w|e|^$/.test(resize) || aspectRatio ? evX(event) : viewX(selection.x2); y2 = /n|s|^$/.test(resize) || aspectRatio ? evY(event) : viewY(selection.y2); doResize(); return false; } /** * Move the selection area * * @param newX1 * New viewport X1 * @param newY1 * New viewport Y1 */ function doMove(newX1, newY1) { x2 = (x1 = newX1) + selection.width; y2 = (y1 = newY1) + selection.height; $.extend(selection, { x1: selX(x1), y1: selY(y1), x2: selX(x2), y2: selY(y2) }); update(); options.onSelectChange(img, getSelection()); } /** * Mousemove event handler triggered when the selection area is being moved * * @param event * The event object * @return false */ function movingMouseMove(event) { x1 = max(left, min(startX + evX(event), left + imgWidth - selection.width)); y1 = max(top, min(startY + evY(event), top + imgHeight - selection.height)); doMove(x1, y1); event.preventDefault(); return false; } /** * Start selection */ function startSelection() { $(document).unbind('mousemove', startSelection); adjust(); x2 = x1; y2 = y1; doResize(); resize = ''; if (!$outer.is(':visible')) /* Show the plugin elements */ $box.add($outer).hide().fadeIn(options.fadeSpeed||0); shown = true; $(document).unbind('mouseup', cancelSelection) .mousemove(selectingMouseMove).one('mouseup', docMouseUp); $box.unbind('mousemove', areaMouseMove); options.onSelectStart(img, getSelection()); } /** * Cancel selection */ function cancelSelection() { $(document).unbind('mousemove', startSelection) .unbind('mouseup', cancelSelection); hide($box.add($outer)); setSelection(selX(x1), selY(y1), selX(x1), selY(y1)); /* If this is an API call, callback functions should not be triggered */ if (!(this instanceof $.imgAreaSelect)) { options.onSelectChange(img, getSelection()); options.onSelectEnd(img, getSelection()); } } /** * Image mousedown event handler * * @param event * The event object * @return false */ function imgMouseDown(event) { /* Ignore the event if animation is in progress */ if (event.which != 1 || $outer.is(':animated')) return false; adjust(); startX = x1 = evX(event); startY = y1 = evY(event); /* Selection will start when the mouse is moved */ $(document).mousemove(startSelection).mouseup(cancelSelection); return false; } /** * Window resize event handler */ function windowResize() { doUpdate(false); } /** * Image load event handler. This is the final part of the initialization * process. */ function imgLoad() { imgLoaded = true; /* Set options */ setOptions(options = $.extend({ classPrefix: 'imgareaselect', movable: true, parent: 'body', resizable: true, resizeMargin: 10, onInit: function () {}, onSelectStart: function () {}, onSelectChange: function () {}, onSelectEnd: function () {} }, options)); $box.add($outer).css({ visibility: '' }); if (options.show) { shown = true; adjust(); update(); $box.add($outer).hide().fadeIn(options.fadeSpeed||0); } /* * Call the onInit callback. The setTimeout() call is used to ensure * that the plugin has been fully initialized and the object instance is * available (so that it can be obtained in the callback). */ setTimeout(function () { options.onInit(img, getSelection()); }, 0); } /** * Document keypress event handler * * @param event * The event object * @return false */ var docKeyPress = function(event) { var k = options.keys, d, t, key = event.keyCode; d = !isNaN(k.alt) && (event.altKey || event.originalEvent.altKey) ? k.alt : !isNaN(k.ctrl) && event.ctrlKey ? k.ctrl : !isNaN(k.shift) && event.shiftKey ? k.shift : !isNaN(k.arrows) ? k.arrows : 10; if (k.arrows == 'resize' || (k.shift == 'resize' && event.shiftKey) || (k.ctrl == 'resize' && event.ctrlKey) || (k.alt == 'resize' && (event.altKey || event.originalEvent.altKey))) { /* Resize selection */ switch (key) { case 37: /* Left */ d = -d; case 39: /* Right */ t = max(x1, x2); x1 = min(x1, x2); x2 = max(t + d, x1); fixAspectRatio(); break; case 38: /* Up */ d = -d; case 40: /* Down */ t = max(y1, y2); y1 = min(y1, y2); y2 = max(t + d, y1); fixAspectRatio(true); break; default: return; } doResize(); } else { /* Move selection */ x1 = min(x1, x2); y1 = min(y1, y2); switch (key) { case 37: /* Left */ doMove(max(x1 - d, left), y1); break; case 38: /* Up */ doMove(x1, max(y1 - d, top)); break; case 39: /* Right */ doMove(x1 + min(d, imgWidth - selX(x2)), y1); break; case 40: /* Down */ doMove(x1, y1 + min(d, imgHeight - selY(y2))); break; default: return; } } return false; }; /** * Apply style options to plugin element (or multiple elements) * * @param $elem * A jQuery object representing the element(s) to style * @param props * An object that maps option names to corresponding CSS * properties */ function styleOptions($elem, props) { for (var option in props) if (options[option] !== undefined) $elem.css(props[option], options[option]); } /** * Set plugin options * * @param newOptions * The new options object */ function setOptions(newOptions) { if (newOptions.parent) ($parent = $(newOptions.parent)).append($box.add($outer)); /* Merge the new options with the existing ones */ $.extend(options, newOptions); adjust(); if (newOptions.handles != null) { /* Recreate selection area handles */ $handles.remove(); $handles = $([]); i = newOptions.handles ? newOptions.handles == 'corners' ? 4 : 8 : 0; while (i--) $handles = $handles.add(div()); /* Add a class to handles and set the CSS properties */ $handles.addClass(options.classPrefix + '-handle').css({ position: 'absolute', /* * The font-size property needs to be set to zero, otherwise * Internet Explorer makes the handles too large */ fontSize: 0, zIndex: zIndex + 1 || 1 }); /* * If handle width/height has not been set with CSS rules, set the * default 5px */ if (!parseInt($handles.css('width')) >= 0) $handles.width(5).height(5); /* * If the borderWidth option is in use, add a solid border to * handles */ if (o = options.borderWidth) $handles.css({ borderWidth: o, borderStyle: 'solid' }); /* Apply other style options */ styleOptions($handles, { borderColor1: 'border-color', borderColor2: 'background-color', borderOpacity: 'opacity' }); } /* Calculate scale factors */ scaleX = options.imageWidth / imgWidth || 1; scaleY = options.imageHeight / imgHeight || 1; /* Set selection */ if (newOptions.x1 != null) { setSelection(newOptions.x1, newOptions.y1, newOptions.x2, newOptions.y2); newOptions.show = !newOptions.hide; } if (newOptions.keys) /* Enable keyboard support */ options.keys = $.extend({ shift: 1, ctrl: 'resize' }, newOptions.keys); /* Add classes to plugin elements */ $outer.addClass(options.classPrefix + '-outer'); $area.addClass(options.classPrefix + '-selection'); for (i = 0; i++ < 4;) $($border[i-1]).addClass(options.classPrefix + '-border' + i); /* Apply style options */ styleOptions($area, { selectionColor: 'background-color', selectionOpacity: 'opacity' }); styleOptions($border, { borderOpacity: 'opacity', borderWidth: 'border-width' }); styleOptions($outer, { outerColor: 'background-color', outerOpacity: 'opacity' }); if (o = options.borderColor1) $($border[0]).css({ borderStyle: 'solid', borderColor: o }); if (o = options.borderColor2) $($border[1]).css({ borderStyle: 'dashed', borderColor: o }); /* Append all the selection area elements to the container box */ $box.append($area.add($border).add($areaOpera).add($handles)); if ($.browser.msie) { if (o = $outer.css('filter').match(/opacity=(\d+)/)) $outer.css('opacity', o[1]/100); if (o = $border.css('filter').match(/opacity=(\d+)/)) $border.css('opacity', o[1]/100); } if (newOptions.hide) hide($box.add($outer)); else if (newOptions.show && imgLoaded) { shown = true; $box.add($outer).fadeIn(options.fadeSpeed||0); doUpdate(); } /* Calculate the aspect ratio factor */ aspectRatio = (d = (options.aspectRatio || '').split(/:/))[0] / d[1]; $img.add($outer).unbind('mousedown', imgMouseDown); if (options.disable || options.enable === false) { /* Disable the plugin */ $box.unbind('mousemove', areaMouseMove).unbind('mousedown', areaMouseDown); $(window).unbind('resize', windowResize); } else { if (options.enable || options.disable === false) { /* Enable the plugin */ if (options.resizable || options.movable) $box.mousemove(areaMouseMove).mousedown(areaMouseDown); $(window).resize(windowResize); } if (!options.persistent) $img.add($outer).mousedown(imgMouseDown); } options.enable = options.disable = undefined; } /** * Remove plugin completely */ this.remove = function () { /* * Call setOptions with { disable: true } to unbind the event handlers */ setOptions({ disable: true }); $box.add($outer).remove(); }; /* * Public API */ /** * Get current options * * @return An object containing the set of options currently in use */ this.getOptions = function () { return options; }; /** * Set plugin options * * @param newOptions * The new options object */ this.setOptions = setOptions; /** * Get the current selection * * @param noScale * If set to <code>true</code>, scaling is not applied to the * returned selection * @return Selection object */ this.getSelection = getSelection; /** * Set the current selection * * @param x1 * X coordinate of the upper left corner of the selection area * @param y1 * Y coordinate of the upper left corner of the selection area * @param x2 * X coordinate of the lower right corner of the selection area * @param y2 * Y coordinate of the lower right corner of the selection area * @param noScale * If set to <code>true</code>, scaling is not applied to the * new selection */ this.setSelection = setSelection; /** * Cancel selection */ this.cancelSelection = cancelSelection; /** * Update plugin elements * * @param resetKeyPress * If set to <code>false</code>, this instance's keypress * event handler is not activated */ this.update = doUpdate; /* * Traverse the image's parent elements (up to <body>) and find the * highest z-index */ $p = $img; while ($p.length) { zIndex = max(zIndex, !isNaN($p.css('z-index')) ? $p.css('z-index') : zIndex); /* Also check if any of the ancestor elements has fixed position */ if ($p.css('position') == 'fixed') position = 'fixed'; $p = $p.parent(':not(body)'); } /* * If z-index is given as an option, it overrides the one found by the * above loop */ zIndex = options.zIndex || zIndex; if ($.browser.msie) $img.attr('unselectable', 'on'); /* * In MSIE and WebKit, we need to use the keydown event instead of keypress */ $.imgAreaSelect.keyPress = $.browser.msie || $.browser.safari ? 'keydown' : 'keypress'; /* * There is a bug affecting the CSS cursor property in Opera (observed in * versions up to 10.00) that prevents the cursor from being updated unless * the mouse leaves and enters the element again. To trigger the mouseover * event, we're adding an additional div to $box and we're going to toggle * it when mouse moves inside the selection area. */ if ($.browser.opera) $areaOpera = div().css({ width: '100%', height: '100%', position: 'absolute', zIndex: zIndex + 2 || 2 }); /* * We initially set visibility to "hidden" as a workaround for a weird * behaviour observed in Google Chrome 1.0.154.53 (on Windows XP). Normally * we would just set display to "none", but, for some reason, if we do so * then Chrome refuses to later display the element with .show() or * .fadeIn(). */ $box.add($outer).css({ visibility: 'hidden', position: position, overflow: 'hidden', zIndex: zIndex || '0' }); $box.css({ zIndex: zIndex + 2 || 2 }); $area.add($border).css({ position: 'absolute', fontSize: 0 }); /* * If the image has been fully loaded, or if it is not really an image (eg. * a div), call imgLoad() immediately; otherwise, bind it to be called once * on image load event. */ img.complete || img.readyState == 'complete' || !$img.is('img') ? imgLoad() : $img.one('load', imgLoad); /* * MSIE 9.0 doesn't always fire the image load event -- resetting the src * attribute seems to trigger it. The check is for version 7 and above to * accommodate for MSIE 9 running in compatibility mode. */ if (!imgLoaded && $.browser.msie && $.browser.version >= 7) img.src = img.src; }; /** * Invoke imgAreaSelect on a jQuery object containing the image(s) * * @param options * Options object * @return The jQuery object or a reference to imgAreaSelect instance (if the * <code>instance</code> option was specified) */ $.fn.imgAreaSelect = function (options) { options = options || {}; this.each(function () { /* Is there already an imgAreaSelect instance bound to this element? */ if ($(this).data('imgAreaSelect')) { /* Yes there is -- is it supposed to be removed? */ if (options.remove) { /* Remove the plugin */ $(this).data('imgAreaSelect').remove(); $(this).removeData('imgAreaSelect'); } else /* Reset options */ $(this).data('imgAreaSelect').setOptions(options); } else if (!options.remove) { /* No exising instance -- create a new one */ /* * If neither the "enable" nor the "disable" option is present, add * "enable" as the default */ if (options.enable === undefined && options.disable === undefined) options.enable = true; $(this).data('imgAreaSelect', new $.imgAreaSelect(this, options)); } }); if (options.instance) /* * Return the imgAreaSelect instance bound to the first element in the * set */ return $(this).data('imgAreaSelect'); return this; }; })(jQuery);
JavaScript
(function(){ if ( typeof tinyMCEPreInit === 'undefined' ) return; var t = tinyMCEPreInit, baseurl = t.base, markDone = tinymce.ScriptLoader.markDone, lang = t.ref.language, theme = t.ref.theme, plugins = t.ref.plugins, suffix = t.suffix; markDone( baseurl+'/langs/'+lang+'.js' ); markDone( baseurl+'/themes/'+theme+'/editor_template'+suffix+'.js' ); markDone( baseurl+'/themes/'+theme+'/langs/'+lang+'.js' ); markDone( baseurl+'/themes/'+theme+'/langs/'+lang+'_dlg.js' ); tinymce.each( plugins.split(','), function(plugin){ if ( plugin && plugin.charAt(0) != '-' ) { markDone( baseurl+'/plugins/'+plugin+'/editor_plugin'+suffix+'.js' ); markDone( baseurl+'/plugins/'+plugin+'/langs/'+lang+'.js' ); markDone( baseurl+'/plugins/'+plugin+'/langs/'+lang+'_dlg.js' ) } }); })();
JavaScript
/** * TinyMCE Schema.js * * Duck-punched by WordPress core to support a sane schema superset. * * Copyright, Moxiecode Systems AB * Released under LGPL * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ (function(tinymce) { var mapCache = {}, makeMap = tinymce.makeMap, each = tinymce.each; function split(str, delim) { return str.split(delim || ','); }; /** * Unpacks the specified lookup and string data it will also parse it into an object * map with sub object for it's children. This will later also include the attributes. */ function unpack(lookup, data) { var key, elements = {}; function replace(value) { return value.replace(/[A-Z]+/g, function(key) { return replace(lookup[key]); }); }; // Unpack lookup for (key in lookup) { if (lookup.hasOwnProperty(key)) lookup[key] = replace(lookup[key]); } // Unpack and parse data into object map replace(data).replace(/#/g, '#text').replace(/(\w+)\[([^\]]+)\]\[([^\]]*)\]/g, function(str, name, attributes, children) { attributes = split(attributes, '|'); elements[name] = { attributes : makeMap(attributes), attributesOrder : attributes, children : makeMap(children, '|', {'#comment' : {}}) } }); return elements; }; /** * Returns the HTML5 schema and caches it in the mapCache. */ function getHTML5() { var html5 = mapCache.html5; if (!html5) { html5 = mapCache.html5 = unpack({ A : 'accesskey|class|contextmenu|dir|draggable|dropzone|hidden|id|inert|itemid|itemprop|itemref|itemscope|itemtype|lang|spellcheck|style|tabindex|title|translate|item|role|subject|onclick|ondblclick|onmousedown|onmouseup|onmouseover|onmousemove|onmouseout|onkeypress|onkeydown|onkeyup', B : '#|a|abbr|area|audio|b|bdi|bdo|br|button|canvas|cite|code|command|data|datalist|del|dfn|em|embed|i|iframe|img|input|ins|kbd|keygen|label|link|map|mark|math|meta|meter|noscript|object|output|progress|q|ruby|s|samp|script|select|small|span|strong|sub|sup|svg|textarea|time|u|var|video|wbr', C : '#|a|abbr|area|address|article|aside|audio|b|bdi|bdo|blockquote|br|button|canvas|cite|code|command|data|datalist|del|details|dfn|dialog|div|dl|em|embed|fieldset|figure|footer|form|h1|h2|h3|h4|h5|h6|header|hgroup|hr|i|iframe|img|input|ins|kbd|keygen|label|link|map|mark|math|menu|meta|meter|nav|noscript|ol|object|output|p|pre|progress|q|ruby|s|samp|script|section|select|small|span|strong|style|sub|sup|svg|table|textarea|time|u|ul|var|video|wbr' }, 'html[A|manifest][body|head]' + 'head[A][base|command|link|meta|noscript|script|style|title]' + 'title[A][#]' + 'base[A|href|target][]' + 'link[A|href|rel|media|type|sizes|crossorigin|hreflang][]' + 'meta[A|http-equiv|name|content|charset][]' + 'style[A|type|media|scoped][#]' + 'script[A|charset|type|src|defer|async|crossorigin][#]' + 'noscript[A][C]' + 'body[A|onafterprint|onbeforeprint|onbeforeunload|onblur|onerror|onfocus|onfullscreenchange|onfullscreenerror|onhashchange|onload|onmessage|onoffline|ononline|onpagehide|onpageshow|onpopstate|onresize|onscroll|onstorage|onunload][C]' + 'section[A][C]' + 'nav[A][C]' + 'article[A][C]' + 'aside[A][C]' + 'h1[A][B]' + 'h2[A][B]' + 'h3[A][B]' + 'h4[A][B]' + 'h5[A][B]' + 'h6[A][B]' + 'hgroup[A][h1|h2|h3|h4|h5|h6]' + 'header[A][C]' + 'footer[A][C]' + 'address[A][C]' + 'p[A][B]' + 'br[A][]' + 'pre[A][B]' + 'dialog[A|open][C|dd|dt]' + 'blockquote[A|cite][C]' + 'ol[A|start|reversed][li]' + 'ul[A][li]' + 'li[A|value][C]' + 'dl[A][dd|dt]' + 'dt[A][C|B]' + 'dd[A][C]' + 'a[A|href|target|download|ping|rel|media|type][B]' + 'em[A][B]' + 'strong[A][B]' + 'small[A][B]' + 's[A][B]' + 'cite[A][B]' + 'q[A|cite][B]' + 'dfn[A][B]' + 'abbr[A][B]' + 'code[A][B]' + 'var[A][B]' + 'samp[A][B]' + 'kbd[A][B]' + 'sub[A][B]' + 'sup[A][B]' + 'i[A][B]' + 'b[A][B]' + 'u[A][B]' + 'mark[A][B]' + 'progress[A|value|max][B]' + 'meter[A|value|min|max|low|high|optimum][B]' + 'time[A|datetime][B]' + 'ruby[A][B|rt|rp]' + 'rt[A][B]' + 'rp[A][B]' + 'bdi[A][B]' + 'bdo[A][B]' + 'span[A][B]' + 'ins[A|cite|datetime][C|B]' + 'del[A|cite|datetime][C|B]' + 'figure[A][C|legend|figcaption]' + 'figcaption[A][C]' + 'img[A|alt|src|srcset|crossorigin|usemap|ismap|width|height][]' + 'iframe[A|name|src|srcdoc|height|width|sandbox|seamless|allowfullscreen][C|B]' + 'embed[A|src|height|width|type][]' + 'object[A|data|type|typemustmatch|name|usemap|form|width|height][C|B|param]' + 'param[A|name|value][]' + 'summary[A][B]' + 'details[A|open][C|legend|summary]' + 'command[A|type|label|icon|disabled|checked|radiogroup|command][]' + 'menu[A|type|label][C|li]' + 'legend[A][C|B]' + 'div[A][C]' + 'source[A|src|type|media][]' + 'track[A|kind|src|srclang|label|default][]' + 'audio[A|src|autobuffer|autoplay|loop|controls|crossorigin|preload|mediagroup|muted][C|source|track]' + 'video[A|src|autobuffer|autoplay|loop|controls|width|height|poster|crossorigin|preload|mediagroup|muted][C|source|track]' + 'hr[A][]' + 'form[A|accept-charset|action|autocomplete|enctype|method|name|novalidate|target][C]' + 'fieldset[A|disabled|form|name][C|legend]' + 'label[A|form|for][B]' + 'input[A|type|accept|alt|autocomplete|autofocus|checked|dirname|disabled|form|formaction|formenctype|formmethod|formnovalidate|formtarget|height|inputmode|list|max|maxlength|min|multiple|name|pattern|placeholder|readonly|required|size|src|step|value|width|files][]' + 'button[A|autofocus|disabled|form|formaction|formenctype|formmethod|formnovalidate|formtarget|name|type|value][B]' + 'select[A|autofocus|disabled|form|multiple|name|required|size][option|optgroup]' + 'data[A|value][B]' + 'datalist[A][B|option]' + 'optgroup[A|disabled|label][option]' + 'option[A|disabled|selected|label|value][#]' + 'textarea[A|autocomplete|autofocus|cols|dirname|disabled|form|inputmode|maxlength|name|placeholder|readonly|required|rows|wrap][#]' + 'keygen[A|autofocus|challenge|disabled|form|keytype|name][]' + 'output[A|for|form|name][B]' + 'canvas[A|width|height][a|button|input]' + 'map[A|name][C|B]' + 'area[A|alt|coords|shape|href|target|download|ping|rel|media|hreflang|type][]' + 'math[A][]' + 'svg[A][]' + 'table[A][caption|colgroup|thead|tfoot|tbody|tr]' + 'caption[A][C]' + 'colgroup[A|span][col]' + 'col[A|span][]' + 'thead[A][tr]' + 'tfoot[A][tr]' + 'tbody[A][tr]' + 'tr[A][th|td]' + 'th[A|headers|rowspan|colspan|scope][C]' + 'td[A|headers|rowspan|colspan][C]' + 'wbr[A][]' ); } return html5; }; /** * Returns the HTML4 schema and caches it in the mapCache. */ function getHTML4() { var html4 = mapCache.html4; if (!html4) { // This is the XHTML 1.0 transitional elements with it's attributes and children packed to reduce it's size html4 = mapCache.html4 = unpack({ Z : 'H|K|N|O|P', Y : 'X|form|R|Q', ZG : 'E|span|width|align|char|charoff|valign', X : 'p|T|div|U|W|isindex|fieldset|table', ZF : 'E|align|char|charoff|valign', W : 'pre|hr|blockquote|address|center|noframes', ZE : 'abbr|axis|headers|scope|rowspan|colspan|align|char|charoff|valign|nowrap|bgcolor|width|height', ZD : '[E][S]', U : 'ul|ol|dl|menu|dir', ZC : 'p|Y|div|U|W|table|br|span|bdo|object|applet|img|map|K|N|Q', T : 'h1|h2|h3|h4|h5|h6', ZB : 'X|S|Q', S : 'R|P', ZA : 'a|G|J|M|O|P', R : 'a|H|K|N|O', Q : 'noscript|P', P : 'ins|del|script', O : 'input|select|textarea|label|button', N : 'M|L', M : 'em|strong|dfn|code|q|samp|kbd|var|cite|abbr|acronym', L : 'sub|sup', K : 'J|I', J : 'tt|i|b|u|s|strike', I : 'big|small|font|basefont', H : 'G|F', G : 'br|span|bdo', F : 'object|applet|img|map|iframe', E : 'A|B|C', D : 'accesskey|tabindex|onfocus|onblur', C : 'onclick|ondblclick|onmousedown|onmouseup|onmouseover|onmousemove|onmouseout|onkeypress|onkeydown|onkeyup', B : 'lang|xml:lang|dir', A : 'id|class|style|title' }, 'script[id|charset|type|language|src|defer|xml:space][]' + 'style[B|id|type|media|title|xml:space][]' + 'object[E|declare|classid|codebase|data|type|codetype|archive|standby|width|height|usemap|name|tabindex|align|border|hspace|vspace][#|param|Y]' + 'param[id|name|value|valuetype|type][]' + 'p[E|align][#|S]' + 'a[E|D|charset|type|name|href|hreflang|rel|rev|shape|coords|target][#|Z]' + 'br[A|clear][]' + 'span[E][#|S]' + 'bdo[A|C|B][#|S]' + 'applet[A|codebase|archive|code|object|alt|name|width|height|align|hspace|vspace][#|param|Y]' + 'h1[E|align][#|S]' + 'img[E|src|alt|name|longdesc|width|height|usemap|ismap|align|border|hspace|vspace][]' + 'map[B|C|A|name][X|form|Q|area]' + 'h2[E|align][#|S]' + 'iframe[A|longdesc|name|src|frameborder|marginwidth|marginheight|scrolling|align|width|height][#|Y]' + 'h3[E|align][#|S]' + 'tt[E][#|S]' + 'i[E][#|S]' + 'b[E][#|S]' + 'u[E][#|S]' + 's[E][#|S]' + 'strike[E][#|S]' + 'big[E][#|S]' + 'small[E][#|S]' + 'font[A|B|size|color|face][#|S]' + 'basefont[id|size|color|face][]' + 'em[E][#|S]' + 'strong[E][#|S]' + 'dfn[E][#|S]' + 'code[E][#|S]' + 'q[E|cite][#|S]' + 'samp[E][#|S]' + 'kbd[E][#|S]' + 'var[E][#|S]' + 'cite[E][#|S]' + 'abbr[E][#|S]' + 'acronym[E][#|S]' + 'sub[E][#|S]' + 'sup[E][#|S]' + 'input[E|D|type|name|value|checked|disabled|readonly|size|maxlength|src|alt|usemap|onselect|onchange|accept|align][]' + 'select[E|name|size|multiple|disabled|tabindex|onfocus|onblur|onchange][optgroup|option]' + 'optgroup[E|disabled|label][option]' + 'option[E|selected|disabled|label|value][]' + 'textarea[E|D|name|rows|cols|disabled|readonly|onselect|onchange][]' + 'label[E|for|accesskey|onfocus|onblur][#|S]' + 'button[E|D|name|value|type|disabled][#|p|T|div|U|W|table|G|object|applet|img|map|K|N|Q]' + 'h4[E|align][#|S]' + 'ins[E|cite|datetime][#|Y]' + 'h5[E|align][#|S]' + 'del[E|cite|datetime][#|Y]' + 'h6[E|align][#|S]' + 'div[E|align][#|Y]' + 'ul[E|type|compact][li]' + 'li[E|type|value][#|Y]' + 'ol[E|type|compact|start][li]' + 'dl[E|compact][dt|dd]' + 'dt[E][#|S]' + 'dd[E][#|Y]' + 'menu[E|compact][li]' + 'dir[E|compact][li]' + 'pre[E|width|xml:space][#|ZA]' + 'hr[E|align|noshade|size|width][]' + 'blockquote[E|cite][#|Y]' + 'address[E][#|S|p]' + 'center[E][#|Y]' + 'noframes[E][#|Y]' + 'isindex[A|B|prompt][]' + 'fieldset[E][#|legend|Y]' + 'legend[E|accesskey|align][#|S]' + 'table[E|summary|width|border|frame|rules|cellspacing|cellpadding|align|bgcolor][caption|col|colgroup|thead|tfoot|tbody|tr]' + 'caption[E|align][#|S]' + 'col[ZG][]' + 'colgroup[ZG][col]' + 'thead[ZF][tr]' + 'tr[ZF|bgcolor][th|td]' + 'th[E|ZE][#|Y]' + 'form[E|action|method|name|enctype|onsubmit|onreset|accept|accept-charset|target][#|X|R|Q]' + 'noscript[E][#|Y]' + 'td[E|ZE][#|Y]' + 'tfoot[ZF][tr]' + 'tbody[ZF][tr]' + 'area[E|D|shape|coords|href|nohref|alt|target][]' + 'base[id|href|target][]' + 'body[E|onload|onunload|background|bgcolor|text|link|vlink|alink][#|Y]' ); } return html4; }; /** * WordPress Core * * Returns a schema that is the result of a deep merge between the HTML5 * and HTML4 schemas. */ function getSaneSchema() { var cachedMapCache = mapCache, html5, html4; if ( mapCache.sane ) return mapCache.sane; // Bust the mapCache so we're not dealing with the other schema objects. mapCache = {}; html5 = getHTML5(); html4 = getHTML4(); mapCache = cachedMapCache; each( html4, function( html4settings, tag ) { var html5settings = html5[ tag ], difference = []; // Merge tags missing in HTML5 mode. if ( ! html5settings ) { html5[ tag ] = html4settings; return; } // Merge attributes missing from this HTML5 tag. each( html4settings.attributes, function( attribute, key ) { if ( ! html5settings.attributes[ key ] ) html5settings.attributes[ key ] = attribute; }); // Merge any missing attributes into the attributes order. each( html4settings.attributesOrder, function( key ) { if ( -1 === tinymce.inArray( html5settings.attributesOrder, key ) ) difference.push( key ); }); html5settings.attributesOrder = html5settings.attributesOrder.concat( difference ); // Merge children missing from this HTML5 tag. each( html4settings.children, function( child, key ) { if ( ! html5settings.children[ key ] ) html5settings.children[ key ] = child; }); }); return mapCache.sane = html5; } /** * Schema validator class. * * @class tinymce.html.Schema * @example * if (tinymce.activeEditor.schema.isValidChild('p', 'span')) * alert('span is valid child of p.'); * * if (tinymce.activeEditor.schema.getElementRule('p')) * alert('P is a valid element.'); * * @class tinymce.html.Schema * @version 3.4 */ /** * Constructs a new Schema instance. * * @constructor * @method Schema * @param {Object} settings Name/value settings object. */ tinymce.html.Schema = function(settings) { var self = this, elements = {}, children = {}, patternElements = [], validStyles, schemaItems; var whiteSpaceElementsMap, selfClosingElementsMap, shortEndedElementsMap, boolAttrMap, blockElementsMap, nonEmptyElementsMap, customElementsMap = {}; // Creates an lookup table map object for the specified option or the default value function createLookupTable(option, default_value, extend) { var value = settings[option]; if (!value) { // Get cached default map or make it if needed value = mapCache[option]; if (!value) { value = makeMap(default_value, ' ', makeMap(default_value.toUpperCase(), ' ')); value = tinymce.extend(value, extend); mapCache[option] = value; } } else { // Create custom map value = makeMap(value, ',', makeMap(value.toUpperCase(), ' ')); } return value; }; settings = settings || {}; /** * WordPress core uses a sane schema in place of the default "HTML5" schema. */ schemaItems = settings.schema == "html5" ? getSaneSchema() : getHTML4(); // Allow all elements and attributes if verify_html is set to false if (settings.verify_html === false) settings.valid_elements = '*[*]'; // Build styles list if (settings.valid_styles) { validStyles = {}; // Convert styles into a rule list each(settings.valid_styles, function(value, key) { validStyles[key] = tinymce.explode(value); }); } // Setup map objects whiteSpaceElementsMap = createLookupTable('whitespace_elements', 'pre script noscript style textarea'); selfClosingElementsMap = createLookupTable('self_closing_elements', 'colgroup dd dt li option p td tfoot th thead tr'); shortEndedElementsMap = createLookupTable('short_ended_elements', 'area base basefont br col frame hr img input isindex link meta param embed source wbr'); boolAttrMap = createLookupTable('boolean_attributes', 'checked compact declare defer disabled ismap multiple nohref noresize noshade nowrap readonly selected autoplay loop controls'); nonEmptyElementsMap = createLookupTable('non_empty_elements', 'td th iframe video audio object', shortEndedElementsMap); textBlockElementsMap = createLookupTable('text_block_elements', 'h1 h2 h3 h4 h5 h6 p div address pre form ' + 'blockquote center dir fieldset header footer article section hgroup aside nav figure'); blockElementsMap = createLookupTable('block_elements', 'hr table tbody thead tfoot ' + 'th tr td li ol ul caption dl dt dd noscript menu isindex option datalist select optgroup', textBlockElementsMap); // Converts a wildcard expression string to a regexp for example *a will become /.*a/. function patternToRegExp(str) { return new RegExp('^' + str.replace(/([?+*])/g, '.$1') + '$'); }; // Parses the specified valid_elements string and adds to the current rules // This function is a bit hard to read since it's heavily optimized for speed function addValidElements(valid_elements) { var ei, el, ai, al, yl, matches, element, attr, attrData, elementName, attrName, attrType, attributes, attributesOrder, prefix, outputName, globalAttributes, globalAttributesOrder, transElement, key, childKey, value, elementRuleRegExp = /^([#+\-])?([^\[\/]+)(?:\/([^\[]+))?(?:\[([^\]]+)\])?$/, attrRuleRegExp = /^([!\-])?(\w+::\w+|[^=:<]+)?(?:([=:<])(.*))?$/, hasPatternsRegExp = /[*?+]/; if (valid_elements) { // Split valid elements into an array with rules valid_elements = split(valid_elements); if (elements['@']) { globalAttributes = elements['@'].attributes; globalAttributesOrder = elements['@'].attributesOrder; } // Loop all rules for (ei = 0, el = valid_elements.length; ei < el; ei++) { // Parse element rule matches = elementRuleRegExp.exec(valid_elements[ei]); if (matches) { // Setup local names for matches prefix = matches[1]; elementName = matches[2]; outputName = matches[3]; attrData = matches[4]; // Create new attributes and attributesOrder attributes = {}; attributesOrder = []; // Create the new element element = { attributes : attributes, attributesOrder : attributesOrder }; // Padd empty elements prefix if (prefix === '#') element.paddEmpty = true; // Remove empty elements prefix if (prefix === '-') element.removeEmpty = true; // Copy attributes from global rule into current rule if (globalAttributes) { for (key in globalAttributes) attributes[key] = globalAttributes[key]; attributesOrder.push.apply(attributesOrder, globalAttributesOrder); } // Attributes defined if (attrData) { attrData = split(attrData, '|'); for (ai = 0, al = attrData.length; ai < al; ai++) { matches = attrRuleRegExp.exec(attrData[ai]); if (matches) { attr = {}; attrType = matches[1]; attrName = matches[2].replace(/::/g, ':'); prefix = matches[3]; value = matches[4]; // Required if (attrType === '!') { element.attributesRequired = element.attributesRequired || []; element.attributesRequired.push(attrName); attr.required = true; } // Denied from global if (attrType === '-') { delete attributes[attrName]; attributesOrder.splice(tinymce.inArray(attributesOrder, attrName), 1); continue; } // Default value if (prefix) { // Default value if (prefix === '=') { element.attributesDefault = element.attributesDefault || []; element.attributesDefault.push({name: attrName, value: value}); attr.defaultValue = value; } // Forced value if (prefix === ':') { element.attributesForced = element.attributesForced || []; element.attributesForced.push({name: attrName, value: value}); attr.forcedValue = value; } // Required values if (prefix === '<') attr.validValues = makeMap(value, '?'); } // Check for attribute patterns if (hasPatternsRegExp.test(attrName)) { element.attributePatterns = element.attributePatterns || []; attr.pattern = patternToRegExp(attrName); element.attributePatterns.push(attr); } else { // Add attribute to order list if it doesn't already exist if (!attributes[attrName]) attributesOrder.push(attrName); attributes[attrName] = attr; } } } } // Global rule, store away these for later usage if (!globalAttributes && elementName == '@') { globalAttributes = attributes; globalAttributesOrder = attributesOrder; } // Handle substitute elements such as b/strong if (outputName) { element.outputName = elementName; elements[outputName] = element; } // Add pattern or exact element if (hasPatternsRegExp.test(elementName)) { element.pattern = patternToRegExp(elementName); patternElements.push(element); } else elements[elementName] = element; } } } }; function setValidElements(valid_elements) { elements = {}; patternElements = []; addValidElements(valid_elements); each(schemaItems, function(element, name) { children[name] = element.children; }); }; // Adds custom non HTML elements to the schema function addCustomElements(custom_elements) { var customElementRegExp = /^(~)?(.+)$/; if (custom_elements) { each(split(custom_elements), function(rule) { var matches = customElementRegExp.exec(rule), inline = matches[1] === '~', cloneName = inline ? 'span' : 'div', name = matches[2]; children[name] = children[cloneName]; customElementsMap[name] = cloneName; // If it's not marked as inline then add it to valid block elements if (!inline) { blockElementsMap[name.toUpperCase()] = {}; blockElementsMap[name] = {}; } // Add elements clone if needed if (!elements[name]) { elements[name] = elements[cloneName]; } // Add custom elements at span/div positions each(children, function(element, child) { if (element[cloneName]) element[name] = element[cloneName]; }); }); } }; // Adds valid children to the schema object function addValidChildren(valid_children) { var childRuleRegExp = /^([+\-]?)(\w+)\[([^\]]+)\]$/; if (valid_children) { each(split(valid_children), function(rule) { var matches = childRuleRegExp.exec(rule), parent, prefix; if (matches) { prefix = matches[1]; // Add/remove items from default if (prefix) parent = children[matches[2]]; else parent = children[matches[2]] = {'#comment' : {}}; parent = children[matches[2]]; each(split(matches[3], '|'), function(child) { if (prefix === '-') delete parent[child]; else parent[child] = {}; }); } }); } }; function getElementRule(name) { var element = elements[name], i; // Exact match found if (element) return element; // No exact match then try the patterns i = patternElements.length; while (i--) { element = patternElements[i]; if (element.pattern.test(name)) return element; } }; if (!settings.valid_elements) { // No valid elements defined then clone the elements from the schema spec each(schemaItems, function(element, name) { elements[name] = { attributes : element.attributes, attributesOrder : element.attributesOrder }; children[name] = element.children; }); // Switch these on HTML4 if (settings.schema != "html5") { each(split('strong/b,em/i'), function(item) { item = split(item, '/'); elements[item[1]].outputName = item[0]; }); } // Add default alt attribute for images elements.img.attributesDefault = [{name: 'alt', value: ''}]; // Remove these if they are empty by default each(split('ol,ul,sub,sup,blockquote,span,font,a,table,tbody,tr'), function(name) { if (elements[name]) { elements[name].removeEmpty = true; } }); // Padd these by default each(split('p,h1,h2,h3,h4,h5,h6,th,td,pre,div,address,caption'), function(name) { elements[name].paddEmpty = true; }); } else setValidElements(settings.valid_elements); addCustomElements(settings.custom_elements); addValidChildren(settings.valid_children); addValidElements(settings.extended_valid_elements); // Todo: Remove this when we fix list handling to be valid addValidChildren('+ol[ul|ol],+ul[ul|ol]'); // Delete invalid elements if (settings.invalid_elements) { tinymce.each(tinymce.explode(settings.invalid_elements), function(item) { if (elements[item]) delete elements[item]; }); } // If the user didn't allow span only allow internal spans if (!getElementRule('span')) addValidElements('span[!data-mce-type|*]'); /** * Name/value map object with valid parents and children to those parents. * * @example * children = { * div:{p:{}, h1:{}} * }; * @field children * @type {Object} */ self.children = children; /** * Name/value map object with valid styles for each element. * * @field styles * @type {Object} */ self.styles = validStyles; /** * Returns a map with boolean attributes. * * @method getBoolAttrs * @return {Object} Name/value lookup map for boolean attributes. */ self.getBoolAttrs = function() { return boolAttrMap; }; /** * Returns a map with block elements. * * @method getBlockElements * @return {Object} Name/value lookup map for block elements. */ self.getBlockElements = function() { return blockElementsMap; }; /** * Returns a map with text block elements. Such as: p,h1-h6,div,address * * @method getTextBlockElements * @return {Object} Name/value lookup map for block elements. */ self.getTextBlockElements = function() { return textBlockElementsMap; }; /** * Returns a map with short ended elements such as BR or IMG. * * @method getShortEndedElements * @return {Object} Name/value lookup map for short ended elements. */ self.getShortEndedElements = function() { return shortEndedElementsMap; }; /** * Returns a map with self closing tags such as <li>. * * @method getSelfClosingElements * @return {Object} Name/value lookup map for self closing tags elements. */ self.getSelfClosingElements = function() { return selfClosingElementsMap; }; /** * Returns a map with elements that should be treated as contents regardless if it has text * content in them or not such as TD, VIDEO or IMG. * * @method getNonEmptyElements * @return {Object} Name/value lookup map for non empty elements. */ self.getNonEmptyElements = function() { return nonEmptyElementsMap; }; /** * Returns a map with elements where white space is to be preserved like PRE or SCRIPT. * * @method getWhiteSpaceElements * @return {Object} Name/value lookup map for white space elements. */ self.getWhiteSpaceElements = function() { return whiteSpaceElementsMap; }; /** * Returns true/false if the specified element and it's child is valid or not * according to the schema. * * @method isValidChild * @param {String} name Element name to check for. * @param {String} child Element child to verify. * @return {Boolean} True/false if the element is a valid child of the specified parent. */ self.isValidChild = function(name, child) { var parent = children[name]; return !!(parent && parent[child]); }; /** * Returns true/false if the specified element name and optional attribute is * valid according to the schema. * * @method isValid * @param {String} name Name of element to check. * @param {String} attr Optional attribute name to check for. * @return {Boolean} True/false if the element and attribute is valid. */ self.isValid = function(name, attr) { var attrPatterns, i, rule = getElementRule(name); // Check if it's a valid element if (rule) { if (attr) { // Check if attribute name exists if (rule.attributes[attr]) { return true; } // Check if attribute matches a regexp pattern attrPatterns = rule.attributePatterns; if (attrPatterns) { i = attrPatterns.length; while (i--) { if (attrPatterns[i].pattern.test(name)) { return true; } } } } else { return true; } } // No match return false; }; /** * Returns true/false if the specified element is valid or not * according to the schema. * * @method getElementRule * @param {String} name Element name to check for. * @return {Object} Element object or undefined if the element isn't valid. */ self.getElementRule = getElementRule; /** * Returns an map object of all custom elements. * * @method getCustomElements * @return {Object} Name/value map object of all custom elements. */ self.getCustomElements = function() { return customElementsMap; }; /** * Parses a valid elements string and adds it to the schema. The valid elements format is for example "element[attr=default|otherattr]". * Existing rules will be replaced with the ones specified, so this extends the schema. * * @method addValidElements * @param {String} valid_elements String in the valid elements format to be parsed. */ self.addValidElements = addValidElements; /** * Parses a valid elements string and sets it to the schema. The valid elements format is for example "element[attr=default|otherattr]". * Existing rules will be replaced with the ones specified, so this extends the schema. * * @method setValidElements * @param {String} valid_elements String in the valid elements format to be parsed. */ self.setValidElements = setValidElements; /** * Adds custom non HTML elements to the schema. * * @method addCustomElements * @param {String} custom_elements Comma separated list of custom elements to add. */ self.addCustomElements = addCustomElements; /** * Parses a valid children string and adds them to the schema structure. The valid children format is for example: "element[child1|child2]". * * @method addValidChildren * @param {String} valid_children Valid children elements string to parse */ self.addValidChildren = addValidChildren; self.elements = elements; }; })(tinymce);
JavaScript
/** * editable_selects.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ var TinyMCE_EditableSelects = { editSelectElm : null, init : function() { var nl = document.getElementsByTagName("select"), i, d = document, o; for (i=0; i<nl.length; i++) { if (nl[i].className.indexOf('mceEditableSelect') != -1) { o = new Option(tinyMCEPopup.editor.translate('value'), '__mce_add_custom__'); o.className = 'mceAddSelectValue'; nl[i].options[nl[i].options.length] = o; nl[i].onchange = TinyMCE_EditableSelects.onChangeEditableSelect; } } }, onChangeEditableSelect : function(e) { var d = document, ne, se = window.event ? window.event.srcElement : e.target; if (se.options[se.selectedIndex].value == '__mce_add_custom__') { ne = d.createElement("input"); ne.id = se.id + "_custom"; ne.name = se.name + "_custom"; ne.type = "text"; ne.style.width = se.offsetWidth + 'px'; se.parentNode.insertBefore(ne, se); se.style.display = 'none'; ne.focus(); ne.onblur = TinyMCE_EditableSelects.onBlurEditableSelectInput; ne.onkeydown = TinyMCE_EditableSelects.onKeyDown; TinyMCE_EditableSelects.editSelectElm = se; } }, onBlurEditableSelectInput : function() { var se = TinyMCE_EditableSelects.editSelectElm; if (se) { if (se.previousSibling.value != '') { addSelectValue(document.forms[0], se.id, se.previousSibling.value, se.previousSibling.value); selectByValue(document.forms[0], se.id, se.previousSibling.value); } else selectByValue(document.forms[0], se.id, ''); se.style.display = 'inline'; se.parentNode.removeChild(se.previousSibling); TinyMCE_EditableSelects.editSelectElm = null; } }, onKeyDown : function(e) { e = e || window.event; if (e.keyCode == 13) TinyMCE_EditableSelects.onBlurEditableSelectInput(); } };
JavaScript
/** * mctabs.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ function MCTabs() { this.settings = []; this.onChange = tinyMCEPopup.editor.windowManager.createInstance('tinymce.util.Dispatcher'); }; MCTabs.prototype.init = function(settings) { this.settings = settings; }; MCTabs.prototype.getParam = function(name, default_value) { var value = null; value = (typeof(this.settings[name]) == "undefined") ? default_value : this.settings[name]; // Fix bool values if (value == "true" || value == "false") return (value == "true"); return value; }; MCTabs.prototype.showTab =function(tab){ tab.className = 'current'; tab.setAttribute("aria-selected", true); tab.setAttribute("aria-expanded", true); tab.tabIndex = 0; }; MCTabs.prototype.hideTab =function(tab){ var t=this; tab.className = ''; tab.setAttribute("aria-selected", false); tab.setAttribute("aria-expanded", false); tab.tabIndex = -1; }; MCTabs.prototype.showPanel = function(panel) { panel.className = 'current'; panel.setAttribute("aria-hidden", false); }; MCTabs.prototype.hidePanel = function(panel) { panel.className = 'panel'; panel.setAttribute("aria-hidden", true); }; MCTabs.prototype.getPanelForTab = function(tabElm) { return tinyMCEPopup.dom.getAttrib(tabElm, "aria-controls"); }; MCTabs.prototype.displayTab = function(tab_id, panel_id, avoid_focus) { var panelElm, panelContainerElm, tabElm, tabContainerElm, selectionClass, nodes, i, t = this; tabElm = document.getElementById(tab_id); if (panel_id === undefined) { panel_id = t.getPanelForTab(tabElm); } panelElm= document.getElementById(panel_id); panelContainerElm = panelElm ? panelElm.parentNode : null; tabContainerElm = tabElm ? tabElm.parentNode : null; selectionClass = t.getParam('selection_class', 'current'); if (tabElm && tabContainerElm) { nodes = tabContainerElm.childNodes; // Hide all other tabs for (i = 0; i < nodes.length; i++) { if (nodes[i].nodeName == "LI") { t.hideTab(nodes[i]); } } // Show selected tab t.showTab(tabElm); } if (panelElm && panelContainerElm) { nodes = panelContainerElm.childNodes; // Hide all other panels for (i = 0; i < nodes.length; i++) { if (nodes[i].nodeName == "DIV") t.hidePanel(nodes[i]); } if (!avoid_focus) { tabElm.focus(); } // Show selected panel t.showPanel(panelElm); } }; MCTabs.prototype.getAnchor = function() { var pos, url = document.location.href; if ((pos = url.lastIndexOf('#')) != -1) return url.substring(pos + 1); return ""; }; //Global instance var mcTabs = new MCTabs(); tinyMCEPopup.onInit.add(function() { var tinymce = tinyMCEPopup.getWin().tinymce, dom = tinyMCEPopup.dom, each = tinymce.each; each(dom.select('div.tabs'), function(tabContainerElm) { var keyNav; dom.setAttrib(tabContainerElm, "role", "tablist"); var items = tinyMCEPopup.dom.select('li', tabContainerElm); var action = function(id) { mcTabs.displayTab(id, mcTabs.getPanelForTab(id)); mcTabs.onChange.dispatch(id); }; each(items, function(item) { dom.setAttrib(item, 'role', 'tab'); dom.bind(item, 'click', function(evt) { action(item.id); }); }); dom.bind(dom.getRoot(), 'keydown', function(evt) { if (evt.keyCode === 9 && evt.ctrlKey && !evt.altKey) { // Tab keyNav.moveFocus(evt.shiftKey ? -1 : 1); tinymce.dom.Event.cancel(evt); } }); each(dom.select('a', tabContainerElm), function(a) { dom.setAttrib(a, 'tabindex', '-1'); }); keyNav = tinyMCEPopup.editor.windowManager.createInstance('tinymce.ui.KeyboardNavigation', { root: tabContainerElm, items: items, onAction: action, actOnFocus: true, enableLeftRight: true, enableUpDown: true }, tinyMCEPopup.dom); }); });
JavaScript
/** * validate.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ /** // String validation: if (!Validator.isEmail('myemail')) alert('Invalid email.'); // Form validation: var f = document.forms['myform']; if (!Validator.isEmail(f.myemail)) alert('Invalid email.'); */ var Validator = { isEmail : function(s) { return this.test(s, '^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+@[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$'); }, isAbsUrl : function(s) { return this.test(s, '^(news|telnet|nttp|file|http|ftp|https)://[-A-Za-z0-9\\.]+\\/?.*$'); }, isSize : function(s) { return this.test(s, '^[0-9.]+(%|in|cm|mm|em|ex|pt|pc|px)?$'); }, isId : function(s) { return this.test(s, '^[A-Za-z_]([A-Za-z0-9_])*$'); }, isEmpty : function(s) { var nl, i; if (s.nodeName == 'SELECT' && s.selectedIndex < 1) return true; if (s.type == 'checkbox' && !s.checked) return true; if (s.type == 'radio') { for (i=0, nl = s.form.elements; i<nl.length; i++) { if (nl[i].type == "radio" && nl[i].name == s.name && nl[i].checked) return false; } return true; } return new RegExp('^\\s*$').test(s.nodeType == 1 ? s.value : s); }, isNumber : function(s, d) { return !isNaN(s.nodeType == 1 ? s.value : s) && (!d || !this.test(s, '^-?[0-9]*\\.[0-9]*$')); }, test : function(s, p) { s = s.nodeType == 1 ? s.value : s; return s == '' || new RegExp(p).test(s); } }; var AutoValidator = { settings : { id_cls : 'id', int_cls : 'int', url_cls : 'url', number_cls : 'number', email_cls : 'email', size_cls : 'size', required_cls : 'required', invalid_cls : 'invalid', min_cls : 'min', max_cls : 'max' }, init : function(s) { var n; for (n in s) this.settings[n] = s[n]; }, validate : function(f) { var i, nl, s = this.settings, c = 0; nl = this.tags(f, 'label'); for (i=0; i<nl.length; i++) { this.removeClass(nl[i], s.invalid_cls); nl[i].setAttribute('aria-invalid', false); } c += this.validateElms(f, 'input'); c += this.validateElms(f, 'select'); c += this.validateElms(f, 'textarea'); return c == 3; }, invalidate : function(n) { this.mark(n.form, n); }, getErrorMessages : function(f) { var nl, i, s = this.settings, field, msg, values, messages = [], ed = tinyMCEPopup.editor; nl = this.tags(f, "label"); for (i=0; i<nl.length; i++) { if (this.hasClass(nl[i], s.invalid_cls)) { field = document.getElementById(nl[i].getAttribute("for")); values = { field: nl[i].textContent }; if (this.hasClass(field, s.min_cls, true)) { message = ed.getLang('invalid_data_min'); values.min = this.getNum(field, s.min_cls); } else if (this.hasClass(field, s.number_cls)) { message = ed.getLang('invalid_data_number'); } else if (this.hasClass(field, s.size_cls)) { message = ed.getLang('invalid_data_size'); } else { message = ed.getLang('invalid_data'); } message = message.replace(/{\#([^}]+)\}/g, function(a, b) { return values[b] || '{#' + b + '}'; }); messages.push(message); } } return messages; }, reset : function(e) { var t = ['label', 'input', 'select', 'textarea']; var i, j, nl, s = this.settings; if (e == null) return; for (i=0; i<t.length; i++) { nl = this.tags(e.form ? e.form : e, t[i]); for (j=0; j<nl.length; j++) { this.removeClass(nl[j], s.invalid_cls); nl[j].setAttribute('aria-invalid', false); } } }, validateElms : function(f, e) { var nl, i, n, s = this.settings, st = true, va = Validator, v; nl = this.tags(f, e); for (i=0; i<nl.length; i++) { n = nl[i]; this.removeClass(n, s.invalid_cls); if (this.hasClass(n, s.required_cls) && va.isEmpty(n)) st = this.mark(f, n); if (this.hasClass(n, s.number_cls) && !va.isNumber(n)) st = this.mark(f, n); if (this.hasClass(n, s.int_cls) && !va.isNumber(n, true)) st = this.mark(f, n); if (this.hasClass(n, s.url_cls) && !va.isAbsUrl(n)) st = this.mark(f, n); if (this.hasClass(n, s.email_cls) && !va.isEmail(n)) st = this.mark(f, n); if (this.hasClass(n, s.size_cls) && !va.isSize(n)) st = this.mark(f, n); if (this.hasClass(n, s.id_cls) && !va.isId(n)) st = this.mark(f, n); if (this.hasClass(n, s.min_cls, true)) { v = this.getNum(n, s.min_cls); if (isNaN(v) || parseInt(n.value) < parseInt(v)) st = this.mark(f, n); } if (this.hasClass(n, s.max_cls, true)) { v = this.getNum(n, s.max_cls); if (isNaN(v) || parseInt(n.value) > parseInt(v)) st = this.mark(f, n); } } return st; }, hasClass : function(n, c, d) { return new RegExp('\\b' + c + (d ? '[0-9]+' : '') + '\\b', 'g').test(n.className); }, getNum : function(n, c) { c = n.className.match(new RegExp('\\b' + c + '([0-9]+)\\b', 'g'))[0]; c = c.replace(/[^0-9]/g, ''); return c; }, addClass : function(n, c, b) { var o = this.removeClass(n, c); n.className = b ? c + (o != '' ? (' ' + o) : '') : (o != '' ? (o + ' ') : '') + c; }, removeClass : function(n, c) { c = n.className.replace(new RegExp("(^|\\s+)" + c + "(\\s+|$)"), ' '); return n.className = c != ' ' ? c : ''; }, tags : function(f, s) { return f.getElementsByTagName(s); }, mark : function(f, n) { var s = this.settings; this.addClass(n, s.invalid_cls); n.setAttribute('aria-invalid', 'true'); this.markLabels(f, n, s.invalid_cls); return false; }, markLabels : function(f, n, ic) { var nl, i; nl = this.tags(f, "label"); for (i=0; i<nl.length; i++) { if (nl[i].getAttribute("for") == n.id || nl[i].htmlFor == n.id) this.addClass(nl[i], ic); } return null; } };
JavaScript
/** * form_utils.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ var themeBaseURL = tinyMCEPopup.editor.baseURI.toAbsolute('themes/' + tinyMCEPopup.getParam("theme")); function getColorPickerHTML(id, target_form_element) { var h = "", dom = tinyMCEPopup.dom; if (label = dom.select('label[for=' + target_form_element + ']')[0]) { label.id = label.id || dom.uniqueId(); } h += '<a role="button" aria-labelledby="' + id + '_label" id="' + id + '_link" href="javascript:;" onclick="tinyMCEPopup.pickColor(event,\'' + target_form_element +'\');" onmousedown="return false;" class="pickcolor">'; h += '<span id="' + id + '" title="' + tinyMCEPopup.getLang('browse') + '">&nbsp;<span id="' + id + '_label" class="mceVoiceLabel mceIconOnly" style="display:none;">' + tinyMCEPopup.getLang('browse') + '</span></span></a>'; return h; } function updateColor(img_id, form_element_id) { document.getElementById(img_id).style.backgroundColor = document.forms[0].elements[form_element_id].value; } function setBrowserDisabled(id, state) { var img = document.getElementById(id); var lnk = document.getElementById(id + "_link"); if (lnk) { if (state) { lnk.setAttribute("realhref", lnk.getAttribute("href")); lnk.removeAttribute("href"); tinyMCEPopup.dom.addClass(img, 'disabled'); } else { if (lnk.getAttribute("realhref")) lnk.setAttribute("href", lnk.getAttribute("realhref")); tinyMCEPopup.dom.removeClass(img, 'disabled'); } } } function getBrowserHTML(id, target_form_element, type, prefix) { var option = prefix + "_" + type + "_browser_callback", cb, html; cb = tinyMCEPopup.getParam(option, tinyMCEPopup.getParam("file_browser_callback")); if (!cb) return ""; html = ""; html += '<a id="' + id + '_link" href="javascript:openBrowser(\'' + id + '\',\'' + target_form_element + '\', \'' + type + '\',\'' + option + '\');" onmousedown="return false;" class="browse">'; html += '<span id="' + id + '" title="' + tinyMCEPopup.getLang('browse') + '">&nbsp;</span></a>'; return html; } function openBrowser(img_id, target_form_element, type, option) { var img = document.getElementById(img_id); if (img.className != "mceButtonDisabled") tinyMCEPopup.openBrowser(target_form_element, type, option); } function selectByValue(form_obj, field_name, value, add_custom, ignore_case) { if (!form_obj || !form_obj.elements[field_name]) return; if (!value) value = ""; var sel = form_obj.elements[field_name]; var found = false; for (var i=0; i<sel.options.length; i++) { var option = sel.options[i]; if (option.value == value || (ignore_case && option.value.toLowerCase() == value.toLowerCase())) { option.selected = true; found = true; } else option.selected = false; } if (!found && add_custom && value != '') { var option = new Option(value, value); option.selected = true; sel.options[sel.options.length] = option; sel.selectedIndex = sel.options.length - 1; } return found; } function getSelectValue(form_obj, field_name) { var elm = form_obj.elements[field_name]; if (elm == null || elm.options == null || elm.selectedIndex === -1) return ""; return elm.options[elm.selectedIndex].value; } function addSelectValue(form_obj, field_name, name, value) { var s = form_obj.elements[field_name]; var o = new Option(name, value); s.options[s.options.length] = o; } function addClassesToList(list_id, specific_option) { // Setup class droplist var styleSelectElm = document.getElementById(list_id); var styles = tinyMCEPopup.getParam('theme_advanced_styles', false); styles = tinyMCEPopup.getParam(specific_option, styles); if (styles) { var stylesAr = styles.split(';'); for (var i=0; i<stylesAr.length; i++) { if (stylesAr != "") { var key, value; key = stylesAr[i].split('=')[0]; value = stylesAr[i].split('=')[1]; styleSelectElm.options[styleSelectElm.length] = new Option(key, value); } } } else { tinymce.each(tinyMCEPopup.editor.dom.getClasses(), function(o) { styleSelectElm.options[styleSelectElm.length] = new Option(o.title || o['class'], o['class']); }); } } function isVisible(element_id) { var elm = document.getElementById(element_id); return elm && elm.style.display != "none"; } function convertRGBToHex(col) { var re = new RegExp("rgb\\s*\\(\\s*([0-9]+).*,\\s*([0-9]+).*,\\s*([0-9]+).*\\)", "gi"); var rgb = col.replace(re, "$1,$2,$3").split(','); if (rgb.length == 3) { r = parseInt(rgb[0]).toString(16); g = parseInt(rgb[1]).toString(16); b = parseInt(rgb[2]).toString(16); r = r.length == 1 ? '0' + r : r; g = g.length == 1 ? '0' + g : g; b = b.length == 1 ? '0' + b : b; return "#" + r + g + b; } return col; } function convertHexToRGB(col) { if (col.indexOf('#') != -1) { col = col.replace(new RegExp('[^0-9A-F]', 'gi'), ''); r = parseInt(col.substring(0, 2), 16); g = parseInt(col.substring(2, 4), 16); b = parseInt(col.substring(4, 6), 16); return "rgb(" + r + "," + g + "," + b + ")"; } return col; } function trimSize(size) { return size.replace(/([0-9\.]+)(px|%|in|cm|mm|em|ex|pt|pc)/i, '$1$2'); } function getCSSSize(size) { size = trimSize(size); if (size == "") return ""; // Add px if (/^[0-9]+$/.test(size)) size += 'px'; // Sanity check, IE doesn't like broken values else if (!(/^[0-9\.]+(px|%|in|cm|mm|em|ex|pt|pc)$/i.test(size))) return ""; return size; } function getStyle(elm, attrib, style) { var val = tinyMCEPopup.dom.getAttrib(elm, attrib); if (val != '') return '' + val; if (typeof(style) == 'undefined') style = attrib; return tinyMCEPopup.dom.getStyle(elm, style); }
JavaScript
tinyMCE.addI18n({en:{ common:{ edit_confirm:"Do you want to use the WYSIWYG mode for this textarea?", apply:"Apply", insert:"Insert", update:"Update", cancel:"Cancel", close:"Close", browse:"Browse", class_name:"Class", not_set:"-- Not set --", clipboard_msg:"Copy/Cut/Paste is not available in Mozilla and Firefox.", clipboard_no_support:"Currently not supported by your browser, use keyboard shortcuts instead.", popup_blocked:"Sorry, but we have noticed that your popup-blocker has disabled a window that provides application functionality. You will need to disable popup blocking on this site in order to fully utilize this tool.", invalid_data:"ERROR: Invalid values entered, these are marked in red.", invalid_data_number:"{#field} must be a number", invalid_data_min:"{#field} must be a number greater than {#min}", invalid_data_size:"{#field} must be a number or percentage", more_colors:"More colors" }, colors:{ "000000":"Black", "993300":"Burnt orange", "333300":"Dark olive", "003300":"Dark green", "003366":"Dark azure", "000080":"Navy Blue", "333399":"Indigo", "333333":"Very dark gray", "800000":"Maroon", "FF6600":"Orange", "808000":"Olive", "008000":"Green", "008080":"Teal", "0000FF":"Blue", "666699":"Grayish blue", "808080":"Gray", "FF0000":"Red", "FF9900":"Amber", "99CC00":"Yellow green", "339966":"Sea green", "33CCCC":"Turquoise", "3366FF":"Royal blue", "800080":"Purple", "999999":"Medium gray", "FF00FF":"Magenta", "FFCC00":"Gold", "FFFF00":"Yellow", "00FF00":"Lime", "00FFFF":"Aqua", "00CCFF":"Sky blue", "993366":"Brown", "C0C0C0":"Silver", "FF99CC":"Pink", "FFCC99":"Peach", "FFFF99":"Light yellow", "CCFFCC":"Pale green", "CCFFFF":"Pale cyan", "99CCFF":"Light sky blue", "CC99FF":"Plum", "FFFFFF":"White" }, contextmenu:{ align:"Alignment", left:"Left", center:"Center", right:"Right", full:"Full" }, insertdatetime:{ date_fmt:"%Y-%m-%d", time_fmt:"%H:%M:%S", insertdate_desc:"Insert date", inserttime_desc:"Insert time", months_long:"January,February,March,April,May,June,July,August,September,October,November,December", months_short:"Jan_January_abbreviation,Feb_February_abbreviation,Mar_March_abbreviation,Apr_April_abbreviation,May_May_abbreviation,Jun_June_abbreviation,Jul_July_abbreviation,Aug_August_abbreviation,Sep_September_abbreviation,Oct_October_abbreviation,Nov_November_abbreviation,Dec_December_abbreviation", day_long:"Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday", day_short:"Sun,Mon,Tue,Wed,Thu,Fri,Sat" }, print:{ print_desc:"Print" }, preview:{ preview_desc:"Preview" }, directionality:{ ltr_desc:"Direction left to right", rtl_desc:"Direction right to left" }, layer:{ insertlayer_desc:"Insert new layer", forward_desc:"Move forward", backward_desc:"Move backward", absolute_desc:"Toggle absolute positioning", content:"New layer..." }, save:{ save_desc:"Save", cancel_desc:"Cancel all changes" }, nonbreaking:{ nonbreaking_desc:"Insert non-breaking space character" }, iespell:{ iespell_desc:"Run spell checking", download:"ieSpell not detected. Do you want to install it now?" }, advhr:{ advhr_desc:"Horizontal rule" }, emotions:{ emotions_desc:"Emotions" }, searchreplace:{ search_desc:"Find", replace_desc:"Find/Replace" }, advimage:{ image_desc:"Insert/edit image" }, advlink:{ link_desc:"Insert/edit link" }, xhtmlxtras:{ cite_desc:"Citation", abbr_desc:"Abbreviation", acronym_desc:"Acronym", del_desc:"Deletion", ins_desc:"Insertion", attribs_desc:"Insert/Edit Attributes" }, style:{ desc:"Edit CSS Style" }, paste:{ paste_text_desc:"Paste as Plain Text", paste_word_desc:"Paste from Word", selectall_desc:"Select All", plaintext_mode_sticky:"Paste is now in plain text mode. Click again to toggle back to regular paste mode. After you paste something you will be returned to regular paste mode.", plaintext_mode:"Paste is now in plain text mode. Click again to toggle back to regular paste mode." }, paste_dlg:{ text_title:"Use CTRL + V on your keyboard to paste the text into the window.", text_linebreaks:"Keep linebreaks", word_title:"Use CTRL + V on your keyboard to paste the text into the window." }, table:{ desc:"Inserts a new table", row_before_desc:"Insert row before", row_after_desc:"Insert row after", delete_row_desc:"Delete row", col_before_desc:"Insert column before", col_after_desc:"Insert column after", delete_col_desc:"Remove column", split_cells_desc:"Split merged table cells", merge_cells_desc:"Merge table cells", row_desc:"Table row properties", cell_desc:"Table cell properties", props_desc:"Table properties", paste_row_before_desc:"Paste table row before", paste_row_after_desc:"Paste table row after", cut_row_desc:"Cut table row", copy_row_desc:"Copy table row", del:"Delete table", row:"Row", col:"Column", cell:"Cell" }, autosave:{ unload_msg:"The changes you made will be lost if you navigate away from this page." }, fullscreen:{ desc:"Toggle fullscreen mode (Alt + Shift + G)" }, media:{ desc:"Insert / edit embedded media", edit:"Edit embedded media" }, fullpage:{ desc:"Document properties" }, template:{ desc:"Insert predefined template content" }, visualchars:{ desc:"Visual control characters on/off." }, spellchecker:{ desc:"Toggle spellchecker (Alt + Shift + N)", menu:"Spellchecker settings", ignore_word:"Ignore word", ignore_words:"Ignore all", langs:"Languages", wait:"Please wait...", sug:"Suggestions", no_sug:"No suggestions", no_mpell:"No misspellings found.", learn_word:"Learn word" }, pagebreak:{ desc:"Insert Page Break" }, advlist:{ types:"Types", def:"Default", lower_alpha:"Lower alpha", lower_greek:"Lower greek", lower_roman:"Lower roman", upper_alpha:"Upper alpha", upper_roman:"Upper roman", circle:"Circle", disc:"Disc", square:"Square" }, aria:{ rich_text_area:"Rich Text Area" }, wordcount:{ words:"Words: " } }}); tinyMCE.addI18n("en.advanced",{ style_select:"Styles", font_size:"Font size", fontdefault:"Font family", block:"Format", paragraph:"Paragraph", div:"Div", address:"Address", pre:"Preformatted", h1:"Heading 1", h2:"Heading 2", h3:"Heading 3", h4:"Heading 4", h5:"Heading 5", h6:"Heading 6", blockquote:"Blockquote", code:"Code", samp:"Code sample", dt:"Definition term ", dd:"Definition description", bold_desc:"Bold (Ctrl + B)", italic_desc:"Italic (Ctrl + I)", underline_desc:"Underline", striketrough_desc:"Strikethrough (Alt + Shift + D)", justifyleft_desc:"Align Left (Alt + Shift + L)", justifycenter_desc:"Align Center (Alt + Shift + C)", justifyright_desc:"Align Right (Alt + Shift + R)", justifyfull_desc:"Align Full (Alt + Shift + J)", bullist_desc:"Unordered list (Alt + Shift + U)", numlist_desc:"Ordered list (Alt + Shift + O)", outdent_desc:"Outdent", indent_desc:"Indent", undo_desc:"Undo (Ctrl + Z)", redo_desc:"Redo (Ctrl + Y)", link_desc:"Insert/edit link (Alt + Shift + A)", unlink_desc:"Unlink (Alt + Shift + S)", image_desc:"Insert/edit image (Alt + Shift + M)", cleanup_desc:"Cleanup messy code", code_desc:"Edit HTML Source", sub_desc:"Subscript", sup_desc:"Superscript", hr_desc:"Insert horizontal ruler", removeformat_desc:"Remove formatting", forecolor_desc:"Select text color", backcolor_desc:"Select background color", charmap_desc:"Insert custom character", visualaid_desc:"Toggle guidelines/invisible elements", anchor_desc:"Insert/edit anchor", cut_desc:"Cut", copy_desc:"Copy", paste_desc:"Paste", image_props_desc:"Image properties", newdocument_desc:"New document", help_desc:"Help", blockquote_desc:"Blockquote (Alt + Shift + Q)", clipboard_msg:"Copy/Cut/Paste is not available in Mozilla and Firefox.", path:"Path", newdocument:"Are you sure you want to clear all contents?", toolbar_focus:"Jump to tool buttons - Alt+Q, Jump to editor - Alt-Z, Jump to element path - Alt-X", more_colors:"More colors", shortcuts_desc:"Accessibility Help", help_shortcut:" Press ALT F10 for toolbar. Press ALT 0 for help.", rich_text_area:"Rich Text Area", toolbar:"Toolbar" }); tinyMCE.addI18n("en.advanced_dlg",{ about_title:"About TinyMCE", about_general:"About", about_help:"Help", about_license:"License", about_plugins:"Plugins", about_plugin:"Plugin", about_author:"Author", about_version:"Version", about_loaded:"Loaded plugins", anchor_title:"Insert/edit anchor", anchor_name:"Anchor name", code_title:"HTML Source Editor", code_wordwrap:"Word wrap", colorpicker_title:"Select a color", colorpicker_picker_tab:"Picker", colorpicker_picker_title:"Color picker", colorpicker_palette_tab:"Palette", colorpicker_palette_title:"Palette colors", colorpicker_named_tab:"Named", colorpicker_named_title:"Named colors", colorpicker_color:"Color:", colorpicker_name:"Name:", charmap_title:"Select custom character", charmap_usage:"Use left and right arrows to navigate.", image_title:"Insert/edit image", image_src:"Image URL", image_alt:"Image description", image_list:"Image list", image_border:"Border", image_dimensions:"Dimensions", image_vspace:"Vertical space", image_hspace:"Horizontal space", image_align:"Alignment", image_align_baseline:"Baseline", image_align_top:"Top", image_align_middle:"Middle", image_align_bottom:"Bottom", image_align_texttop:"Text top", image_align_textbottom:"Text bottom", image_align_left:"Left", image_align_right:"Right", link_title:"Insert/edit link", link_url:"Link URL", link_target:"Target", link_target_same:"Open link in the same window", link_target_blank:"Open link in a new window", link_titlefield:"Title", link_is_email:"The URL you entered seems to be an email address, do you want to add the required mailto: prefix?", link_is_external:"The URL you entered seems to external link, do you want to add the required http:// prefix?", link_list:"Link list", accessibility_help:"Accessibility Help", accessibility_usage_title:"General Usage" }); tinyMCE.addI18n("en.media_dlg",{ title:"Insert / edit embedded media", general:"General", advanced:"Advanced", file:"File/URL", list:"List", size:"Dimensions", preview:"Preview", constrain_proportions:"Constrain proportions", type:"Type", id:"Id", name:"Name", class_name:"Class", vspace:"V-Space", hspace:"H-Space", play:"Auto play", loop:"Loop", menu:"Show menu", quality:"Quality", scale:"Scale", align:"Align", salign:"SAlign", wmode:"WMode", bgcolor:"Background", base:"Base", flashvars:"Flashvars", liveconnect:"SWLiveConnect", autohref:"AutoHREF", cache:"Cache", hidden:"Hidden", controller:"Controller", kioskmode:"Kiosk mode", playeveryframe:"Play every frame", targetcache:"Target cache", correction:"No correction", enablejavascript:"Enable JavaScript", starttime:"Start time", endtime:"End time", href:"href", qtsrcchokespeed:"Choke speed", target:"Target", volume:"Volume", autostart:"Auto start", enabled:"Enabled", fullscreen:"Fullscreen", invokeurls:"Invoke URLs", mute:"Mute", stretchtofit:"Stretch to fit", windowlessvideo:"Windowless video", balance:"Balance", baseurl:"Base URL", captioningid:"Captioning id", currentmarker:"Current marker", currentposition:"Current position", defaultframe:"Default frame", playcount:"Play count", rate:"Rate", uimode:"UI Mode", flash_options:"Flash options", qt_options:"QuickTime options", wmp_options:"Windows media player options", rmp_options:"Real media player options", shockwave_options:"Shockwave options", autogotourl:"Auto goto URL", center:"Center", imagestatus:"Image status", maintainaspect:"Maintain aspect", nojava:"No java", prefetch:"Prefetch", shuffle:"Shuffle", console:"Console", numloop:"Num loops", controls:"Controls", scriptcallbacks:"Script callbacks", swstretchstyle:"Stretch style", swstretchhalign:"Stretch H-Align", swstretchvalign:"Stretch V-Align", sound:"Sound", progress:"Progress", qtsrc:"QT Src", qt_stream_warn:"Streamed rtsp resources should be added to the QT Src field under the advanced tab.", align_top:"Top", align_right:"Right", align_bottom:"Bottom", align_left:"Left", align_center:"Center", align_top_left:"Top left", align_top_right:"Top right", align_bottom_left:"Bottom left", align_bottom_right:"Bottom right", flv_options:"Flash video options", flv_scalemode:"Scale mode", flv_buffer:"Buffer", flv_startimage:"Start image", flv_starttime:"Start time", flv_defaultvolume:"Default volume", flv_hiddengui:"Hidden GUI", flv_autostart:"Auto start", flv_loop:"Loop", flv_showscalemodes:"Show scale modes", flv_smoothvideo:"Smooth video", flv_jscallback:"JS Callback", html5_video_options:"HTML5 Video Options", altsource1:"Alternative source 1", altsource2:"Alternative source 2", preload:"Preload", poster:"Poster", source:"Source" }); tinyMCE.addI18n("en.wordpress",{ wp_adv_desc:"Show/Hide Kitchen Sink (Alt + Shift + Z)", wp_more_desc:"Insert More Tag (Alt + Shift + T)", wp_page_desc:"Insert Page break (Alt + Shift + P)", wp_help_desc:"Help (Alt + Shift + H)", wp_more_alt:"More...", wp_page_alt:"Next page...", add_media:"Add Media", add_image:"Add an Image", add_video:"Add Video", add_audio:"Add Audio", editgallery:"Edit Gallery", delgallery:"Delete Gallery", wp_fullscreen_desc:"Distraction Free Writing mode (Alt + Shift + W)" }); tinyMCE.addI18n("en.wpeditimage",{ edit_img:"Edit Image", del_img:"Delete Image", adv_settings:"Advanced Settings", none:"None", size:"Size", thumbnail:"Thumbnail", medium:"Medium", full_size:"Full Size", current_link:"Current Link", link_to_img:"Link to Image", link_help:"Enter a link URL or click above for presets.", adv_img_settings:"Advanced Image Settings", source:"Source", width:"Width", height:"Height", orig_size:"Original Size", css:"CSS Class", adv_link_settings:"Advanced Link Settings", link_rel:"Link Rel", height:"Height", orig_size:"Original Size", css:"CSS Class", s60:"60%", s70:"70%", s80:"80%", s90:"90%", s100:"100%", s110:"110%", s120:"120%", s130:"130%", img_title:"Title", caption:"Caption", alt:"Alternative Text" });
JavaScript
(function($){ $.ui.dialog.prototype.options.closeOnEscape = false; $.widget('wp.wpdialog', $.ui.dialog, { // Work around a bug in jQuery UI 1.9.1. // http://bugs.jqueryui.com/ticket/8805 widgetEventPrefix: 'wpdialog', open: function() { var ed; // Initialize tinyMCEPopup if it exists and the editor is active. if ( tinyMCEPopup && typeof tinyMCE != 'undefined' && ( ed = tinyMCE.activeEditor ) && !ed.isHidden() ) { tinyMCEPopup.init(); } // Add beforeOpen event. if ( this.isOpen() || false === this._trigger('beforeOpen') ) { return; } // Open the dialog. this._super(); // WebKit leaves focus in the TinyMCE editor unless we shift focus. this.element.focus(); this._trigger('refresh'); } }); })(jQuery);
JavaScript
/** * popup.js * * An altered version of tinyMCEPopup to work in the same window as tinymce. * * ------------------------------------------------------------------ * * Copyright 2009, Moxiecode Systems AB * Released under LGPL * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ // Some global instances /** * TinyMCE popup/dialog helper class. This gives you easy access to the * parent editor instance and a bunch of other things. It's higly recommended * that you load this script into your dialogs. * * @static * @class tinyMCEPopup */ var tinyMCEPopup = { /** * Initializes the popup this will be called automatically. * * @method init */ init : function() { var t = this, w, ti; // Find window & API w = t.getWin(); tinymce = w.tinymce; tinyMCE = w.tinyMCE; t.editor = tinymce.EditorManager.activeEditor; t.params = t.editor.windowManager.params; t.features = t.editor.windowManager.features; t.dom = tinymce.dom; // Setup on init listeners t.listeners = []; t.onInit = { add : function(f, s) { t.listeners.push({func : f, scope : s}); } }; t.isWindow = false; t.id = t.features.id; t.editor.windowManager.onOpen.dispatch(t.editor.windowManager, window); }, /** * Returns the reference to the parent window that opened the dialog. * * @method getWin * @return {Window} Reference to the parent window that opened the dialog. */ getWin : function() { return window; }, /** * Returns a window argument/parameter by name. * * @method getWindowArg * @param {String} n Name of the window argument to retrieve. * @param {String} dv Optional default value to return. * @return {String} Argument value or default value if it wasn't found. */ getWindowArg : function(n, dv) { var v = this.params[n]; return tinymce.is(v) ? v : dv; }, /** * Returns a editor parameter/config option value. * * @method getParam * @param {String} n Name of the editor config option to retrieve. * @param {String} dv Optional default value to return. * @return {String} Parameter value or default value if it wasn't found. */ getParam : function(n, dv) { return this.editor.getParam(n, dv); }, /** * Returns a language item by key. * * @method getLang * @param {String} n Language item like mydialog.something. * @param {String} dv Optional default value to return. * @return {String} Language value for the item like "my string" or the default value if it wasn't found. */ getLang : function(n, dv) { return this.editor.getLang(n, dv); }, /** * Executed a command on editor that opened the dialog/popup. * * @method execCommand * @param {String} cmd Command to execute. * @param {Boolean} ui Optional boolean value if the UI for the command should be presented or not. * @param {Object} val Optional value to pass with the comman like an URL. * @param {Object} a Optional arguments object. */ execCommand : function(cmd, ui, val, a) { a = a || {}; a.skip_focus = 1; this.restoreSelection(); return this.editor.execCommand(cmd, ui, val, a); }, /** * Resizes the dialog to the inner size of the window. This is needed since various browsers * have different border sizes on windows. * * @method resizeToInnerSize */ resizeToInnerSize : function() { var t = this; // Detach it to workaround a Chrome specific bug // https://sourceforge.net/tracker/?func=detail&atid=635682&aid=2926339&group_id=103281 setTimeout(function() { var vp = t.dom.getViewPort(window); t.editor.windowManager.resizeBy( t.getWindowArg('mce_width') - vp.w, t.getWindowArg('mce_height') - vp.h, t.id || window ); }, 0); }, /** * Will executed the specified string when the page has been loaded. This function * was added for compatibility with the 2.x branch. * * @method executeOnLoad * @param {String} s String to evalutate on init. */ executeOnLoad : function(s) { this.onInit.add(function() { eval(s); }); }, /** * Stores the current editor selection for later restoration. This can be useful since some browsers * loses its selection if a control element is selected/focused inside the dialogs. * * @method storeSelection */ storeSelection : function() { this.editor.windowManager.bookmark = tinyMCEPopup.editor.selection.getBookmark(1); }, /** * Restores any stored selection. This can be useful since some browsers * loses its selection if a control element is selected/focused inside the dialogs. * * @method restoreSelection */ restoreSelection : function() { var t = tinyMCEPopup; if (!t.isWindow && tinymce.isIE) t.editor.selection.moveToBookmark(t.editor.windowManager.bookmark); }, /** * Loads a specific dialog language pack. If you pass in plugin_url as a arugment * when you open the window it will load the <plugin url>/langs/<code>_dlg.js lang pack file. * * @method requireLangPack */ requireLangPack : function() { var t = this, u = t.getWindowArg('plugin_url') || t.getWindowArg('theme_url'); if (u && t.editor.settings.language && t.features.translate_i18n !== false) { u += '/langs/' + t.editor.settings.language + '_dlg.js'; if (!tinymce.ScriptLoader.isDone(u)) { document.write('<script type="text/javascript" src="' + tinymce._addVer(u) + '"></script>'); tinymce.ScriptLoader.markDone(u); } } }, /** * Executes a color picker on the specified element id. When the user * then selects a color it will be set as the value of the specified element. * * @method pickColor * @param {DOMEvent} e DOM event object. * @param {string} element_id Element id to be filled with the color value from the picker. */ pickColor : function(e, element_id) { this.execCommand('mceColorPicker', true, { color : document.getElementById(element_id).value, func : function(c) { document.getElementById(element_id).value = c; try { document.getElementById(element_id).onchange(); } catch (ex) { // Try fire event, ignore errors } } }); }, /** * Opens a filebrowser/imagebrowser this will set the output value from * the browser as a value on the specified element. * * @method openBrowser * @param {string} element_id Id of the element to set value in. * @param {string} type Type of browser to open image/file/flash. * @param {string} option Option name to get the file_broswer_callback function name from. */ openBrowser : function(element_id, type, option) { tinyMCEPopup.restoreSelection(); this.editor.execCallback('file_browser_callback', element_id, document.getElementById(element_id).value, type, window); }, /** * Creates a confirm dialog. Please don't use the blocking behavior of this * native version use the callback method instead then it can be extended. * * @method confirm * @param {String} t Title for the new confirm dialog. * @param {function} cb Callback function to be executed after the user has selected ok or cancel. * @param {Object} s Optional scope to execute the callback in. */ confirm : function(t, cb, s) { this.editor.windowManager.confirm(t, cb, s, window); }, /** * Creates an alert dialog. Please don't use the blocking behavior of this * native version use the callback method instead then it can be extended. * * @method alert * @param {String} t Title for the new alert dialog. * @param {function} cb Callback function to be executed after the user has selected ok. * @param {Object} s Optional scope to execute the callback in. */ alert : function(tx, cb, s) { this.editor.windowManager.alert(tx, cb, s, window); }, /** * Closes the current window. * * @method close */ close : function() { var t = this; // To avoid domain relaxing issue in Opera function close() { t.editor.windowManager.close(window); t.editor = null; }; if (tinymce.isOpera) t.getWin().setTimeout(close, 0); else close(); }, // Internal functions _restoreSelection : function() { var e = window.event.srcElement; if (e.nodeName == 'INPUT' && (e.type == 'submit' || e.type == 'button')) tinyMCEPopup.restoreSelection(); }, /* _restoreSelection : function() { var e = window.event.srcElement; // If user focus a non text input or textarea if ((e.nodeName != 'INPUT' && e.nodeName != 'TEXTAREA') || e.type != 'text') tinyMCEPopup.restoreSelection(); },*/ _onDOMLoaded : function() { var t = tinyMCEPopup, ti = document.title, bm, h, nv; if (t.domLoaded) return; t.domLoaded = 1; tinyMCEPopup.init(); // Translate page if (t.features.translate_i18n !== false) { h = document.body.innerHTML; // Replace a=x with a="x" in IE if (tinymce.isIE) h = h.replace(/ (value|title|alt)=([^"][^\s>]+)/gi, ' $1="$2"') document.dir = t.editor.getParam('directionality',''); if ((nv = t.editor.translate(h)) && nv != h) document.body.innerHTML = nv; if ((nv = t.editor.translate(ti)) && nv != ti) document.title = ti = nv; } document.body.style.display = ''; // Restore selection in IE when focus is placed on a non textarea or input element of the type text if (tinymce.isIE) { document.attachEvent('onmouseup', tinyMCEPopup._restoreSelection); // Add base target element for it since it would fail with modal dialogs t.dom.add(t.dom.select('head')[0], 'base', {target : '_self'}); } t.restoreSelection(); // Set inline title if (!t.isWindow) t.editor.windowManager.setTitle(window, ti); else window.focus(); if (!tinymce.isIE && !t.isWindow) { tinymce.dom.Event._add(document, 'focus', function() { t.editor.windowManager.focus(t.id); }); } // Patch for accessibility tinymce.each(t.dom.select('select'), function(e) { e.onkeydown = tinyMCEPopup._accessHandler; }); // Call onInit // Init must be called before focus so the selection won't get lost by the focus call tinymce.each(t.listeners, function(o) { o.func.call(o.scope, t.editor); }); // Move focus to window if (t.getWindowArg('mce_auto_focus', true)) { window.focus(); // Focus element with mceFocus class tinymce.each(document.forms, function(f) { tinymce.each(f.elements, function(e) { if (t.dom.hasClass(e, 'mceFocus') && !e.disabled) { e.focus(); return false; // Break loop } }); }); } document.onkeyup = tinyMCEPopup._closeWinKeyHandler; }, _accessHandler : function(e) { e = e || window.event; if (e.keyCode == 13 || e.keyCode == 32) { e = e.target || e.srcElement; if (e.onchange) e.onchange(); return tinymce.dom.Event.cancel(e); } }, _closeWinKeyHandler : function(e) { e = e || window.event; if (e.keyCode == 27) tinyMCEPopup.close(); }, _wait : function() { // Use IE method if (document.attachEvent) { document.attachEvent("onreadystatechange", function() { if (document.readyState === "complete") { document.detachEvent("onreadystatechange", arguments.callee); tinyMCEPopup._onDOMLoaded(); } }); if (document.documentElement.doScroll && window == window.top) { (function() { if (tinyMCEPopup.domLoaded) return; try { // If IE is used, use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ document.documentElement.doScroll("left"); } catch (ex) { setTimeout(arguments.callee, 0); return; } tinyMCEPopup._onDOMLoaded(); })(); } document.attachEvent('onload', tinyMCEPopup._onDOMLoaded); } else if (document.addEventListener) { window.addEventListener('DOMContentLoaded', tinyMCEPopup._onDOMLoaded, false); window.addEventListener('load', tinyMCEPopup._onDOMLoaded, false); } } };
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { tinymce.create('tinymce.plugins.WPDialogs', { init : function(ed, url) { tinymce.create('tinymce.WPWindowManager:tinymce.InlineWindowManager', { WPWindowManager : function(ed) { this.parent(ed); }, open : function(f, p) { var t = this, element; if ( ! f.wpDialog ) return this.parent( f, p ); else if ( ! f.id ) return; element = jQuery('#' + f.id); if ( ! element.length ) return; t.features = f; t.params = p; t.onOpen.dispatch(t, f, p); t.element = t.windows[ f.id ] = element; // Store selection t.bookmark = t.editor.selection.getBookmark(1); // Create the dialog if necessary if ( ! element.data('wpdialog') ) { element.wpdialog({ title: f.title, width: f.width, height: f.height, modal: true, dialogClass: 'wp-dialog', zIndex: 300000 }); } element.wpdialog('open'); }, close : function() { if ( ! this.features.wpDialog ) return this.parent.apply( this, arguments ); this.element.wpdialog('close'); } }); // Replace window manager ed.onBeforeRenderUI.add(function() { ed.windowManager = new tinymce.WPWindowManager(ed); }); }, getInfo : function() { return { longname : 'WPDialogs', author : 'WordPress', authorurl : 'http://wordpress.org', infourl : 'http://wordpress.org', version : '0.1' }; } }); // Register plugin tinymce.PluginManager.add('wpdialogs', tinymce.plugins.WPDialogs); })();
JavaScript
/** * WP Fullscreen TinyMCE plugin * * Contains code from Moxiecode Systems AB released under LGPL http://tinymce.moxiecode.com/license */ (function() { tinymce.create('tinymce.plugins.wpFullscreenPlugin', { resize_timeout: false, init : function(ed, url) { var t = this, oldHeight = 0, s = {}, DOM = tinymce.DOM; // Register commands ed.addCommand('wpFullScreenClose', function() { // this removes the editor, content has to be saved first with tinyMCE.execCommand('wpFullScreenSave'); if ( ed.getParam('wp_fullscreen_is_enabled') ) { DOM.win.setTimeout(function() { tinyMCE.remove(ed); DOM.remove('wp_mce_fullscreen_parent'); tinyMCE.settings = tinyMCE.oldSettings; // Restore old settings }, 10); } }); ed.addCommand('wpFullScreenSave', function() { var ed = tinyMCE.get('wp_mce_fullscreen'), edd; ed.focus(); edd = tinyMCE.get( ed.getParam('wp_fullscreen_editor_id') ); edd.setContent( ed.getContent({format : 'raw'}), {format : 'raw'} ); }); ed.addCommand('wpFullScreenInit', function() { var d, b, fsed; ed = tinyMCE.activeEditor; d = ed.getDoc(); b = d.body; tinyMCE.oldSettings = tinyMCE.settings; // Store old settings tinymce.each(ed.settings, function(v, n) { s[n] = v; }); s.id = 'wp_mce_fullscreen'; s.wp_fullscreen_is_enabled = true; s.wp_fullscreen_editor_id = ed.id; s.theme_advanced_resizing = false; s.theme_advanced_statusbar_location = 'none'; s.content_css = s.content_css ? s.content_css + ',' + s.wp_fullscreen_content_css : s.wp_fullscreen_content_css; s.height = tinymce.isIE ? b.scrollHeight : b.offsetHeight; tinymce.each(ed.getParam('wp_fullscreen_settings'), function(v, k) { s[k] = v; }); fsed = new tinymce.Editor('wp_mce_fullscreen', s); fsed.onInit.add(function(edd) { var DOM = tinymce.DOM, buttons = DOM.select('a.mceButton', DOM.get('wp-fullscreen-buttons')); if ( !ed.isHidden() ) edd.setContent( ed.getContent() ); else edd.setContent( switchEditors.wpautop( edd.getElement().value ) ); setTimeout(function(){ // add last edd.onNodeChange.add(function(ed, cm, e){ tinymce.each(buttons, function(c) { var btn, cls; if ( btn = DOM.get( 'wp_mce_fullscreen_' + c.id.substr(6) ) ) { cls = btn.className; if ( cls ) c.className = cls; } }); }); }, 1000); edd.dom.addClass(edd.getBody(), 'wp-fullscreen-editor'); edd.focus(); }); fsed.render(); if ( 'undefined' != fullscreen ) { fsed.dom.bind( fsed.dom.doc, 'mousemove', function(e){ fullscreen.bounder( 'showToolbar', 'hideToolbar', 2000, e ); }); } }); ed.addCommand('wpFullScreen', function() { if ( typeof(fullscreen) == 'undefined' ) return; if ( 'wp_mce_fullscreen' == ed.id ) fullscreen.off(); else fullscreen.on(); }); // Register buttons ed.addButton('wp_fullscreen', { title : 'wordpress.wp_fullscreen_desc', cmd : 'wpFullScreen' }); // END fullscreen //---------------------------------------------------------------- // START autoresize if ( ed.getParam('fullscreen_is_enabled') || !ed.getParam('wp_fullscreen_is_enabled') ) return; /** * This method gets executed each time the editor needs to resize. */ function resize(editor, e) { var DOM = tinymce.DOM, body = ed.getBody(), ifr = DOM.get(ed.id + '_ifr'), height, y = ed.dom.win.scrollY; if ( t.resize_timeout ) return; // sometimes several events are fired few ms apart, trottle down resizing a little t.resize_timeout = true; setTimeout(function(){ t.resize_timeout = false; }, 500); height = body.scrollHeight > 300 ? body.scrollHeight : 300; if ( height != ifr.scrollHeight ) { DOM.setStyle(ifr, 'height', height + 'px'); ed.getWin().scrollTo(0, 0); // iframe window object, make sure there's no scrolling } // WebKit scrolls to top on paste... if ( e && e.type == 'paste' && tinymce.isWebKit ) { setTimeout(function(){ ed.dom.win.scrollTo(0, y); }, 40); } }; // Add appropriate listeners for resizing content area ed.onInit.add(function(ed, l) { ed.onChange.add(resize); ed.onSetContent.add(resize); ed.onPaste.add(resize); ed.onKeyUp.add(resize); ed.onPostRender.add(resize); ed.getBody().style.overflowY = "hidden"; }); if ( ed.getParam('autoresize_on_init', true) ) { ed.onLoadContent.add(function(ed, l) { // Because the content area resizes when its content CSS loads, // and we can't easily add a listener to its onload event, // we'll just trigger a resize after a short loading period setTimeout(function() { resize(); }, 1200); }); } // Register the command so that it can be invoked by using tinyMCE.activeEditor.execCommand('mceExample'); ed.addCommand('wpAutoResize', resize); }, getInfo : function() { return { longname : 'WP Fullscreen', author : 'WordPress', authorurl : 'http://wordpress.org', infourl : '', version : '1.0' }; } }); // Register plugin tinymce.PluginManager.add('wpfullscreen', tinymce.plugins.wpFullscreenPlugin); })();
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { var DOM = tinymce.DOM, Element = tinymce.dom.Element, Event = tinymce.dom.Event, each = tinymce.each, is = tinymce.is; tinymce.create('tinymce.plugins.InlinePopups', { init : function(ed, url) { // Replace window manager ed.onBeforeRenderUI.add(function() { ed.windowManager = new tinymce.InlineWindowManager(ed); DOM.loadCSS(url + '/skins/' + (ed.settings.inlinepopups_skin || 'clearlooks2') + "/window.css"); }); }, getInfo : function() { return { longname : 'InlinePopups', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/inlinepopups', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); tinymce.create('tinymce.InlineWindowManager:tinymce.WindowManager', { InlineWindowManager : function(ed) { var t = this; t.parent(ed); t.zIndex = 300000; t.count = 0; t.windows = {}; }, open : function(f, p) { var t = this, id, opt = '', ed = t.editor, dw = 0, dh = 0, vp, po, mdf, clf, we, w, u, parentWindow; f = f || {}; p = p || {}; // Run native windows if (!f.inline) return t.parent(f, p); parentWindow = t._frontWindow(); if (parentWindow && DOM.get(parentWindow.id + '_ifr')) { parentWindow.focussedElement = DOM.get(parentWindow.id + '_ifr').contentWindow.document.activeElement; } // Only store selection if the type is a normal window if (!f.type) t.bookmark = ed.selection.getBookmark(1); id = DOM.uniqueId(); vp = DOM.getViewPort(); f.width = parseInt(f.width || 320); f.height = parseInt(f.height || 240) + (tinymce.isIE ? 8 : 0); f.min_width = parseInt(f.min_width || 150); f.min_height = parseInt(f.min_height || 100); f.max_width = parseInt(f.max_width || 2000); f.max_height = parseInt(f.max_height || 2000); f.left = f.left || Math.round(Math.max(vp.x, vp.x + (vp.w / 2.0) - (f.width / 2.0))); f.top = f.top || Math.round(Math.max(vp.y, vp.y + (vp.h / 2.0) - (f.height / 2.0))); f.movable = f.resizable = true; p.mce_width = f.width; p.mce_height = f.height; p.mce_inline = true; p.mce_window_id = id; p.mce_auto_focus = f.auto_focus; // Transpose // po = DOM.getPos(ed.getContainer()); // f.left -= po.x; // f.top -= po.y; t.features = f; t.params = p; t.onOpen.dispatch(t, f, p); if (f.type) { opt += ' mceModal'; if (f.type) opt += ' mce' + f.type.substring(0, 1).toUpperCase() + f.type.substring(1); f.resizable = false; } if (f.statusbar) opt += ' mceStatusbar'; if (f.resizable) opt += ' mceResizable'; if (f.minimizable) opt += ' mceMinimizable'; if (f.maximizable) opt += ' mceMaximizable'; if (f.movable) opt += ' mceMovable'; // Create DOM objects t._addAll(DOM.doc.body, ['div', {id : id, role : 'dialog', 'aria-labelledby': f.type ? id + '_content' : id + '_title', 'class' : (ed.settings.inlinepopups_skin || 'clearlooks2') + (tinymce.isIE && window.getSelection ? ' ie9' : ''), style : 'width:100px;height:100px'}, ['div', {id : id + '_wrapper', 'class' : 'mceWrapper' + opt}, ['div', {id : id + '_top', 'class' : 'mceTop'}, ['div', {'class' : 'mceLeft'}], ['div', {'class' : 'mceCenter'}], ['div', {'class' : 'mceRight'}], ['span', {id : id + '_title'}, f.title || ''] ], ['div', {id : id + '_middle', 'class' : 'mceMiddle'}, ['div', {id : id + '_left', 'class' : 'mceLeft', tabindex : '0'}], ['span', {id : id + '_content'}], ['div', {id : id + '_right', 'class' : 'mceRight', tabindex : '0'}] ], ['div', {id : id + '_bottom', 'class' : 'mceBottom'}, ['div', {'class' : 'mceLeft'}], ['div', {'class' : 'mceCenter'}], ['div', {'class' : 'mceRight'}], ['span', {id : id + '_status'}, 'Content'] ], ['a', {'class' : 'mceMove', tabindex : '-1', href : 'javascript:;'}], ['a', {'class' : 'mceMin', tabindex : '-1', href : 'javascript:;', onmousedown : 'return false;'}], ['a', {'class' : 'mceMax', tabindex : '-1', href : 'javascript:;', onmousedown : 'return false;'}], ['a', {'class' : 'mceMed', tabindex : '-1', href : 'javascript:;', onmousedown : 'return false;'}], ['a', {'class' : 'mceClose', tabindex : '-1', href : 'javascript:;', onmousedown : 'return false;'}], ['a', {id : id + '_resize_n', 'class' : 'mceResize mceResizeN', tabindex : '-1', href : 'javascript:;'}], ['a', {id : id + '_resize_s', 'class' : 'mceResize mceResizeS', tabindex : '-1', href : 'javascript:;'}], ['a', {id : id + '_resize_w', 'class' : 'mceResize mceResizeW', tabindex : '-1', href : 'javascript:;'}], ['a', {id : id + '_resize_e', 'class' : 'mceResize mceResizeE', tabindex : '-1', href : 'javascript:;'}], ['a', {id : id + '_resize_nw', 'class' : 'mceResize mceResizeNW', tabindex : '-1', href : 'javascript:;'}], ['a', {id : id + '_resize_ne', 'class' : 'mceResize mceResizeNE', tabindex : '-1', href : 'javascript:;'}], ['a', {id : id + '_resize_sw', 'class' : 'mceResize mceResizeSW', tabindex : '-1', href : 'javascript:;'}], ['a', {id : id + '_resize_se', 'class' : 'mceResize mceResizeSE', tabindex : '-1', href : 'javascript:;'}] ] ] ); DOM.setStyles(id, {top : -10000, left : -10000}); // Fix gecko rendering bug, where the editors iframe messed with window contents if (tinymce.isGecko) DOM.setStyle(id, 'overflow', 'auto'); // Measure borders if (!f.type) { dw += DOM.get(id + '_left').clientWidth; dw += DOM.get(id + '_right').clientWidth; dh += DOM.get(id + '_top').clientHeight; dh += DOM.get(id + '_bottom').clientHeight; } // Resize window DOM.setStyles(id, {top : f.top, left : f.left, width : f.width + dw, height : f.height + dh}); u = f.url || f.file; if (u) { if (tinymce.relaxedDomain) u += (u.indexOf('?') == -1 ? '?' : '&') + 'mce_rdomain=' + tinymce.relaxedDomain; u = tinymce._addVer(u); } if (!f.type) { DOM.add(id + '_content', 'iframe', {id : id + '_ifr', src : 'javascript:""', frameBorder : 0, style : 'border:0;width:10px;height:10px'}); DOM.setStyles(id + '_ifr', {width : f.width, height : f.height}); DOM.setAttrib(id + '_ifr', 'src', u); } else { DOM.add(id + '_wrapper', 'a', {id : id + '_ok', 'class' : 'mceButton mceOk', href : 'javascript:;', onmousedown : 'return false;'}, 'Ok'); if (f.type == 'confirm') DOM.add(id + '_wrapper', 'a', {'class' : 'mceButton mceCancel', href : 'javascript:;', onmousedown : 'return false;'}, 'Cancel'); DOM.add(id + '_middle', 'div', {'class' : 'mceIcon'}); DOM.setHTML(id + '_content', f.content.replace('\n', '<br />')); Event.add(id, 'keyup', function(evt) { var VK_ESCAPE = 27; if (evt.keyCode === VK_ESCAPE) { f.button_func(false); return Event.cancel(evt); } }); Event.add(id, 'keydown', function(evt) { var cancelButton, VK_TAB = 9; if (evt.keyCode === VK_TAB) { cancelButton = DOM.select('a.mceCancel', id + '_wrapper')[0]; if (cancelButton && cancelButton !== evt.target) { cancelButton.focus(); } else { DOM.get(id + '_ok').focus(); } return Event.cancel(evt); } }); } // Register events mdf = Event.add(id, 'mousedown', function(e) { var n = e.target, w, vp; w = t.windows[id]; t.focus(id); if (n.nodeName == 'A' || n.nodeName == 'a') { if (n.className == 'mceClose') { t.close(null, id); return Event.cancel(e); } else if (n.className == 'mceMax') { w.oldPos = w.element.getXY(); w.oldSize = w.element.getSize(); vp = DOM.getViewPort(); // Reduce viewport size to avoid scrollbars vp.w -= 2; vp.h -= 2; w.element.moveTo(vp.x, vp.y); w.element.resizeTo(vp.w, vp.h); DOM.setStyles(id + '_ifr', {width : vp.w - w.deltaWidth, height : vp.h - w.deltaHeight}); DOM.addClass(id + '_wrapper', 'mceMaximized'); } else if (n.className == 'mceMed') { // Reset to old size w.element.moveTo(w.oldPos.x, w.oldPos.y); w.element.resizeTo(w.oldSize.w, w.oldSize.h); w.iframeElement.resizeTo(w.oldSize.w - w.deltaWidth, w.oldSize.h - w.deltaHeight); DOM.removeClass(id + '_wrapper', 'mceMaximized'); } else if (n.className == 'mceMove') return t._startDrag(id, e, n.className); else if (DOM.hasClass(n, 'mceResize')) return t._startDrag(id, e, n.className.substring(13)); } }); clf = Event.add(id, 'click', function(e) { var n = e.target; t.focus(id); if (n.nodeName == 'A' || n.nodeName == 'a') { switch (n.className) { case 'mceClose': t.close(null, id); return Event.cancel(e); case 'mceButton mceOk': case 'mceButton mceCancel': f.button_func(n.className == 'mceButton mceOk'); return Event.cancel(e); } } }); // Make sure the tab order loops within the dialog. Event.add([id + '_left', id + '_right'], 'focus', function(evt) { var iframe = DOM.get(id + '_ifr'); if (iframe) { var body = iframe.contentWindow.document.body; var focusable = DOM.select(':input:enabled,*[tabindex=0]', body); if (evt.target.id === (id + '_left')) { focusable[focusable.length - 1].focus(); } else { focusable[0].focus(); } } else { DOM.get(id + '_ok').focus(); } }); // Add window w = t.windows[id] = { id : id, mousedown_func : mdf, click_func : clf, element : new Element(id, {blocker : 1, container : ed.getContainer()}), iframeElement : new Element(id + '_ifr'), features : f, deltaWidth : dw, deltaHeight : dh }; w.iframeElement.on('focus', function() { t.focus(id); }); // Setup blocker if (t.count == 0 && t.editor.getParam('dialog_type', 'modal') == 'modal') { DOM.add(DOM.doc.body, 'div', { id : 'mceModalBlocker', 'class' : (t.editor.settings.inlinepopups_skin || 'clearlooks2') + '_modalBlocker', style : {zIndex : t.zIndex - 1} }); DOM.show('mceModalBlocker'); // Reduces flicker in IE DOM.setAttrib(DOM.doc.body, 'aria-hidden', 'true'); } else DOM.setStyle('mceModalBlocker', 'z-index', t.zIndex - 1); if (tinymce.isIE6 || /Firefox\/2\./.test(navigator.userAgent) || (tinymce.isIE && !DOM.boxModel)) DOM.setStyles('mceModalBlocker', {position : 'absolute', left : vp.x, top : vp.y, width : vp.w - 2, height : vp.h - 2}); DOM.setAttrib(id, 'aria-hidden', 'false'); t.focus(id); t._fixIELayout(id, 1); // Focus ok button if (DOM.get(id + '_ok')) DOM.get(id + '_ok').focus(); t.count++; return w; }, focus : function(id) { var t = this, w; if (w = t.windows[id]) { w.zIndex = this.zIndex++; w.element.setStyle('zIndex', w.zIndex); w.element.update(); id = id + '_wrapper'; DOM.removeClass(t.lastId, 'mceFocus'); DOM.addClass(id, 'mceFocus'); t.lastId = id; if (w.focussedElement) { w.focussedElement.focus(); } else if (DOM.get(id + '_ok')) { DOM.get(w.id + '_ok').focus(); } else if (DOM.get(w.id + '_ifr')) { DOM.get(w.id + '_ifr').focus(); } } }, _addAll : function(te, ne) { var i, n, t = this, dom = tinymce.DOM; if (is(ne, 'string')) te.appendChild(dom.doc.createTextNode(ne)); else if (ne.length) { te = te.appendChild(dom.create(ne[0], ne[1])); for (i=2; i<ne.length; i++) t._addAll(te, ne[i]); } }, _startDrag : function(id, se, ac) { var t = this, mu, mm, d = DOM.doc, eb, w = t.windows[id], we = w.element, sp = we.getXY(), p, sz, ph, cp, vp, sx, sy, sex, sey, dx, dy, dw, dh; // Get positons and sizes // cp = DOM.getPos(t.editor.getContainer()); cp = {x : 0, y : 0}; vp = DOM.getViewPort(); // Reduce viewport size to avoid scrollbars while dragging vp.w -= 2; vp.h -= 2; sex = se.screenX; sey = se.screenY; dx = dy = dw = dh = 0; // Handle mouse up mu = Event.add(d, 'mouseup', function(e) { Event.remove(d, 'mouseup', mu); Event.remove(d, 'mousemove', mm); if (eb) eb.remove(); we.moveBy(dx, dy); we.resizeBy(dw, dh); sz = we.getSize(); DOM.setStyles(id + '_ifr', {width : sz.w - w.deltaWidth, height : sz.h - w.deltaHeight}); t._fixIELayout(id, 1); return Event.cancel(e); }); if (ac != 'Move') startMove(); function startMove() { if (eb) return; t._fixIELayout(id, 0); // Setup event blocker DOM.add(d.body, 'div', { id : 'mceEventBlocker', 'class' : 'mceEventBlocker ' + (t.editor.settings.inlinepopups_skin || 'clearlooks2'), style : {zIndex : t.zIndex + 1} }); if (tinymce.isIE6 || (tinymce.isIE && !DOM.boxModel)) DOM.setStyles('mceEventBlocker', {position : 'absolute', left : vp.x, top : vp.y, width : vp.w - 2, height : vp.h - 2}); eb = new Element('mceEventBlocker'); eb.update(); // Setup placeholder p = we.getXY(); sz = we.getSize(); sx = cp.x + p.x - vp.x; sy = cp.y + p.y - vp.y; DOM.add(eb.get(), 'div', {id : 'mcePlaceHolder', 'class' : 'mcePlaceHolder', style : {left : sx, top : sy, width : sz.w, height : sz.h}}); ph = new Element('mcePlaceHolder'); }; // Handle mouse move/drag mm = Event.add(d, 'mousemove', function(e) { var x, y, v; startMove(); x = e.screenX - sex; y = e.screenY - sey; switch (ac) { case 'ResizeW': dx = x; dw = 0 - x; break; case 'ResizeE': dw = x; break; case 'ResizeN': case 'ResizeNW': case 'ResizeNE': if (ac == "ResizeNW") { dx = x; dw = 0 - x; } else if (ac == "ResizeNE") dw = x; dy = y; dh = 0 - y; break; case 'ResizeS': case 'ResizeSW': case 'ResizeSE': if (ac == "ResizeSW") { dx = x; dw = 0 - x; } else if (ac == "ResizeSE") dw = x; dh = y; break; case 'mceMove': dx = x; dy = y; break; } // Boundary check if (dw < (v = w.features.min_width - sz.w)) { if (dx !== 0) dx += dw - v; dw = v; } if (dh < (v = w.features.min_height - sz.h)) { if (dy !== 0) dy += dh - v; dh = v; } dw = Math.min(dw, w.features.max_width - sz.w); dh = Math.min(dh, w.features.max_height - sz.h); dx = Math.max(dx, vp.x - (sx + vp.x)); dy = Math.max(dy, vp.y - (sy + vp.y)); dx = Math.min(dx, (vp.w + vp.x) - (sx + sz.w + vp.x)); dy = Math.min(dy, (vp.h + vp.y) - (sy + sz.h + vp.y)); // Move if needed if (dx + dy !== 0) { if (sx + dx < 0) dx = 0; if (sy + dy < 0) dy = 0; ph.moveTo(sx + dx, sy + dy); } // Resize if needed if (dw + dh !== 0) ph.resizeTo(sz.w + dw, sz.h + dh); return Event.cancel(e); }); return Event.cancel(se); }, resizeBy : function(dw, dh, id) { var w = this.windows[id]; if (w) { w.element.resizeBy(dw, dh); w.iframeElement.resizeBy(dw, dh); } }, close : function(win, id) { var t = this, w, d = DOM.doc, fw, id; id = t._findId(id || win); // Probably not inline if (!t.windows[id]) { t.parent(win); return; } t.count--; if (t.count == 0) { DOM.remove('mceModalBlocker'); DOM.setAttrib(DOM.doc.body, 'aria-hidden', 'false'); t.editor.focus(); } if (w = t.windows[id]) { t.onClose.dispatch(t); Event.remove(d, 'mousedown', w.mousedownFunc); Event.remove(d, 'click', w.clickFunc); Event.clear(id); Event.clear(id + '_ifr'); DOM.setAttrib(id + '_ifr', 'src', 'javascript:""'); // Prevent leak w.element.remove(); delete t.windows[id]; fw = t._frontWindow(); if (fw) t.focus(fw.id); } }, // Find front most window _frontWindow : function() { var fw, ix = 0; // Find front most window and focus that each (this.windows, function(w) { if (w.zIndex > ix) { fw = w; ix = w.zIndex; } }); return fw; }, setTitle : function(w, ti) { var e; w = this._findId(w); if (e = DOM.get(w + '_title')) e.innerHTML = DOM.encode(ti); }, alert : function(txt, cb, s) { var t = this, w; w = t.open({ title : t, type : 'alert', button_func : function(s) { if (cb) cb.call(s || t, s); t.close(null, w.id); }, content : DOM.encode(t.editor.getLang(txt, txt)), inline : 1, width : 400, height : 130 }); }, confirm : function(txt, cb, s) { var t = this, w; w = t.open({ title : t, type : 'confirm', button_func : function(s) { if (cb) cb.call(s || t, s); t.close(null, w.id); }, content : DOM.encode(t.editor.getLang(txt, txt)), inline : 1, width : 400, height : 130 }); }, // Internal functions _findId : function(w) { var t = this; if (typeof(w) == 'string') return w; each(t.windows, function(wo) { var ifr = DOM.get(wo.id + '_ifr'); if (ifr && w == ifr.contentWindow) { w = wo.id; return false; } }); return w; }, _fixIELayout : function(id, s) { var w, img; if (!tinymce.isIE6) return; // Fixes the bug where hover flickers and does odd things in IE6 each(['n','s','w','e','nw','ne','sw','se'], function(v) { var e = DOM.get(id + '_resize_' + v); DOM.setStyles(e, { width : s ? e.clientWidth : '', height : s ? e.clientHeight : '', cursor : DOM.getStyle(e, 'cursor', 1) }); DOM.setStyle(id + "_bottom", 'bottom', '-1px'); e = 0; }); // Fixes graphics glitch if (w = this.windows[id]) { // Fixes rendering bug after resize w.element.hide(); w.element.show(); // Forced a repaint of the window //DOM.get(id).style.filter = ''; // IE has a bug where images used in CSS won't get loaded // sometimes when the cache in the browser is disabled // This fix tries to solve it by loading the images using the image object each(DOM.select('div,a', id), function(e, i) { if (e.currentStyle.backgroundImage != 'none') { img = new Image(); img.src = e.currentStyle.backgroundImage.replace(/url\(\"(.+)\"\)/, '$1'); } }); DOM.get(id).style.filter = ''; } } }); // Register plugin tinymce.PluginManager.add('inlinepopups', tinymce.plugins.InlinePopups); })();
JavaScript
(function() { var url; if (url = tinyMCEPopup.getParam("media_external_list_url")) document.write('<script language="javascript" type="text/javascript" src="' + tinyMCEPopup.editor.documentBaseURI.toAbsolute(url) + '"></script>'); function get(id) { return document.getElementById(id); } function clone(obj) { var i, len, copy, attr; if (null == obj || "object" != typeof obj) return obj; // Handle Array if ('length' in obj) { copy = []; for (i = 0, len = obj.length; i < len; ++i) { copy[i] = clone(obj[i]); } return copy; } // Handle Object copy = {}; for (attr in obj) { if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]); } return copy; } function getVal(id) { var elm = get(id); if (elm.nodeName == "SELECT") return elm.options[elm.selectedIndex].value; if (elm.type == "checkbox") return elm.checked; return elm.value; } function setVal(id, value, name) { if (typeof(value) != 'undefined' && value != null) { var elm = get(id); if (elm.nodeName == "SELECT") selectByValue(document.forms[0], id, value); else if (elm.type == "checkbox") { if (typeof(value) == 'string') { value = value.toLowerCase(); value = (!name && value === 'true') || (name && value === name.toLowerCase()); } elm.checked = !!value; } else elm.value = value; } } window.Media = { init : function() { var html, editor, self = this; self.editor = editor = tinyMCEPopup.editor; // Setup file browsers and color pickers get('filebrowsercontainer').innerHTML = getBrowserHTML('filebrowser','src','media','media'); get('qtsrcfilebrowsercontainer').innerHTML = getBrowserHTML('qtsrcfilebrowser','quicktime_qtsrc','media','media'); get('bgcolor_pickcontainer').innerHTML = getColorPickerHTML('bgcolor_pick','bgcolor'); get('video_altsource1_filebrowser').innerHTML = getBrowserHTML('video_filebrowser_altsource1','video_altsource1','media','media'); get('video_altsource2_filebrowser').innerHTML = getBrowserHTML('video_filebrowser_altsource2','video_altsource2','media','media'); get('audio_altsource1_filebrowser').innerHTML = getBrowserHTML('audio_filebrowser_altsource1','audio_altsource1','media','media'); get('audio_altsource2_filebrowser').innerHTML = getBrowserHTML('audio_filebrowser_altsource2','audio_altsource2','media','media'); get('video_poster_filebrowser').innerHTML = getBrowserHTML('filebrowser_poster','video_poster','image','media'); html = self.getMediaListHTML('medialist', 'src', 'media', 'media'); if (html == "") get("linklistrow").style.display = 'none'; else get("linklistcontainer").innerHTML = html; if (isVisible('filebrowser')) get('src').style.width = '230px'; if (isVisible('video_filebrowser_altsource1')) get('video_altsource1').style.width = '220px'; if (isVisible('video_filebrowser_altsource2')) get('video_altsource2').style.width = '220px'; if (isVisible('audio_filebrowser_altsource1')) get('audio_altsource1').style.width = '220px'; if (isVisible('audio_filebrowser_altsource2')) get('audio_altsource2').style.width = '220px'; if (isVisible('filebrowser_poster')) get('video_poster').style.width = '220px'; editor.dom.setOuterHTML(get('media_type'), self.getMediaTypeHTML(editor)); self.setDefaultDialogSettings(editor); self.data = clone(tinyMCEPopup.getWindowArg('data')); self.dataToForm(); self.preview(); updateColor('bgcolor_pick', 'bgcolor'); }, insert : function() { var editor = tinyMCEPopup.editor; this.formToData(); editor.execCommand('mceRepaint'); tinyMCEPopup.restoreSelection(); editor.selection.setNode(editor.plugins.media.dataToImg(this.data)); tinyMCEPopup.close(); }, preview : function() { get('prev').innerHTML = this.editor.plugins.media.dataToHtml(this.data, true); }, moveStates : function(to_form, field) { var data = this.data, editor = this.editor, mediaPlugin = editor.plugins.media, ext, src, typeInfo, defaultStates, src; defaultStates = { // QuickTime quicktime_autoplay : true, quicktime_controller : true, // Flash flash_play : true, flash_loop : true, flash_menu : true, // WindowsMedia windowsmedia_autostart : true, windowsmedia_enablecontextmenu : true, windowsmedia_invokeurls : true, // RealMedia realmedia_autogotourl : true, realmedia_imagestatus : true }; function parseQueryParams(str) { var out = {}; if (str) { tinymce.each(str.split('&'), function(item) { var parts = item.split('='); out[unescape(parts[0])] = unescape(parts[1]); }); } return out; }; function setOptions(type, names) { var i, name, formItemName, value, list; if (type == data.type || type == 'global') { names = tinymce.explode(names); for (i = 0; i < names.length; i++) { name = names[i]; formItemName = type == 'global' ? name : type + '_' + name; if (type == 'global') list = data; else if (type == 'video' || type == 'audio') { list = data.video.attrs; if (!list && !to_form) data.video.attrs = list = {}; } else list = data.params; if (list) { if (to_form) { setVal(formItemName, list[name], type == 'video' || type == 'audio' ? name : ''); } else { delete list[name]; value = getVal(formItemName); if ((type == 'video' || type == 'audio') && value === true) value = name; if (defaultStates[formItemName]) { if (value !== defaultStates[formItemName]) { value = "" + value; list[name] = value; } } else if (value) { value = "" + value; list[name] = value; } } } } } } if (!to_form) { data.type = get('media_type').options[get('media_type').selectedIndex].value; data.width = getVal('width'); data.height = getVal('height'); // Switch type based on extension src = getVal('src'); if (field == 'src') { ext = src.replace(/^.*\.([^.]+)$/, '$1'); if (typeInfo = mediaPlugin.getType(ext)) data.type = typeInfo.name.toLowerCase(); setVal('media_type', data.type); } if (data.type == "video" || data.type == "audio") { if (!data.video.sources) data.video.sources = []; data.video.sources[0] = {src: getVal('src')}; } } // Hide all fieldsets and show the one active get('video_options').style.display = 'none'; get('audio_options').style.display = 'none'; get('flash_options').style.display = 'none'; get('quicktime_options').style.display = 'none'; get('shockwave_options').style.display = 'none'; get('windowsmedia_options').style.display = 'none'; get('realmedia_options').style.display = 'none'; get('embeddedaudio_options').style.display = 'none'; if (get(data.type + '_options')) get(data.type + '_options').style.display = 'block'; setVal('media_type', data.type); setOptions('flash', 'play,loop,menu,swliveconnect,quality,scale,salign,wmode,base,flashvars'); setOptions('quicktime', 'loop,autoplay,cache,controller,correction,enablejavascript,kioskmode,autohref,playeveryframe,targetcache,scale,starttime,endtime,target,qtsrcchokespeed,volume,qtsrc'); setOptions('shockwave', 'sound,progress,autostart,swliveconnect,swvolume,swstretchstyle,swstretchhalign,swstretchvalign'); setOptions('windowsmedia', 'autostart,enabled,enablecontextmenu,fullscreen,invokeurls,mute,stretchtofit,windowlessvideo,balance,baseurl,captioningid,currentmarker,currentposition,defaultframe,playcount,rate,uimode,volume'); setOptions('realmedia', 'autostart,loop,autogotourl,center,imagestatus,maintainaspect,nojava,prefetch,shuffle,console,controls,numloop,scriptcallbacks'); setOptions('video', 'poster,autoplay,loop,muted,preload,controls'); setOptions('audio', 'autoplay,loop,preload,controls'); setOptions('embeddedaudio', 'autoplay,loop,controls'); setOptions('global', 'id,name,vspace,hspace,bgcolor,align,width,height'); if (to_form) { if (data.type == 'video') { if (data.video.sources[0]) setVal('src', data.video.sources[0].src); src = data.video.sources[1]; if (src) setVal('video_altsource1', src.src); src = data.video.sources[2]; if (src) setVal('video_altsource2', src.src); } else if (data.type == 'audio') { if (data.video.sources[0]) setVal('src', data.video.sources[0].src); src = data.video.sources[1]; if (src) setVal('audio_altsource1', src.src); src = data.video.sources[2]; if (src) setVal('audio_altsource2', src.src); } else { // Check flash vars if (data.type == 'flash') { tinymce.each(editor.getParam('flash_video_player_flashvars', {url : '$url', poster : '$poster'}), function(value, name) { if (value == '$url') data.params.src = parseQueryParams(data.params.flashvars)[name] || data.params.src || ''; }); } setVal('src', data.params.src); } } else { src = getVal("src"); // YouTube Embed if (src.match(/youtube\.com\/embed\/\w+/)) { data.width = 425; data.height = 350; data.params.frameborder = '0'; data.type = 'iframe'; setVal('src', src); setVal('media_type', data.type); } else { // YouTube *NEW* if (src.match(/youtu\.be\/[a-z1-9.-_]+/)) { data.width = 425; data.height = 350; data.params.frameborder = '0'; data.type = 'iframe'; src = 'http://www.youtube.com/embed/' + src.match(/youtu.be\/([a-z1-9.-_]+)/)[1]; setVal('src', src); setVal('media_type', data.type); } // YouTube if (src.match(/youtube\.com(.+)v=([^&]+)/)) { data.width = 425; data.height = 350; data.params.frameborder = '0'; data.type = 'iframe'; src = 'http://www.youtube.com/embed/' + src.match(/v=([^&]+)/)[1]; setVal('src', src); setVal('media_type', data.type); } } // Google video if (src.match(/video\.google\.com(.+)docid=([^&]+)/)) { data.width = 425; data.height = 326; data.type = 'flash'; src = 'http://video.google.com/googleplayer.swf?docId=' + src.match(/docid=([^&]+)/)[1] + '&hl=en'; setVal('src', src); setVal('media_type', data.type); } // Vimeo if (src.match(/vimeo\.com\/([0-9]+)/)) { data.width = 425; data.height = 350; data.params.frameborder = '0'; data.type = 'iframe'; src = 'http://player.vimeo.com/video/' + src.match(/vimeo.com\/([0-9]+)/)[1]; setVal('src', src); setVal('media_type', data.type); } // stream.cz if (src.match(/stream\.cz\/((?!object).)*\/([0-9]+)/)) { data.width = 425; data.height = 350; data.params.frameborder = '0'; data.type = 'iframe'; src = 'http://www.stream.cz/object/' + src.match(/stream.cz\/[^/]+\/([0-9]+)/)[1]; setVal('src', src); setVal('media_type', data.type); } // Google maps if (src.match(/maps\.google\.([a-z]{2,3})\/maps\/(.+)msid=(.+)/)) { data.width = 425; data.height = 350; data.params.frameborder = '0'; data.type = 'iframe'; src = 'http://maps.google.com/maps/ms?msid=' + src.match(/msid=(.+)/)[1] + "&output=embed"; setVal('src', src); setVal('media_type', data.type); } if (data.type == 'video') { if (!data.video.sources) data.video.sources = []; data.video.sources[0] = {src : src}; src = getVal("video_altsource1"); if (src) data.video.sources[1] = {src : src}; src = getVal("video_altsource2"); if (src) data.video.sources[2] = {src : src}; } else if (data.type == 'audio') { if (!data.video.sources) data.video.sources = []; data.video.sources[0] = {src : src}; src = getVal("audio_altsource1"); if (src) data.video.sources[1] = {src : src}; src = getVal("audio_altsource2"); if (src) data.video.sources[2] = {src : src}; } else data.params.src = src; // Set default size setVal('width', data.width || (data.type == 'audio' ? 300 : 320)); setVal('height', data.height || (data.type == 'audio' ? 32 : 240)); } }, dataToForm : function() { this.moveStates(true); }, formToData : function(field) { if (field == "width" || field == "height") this.changeSize(field); if (field == 'source') { this.moveStates(false, field); setVal('source', this.editor.plugins.media.dataToHtml(this.data)); this.panel = 'source'; } else { if (this.panel == 'source') { this.data = clone(this.editor.plugins.media.htmlToData(getVal('source'))); this.dataToForm(); this.panel = ''; } this.moveStates(false, field); this.preview(); } }, beforeResize : function() { this.width = parseInt(getVal('width') || (this.data.type == 'audio' ? "300" : "320"), 10); this.height = parseInt(getVal('height') || (this.data.type == 'audio' ? "32" : "240"), 10); }, changeSize : function(type) { var width, height, scale, size; if (get('constrain').checked) { width = parseInt(getVal('width') || (this.data.type == 'audio' ? "300" : "320"), 10); height = parseInt(getVal('height') || (this.data.type == 'audio' ? "32" : "240"), 10); if (type == 'width') { this.height = Math.round((width / this.width) * height); setVal('height', this.height); } else { this.width = Math.round((height / this.height) * width); setVal('width', this.width); } } }, getMediaListHTML : function() { if (typeof(tinyMCEMediaList) != "undefined" && tinyMCEMediaList.length > 0) { var html = ""; html += '<select id="linklist" name="linklist" style="width: 250px" onchange="this.form.src.value=this.options[this.selectedIndex].value;Media.formToData(\'src\');">'; html += '<option value="">---</option>'; for (var i=0; i<tinyMCEMediaList.length; i++) html += '<option value="' + tinyMCEMediaList[i][1] + '">' + tinyMCEMediaList[i][0] + '</option>'; html += '</select>'; return html; } return ""; }, getMediaTypeHTML : function(editor) { function option(media_type, element) { if (!editor.schema.getElementRule(element || media_type)) { return ''; } return '<option value="'+media_type+'">'+tinyMCEPopup.editor.translate("media_dlg."+media_type)+'</option>' } var html = ""; html += '<select id="media_type" name="media_type" onchange="Media.formToData(\'type\');">'; html += option("video"); html += option("audio"); html += option("flash", "object"); html += option("quicktime", "object"); html += option("shockwave", "object"); html += option("windowsmedia", "object"); html += option("realmedia", "object"); html += option("iframe"); if (editor.getParam('media_embedded_audio', false)) { html += option('embeddedaudio', "object"); } html += '</select>'; return html; }, setDefaultDialogSettings : function(editor) { var defaultDialogSettings = editor.getParam("media_dialog_defaults", {}); tinymce.each(defaultDialogSettings, function(v, k) { setVal(k, v); }); } }; tinyMCEPopup.requireLangPack(); tinyMCEPopup.onInit.add(function() { Media.init(); }); })();
JavaScript
/** * This script contains embed functions for common plugins. This scripts are complety free to use for any purpose. */ function writeFlash(p) { writeEmbed( 'D27CDB6E-AE6D-11cf-96B8-444553540000', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0', 'application/x-shockwave-flash', p ); } function writeShockWave(p) { writeEmbed( '166B1BCA-3F9C-11CF-8075-444553540000', 'http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab#version=8,5,1,0', 'application/x-director', p ); } function writeQuickTime(p) { writeEmbed( '02BF25D5-8C17-4B23-BC80-D3488ABDDC6B', 'http://www.apple.com/qtactivex/qtplugin.cab#version=6,0,2,0', 'video/quicktime', p ); } function writeRealMedia(p) { writeEmbed( 'CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0', 'audio/x-pn-realaudio-plugin', p ); } function writeWindowsMedia(p) { p.url = p.src; writeEmbed( '6BF52A52-394A-11D3-B153-00C04F79FAA6', 'http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701', 'application/x-mplayer2', p ); } function writeEmbed(cls, cb, mt, p) { var h = '', n; h += '<object classid="clsid:' + cls + '" codebase="' + cb + '"'; h += typeof(p.id) != "undefined" ? 'id="' + p.id + '"' : ''; h += typeof(p.name) != "undefined" ? 'name="' + p.name + '"' : ''; h += typeof(p.width) != "undefined" ? 'width="' + p.width + '"' : ''; h += typeof(p.height) != "undefined" ? 'height="' + p.height + '"' : ''; h += typeof(p.align) != "undefined" ? 'align="' + p.align + '"' : ''; h += '>'; for (n in p) h += '<param name="' + n + '" value="' + p[n] + '">'; h += '<embed type="' + mt + '"'; for (n in p) h += n + '="' + p[n] + '" '; h += '></embed></object>'; document.write(h); }
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { var rootAttributes = tinymce.explode('id,name,width,height,style,align,class,hspace,vspace,bgcolor,type'), excludedAttrs = tinymce.makeMap(rootAttributes.join(',')), Node = tinymce.html.Node, mediaTypes, scriptRegExp, JSON = tinymce.util.JSON, mimeTypes; // Media types supported by this plugin mediaTypes = [ // Type, clsid:s, mime types, codebase ["Flash", "d27cdb6e-ae6d-11cf-96b8-444553540000", "application/x-shockwave-flash", "http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"], ["ShockWave", "166b1bca-3f9c-11cf-8075-444553540000", "application/x-director", "http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab#version=8,5,1,0"], ["WindowsMedia", "6bf52a52-394a-11d3-b153-00c04f79faa6,22d6f312-b0f6-11d0-94ab-0080c74c7e95,05589fa1-c356-11ce-bf01-00aa0055595a", "application/x-mplayer2", "http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701"], ["QuickTime", "02bf25d5-8c17-4b23-bc80-d3488abddc6b", "video/quicktime", "http://www.apple.com/qtactivex/qtplugin.cab#version=6,0,2,0"], ["RealMedia", "cfcdaa03-8be4-11cf-b84b-0020afbbccfa", "audio/x-pn-realaudio-plugin", "http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"], ["Java", "8ad9c840-044e-11d1-b3e9-00805f499d93", "application/x-java-applet", "http://java.sun.com/products/plugin/autodl/jinstall-1_5_0-windows-i586.cab#Version=1,5,0,0"], ["Silverlight", "dfeaf541-f3e1-4c24-acac-99c30715084a", "application/x-silverlight-2"], ["Iframe"], ["Video"], ["EmbeddedAudio"], ["Audio"] ]; function normalizeSize(size) { return typeof(size) == "string" ? size.replace(/[^0-9%]/g, '') : size; } function toArray(obj) { var undef, out, i; if (obj && !obj.splice) { out = []; for (i = 0; true; i++) { if (obj[i]) out[i] = obj[i]; else break; } return out; } return obj; }; tinymce.create('tinymce.plugins.MediaPlugin', { init : function(ed, url) { var self = this, lookup = {}, i, y, item, name; function isMediaImg(node) { return node && node.nodeName === 'IMG' && ed.dom.hasClass(node, 'mceItemMedia'); }; self.editor = ed; self.url = url; // Parse media types into a lookup table scriptRegExp = ''; for (i = 0; i < mediaTypes.length; i++) { name = mediaTypes[i][0]; item = { name : name, clsids : tinymce.explode(mediaTypes[i][1] || ''), mimes : tinymce.explode(mediaTypes[i][2] || ''), codebase : mediaTypes[i][3] }; for (y = 0; y < item.clsids.length; y++) lookup['clsid:' + item.clsids[y]] = item; for (y = 0; y < item.mimes.length; y++) lookup[item.mimes[y]] = item; lookup['mceItem' + name] = item; lookup[name.toLowerCase()] = item; scriptRegExp += (scriptRegExp ? '|' : '') + name; } // Handle the media_types setting tinymce.each(ed.getParam("media_types", "video=mp4,m4v,ogv,webm;" + "silverlight=xap;" + "flash=swf,flv;" + "shockwave=dcr;" + "quicktime=mov,qt,mpg,mpeg;" + "shockwave=dcr;" + "windowsmedia=avi,wmv,wm,asf,asx,wmx,wvx;" + "realmedia=rm,ra,ram;" + "java=jar;" + "audio=mp3,ogg" ).split(';'), function(item) { var i, extensions, type; item = item.split(/=/); extensions = tinymce.explode(item[1].toLowerCase()); for (i = 0; i < extensions.length; i++) { type = lookup[item[0].toLowerCase()]; if (type) lookup[extensions[i]] = type; } }); scriptRegExp = new RegExp('write(' + scriptRegExp + ')\\(([^)]+)\\)'); self.lookup = lookup; ed.onPreInit.add(function() { // Allow video elements ed.schema.addValidElements('object[id|style|width|height|classid|codebase|*],param[name|value],embed[id|style|width|height|type|src|*],video[*],audio[*],source[*]'); // Convert video elements to image placeholder ed.parser.addNodeFilter('object,embed,video,audio,script,iframe', function(nodes) { var i = nodes.length; while (i--) self.objectToImg(nodes[i]); }); // Convert image placeholders to video elements ed.serializer.addNodeFilter('img', function(nodes, name, args) { var i = nodes.length, node; while (i--) { node = nodes[i]; if ((node.attr('class') || '').indexOf('mceItemMedia') !== -1) self.imgToObject(node, args); } }); }); ed.onInit.add(function() { // Display "media" instead of "img" in element path if (ed.theme && ed.theme.onResolveName) { ed.theme.onResolveName.add(function(theme, path_object) { if (path_object.name === 'img' && ed.dom.hasClass(path_object.node, 'mceItemMedia')) path_object.name = 'media'; }); } // Add contect menu if it's loaded if (ed && ed.plugins.contextmenu) { ed.plugins.contextmenu.onContextMenu.add(function(plugin, menu, element) { if (element.nodeName === 'IMG' && element.className.indexOf('mceItemMedia') !== -1) menu.add({title : 'media.edit', icon : 'media', cmd : 'mceMedia'}); }); } }); // Register commands ed.addCommand('mceMedia', function() { var data, img; img = ed.selection.getNode(); if (isMediaImg(img)) { data = ed.dom.getAttrib(img, 'data-mce-json'); if (data) { data = JSON.parse(data); // Add some extra properties to the data object tinymce.each(rootAttributes, function(name) { var value = ed.dom.getAttrib(img, name); if (value) data[name] = value; }); data.type = self.getType(img.className).name.toLowerCase(); } } if (!data) { data = { type : 'flash', video: {sources:[]}, params: {} }; } ed.windowManager.open({ file : url + '/media.htm', width : 430 + parseInt(ed.getLang('media.delta_width', 0)), height : 500 + parseInt(ed.getLang('media.delta_height', 0)), inline : 1 }, { plugin_url : url, data : data }); }); // Register buttons ed.addButton('media', {title : 'media.desc', cmd : 'mceMedia'}); // Update media selection status ed.onNodeChange.add(function(ed, cm, node) { cm.setActive('media', isMediaImg(node)); }); }, convertUrl : function(url, force_absolute) { var self = this, editor = self.editor, settings = editor.settings, urlConverter = settings.url_converter, urlConverterScope = settings.url_converter_scope || self; if (!url) return url; if (force_absolute) return editor.documentBaseURI.toAbsolute(url); return urlConverter.call(urlConverterScope, url, 'src', 'object'); }, getInfo : function() { return { longname : 'Media', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/media', version : tinymce.majorVersion + "." + tinymce.minorVersion }; }, /** * Converts the JSON data object to an img node. */ dataToImg : function(data, force_absolute) { var self = this, editor = self.editor, baseUri = editor.documentBaseURI, sources, attrs, img, i; data.params.src = self.convertUrl(data.params.src, force_absolute); attrs = data.video.attrs; if (attrs) attrs.src = self.convertUrl(attrs.src, force_absolute); if (attrs) attrs.poster = self.convertUrl(attrs.poster, force_absolute); sources = toArray(data.video.sources); if (sources) { for (i = 0; i < sources.length; i++) sources[i].src = self.convertUrl(sources[i].src, force_absolute); } img = self.editor.dom.create('img', { id : data.id, style : data.style, align : data.align, hspace : data.hspace, vspace : data.vspace, src : self.editor.theme.url + '/img/trans.gif', 'class' : 'mceItemMedia mceItem' + self.getType(data.type).name, 'data-mce-json' : JSON.serialize(data, "'") }); img.width = data.width = normalizeSize(data.width || (data.type == 'audio' ? "300" : "320")); img.height = data.height = normalizeSize(data.height || (data.type == 'audio' ? "32" : "240")); return img; }, /** * Converts the JSON data object to a HTML string. */ dataToHtml : function(data, force_absolute) { return this.editor.serializer.serialize(this.dataToImg(data, force_absolute), {forced_root_block : '', force_absolute : force_absolute}); }, /** * Converts the JSON data object to a HTML string. */ htmlToData : function(html) { var fragment, img, data; data = { type : 'flash', video: {sources:[]}, params: {} }; fragment = this.editor.parser.parse(html); img = fragment.getAll('img')[0]; if (img) { data = JSON.parse(img.attr('data-mce-json')); data.type = this.getType(img.attr('class')).name.toLowerCase(); // Add some extra properties to the data object tinymce.each(rootAttributes, function(name) { var value = img.attr(name); if (value) data[name] = value; }); } return data; }, /** * Get type item by extension, class, clsid or mime type. * * @method getType * @param {String} value Value to get type item by. * @return {Object} Type item object or undefined. */ getType : function(value) { var i, values, typeItem; // Find type by checking the classes values = tinymce.explode(value, ' '); for (i = 0; i < values.length; i++) { typeItem = this.lookup[values[i]]; if (typeItem) return typeItem; } }, /** * Converts a tinymce.html.Node image element to video/object/embed. */ imgToObject : function(node, args) { var self = this, editor = self.editor, video, object, embed, iframe, name, value, data, source, sources, params, param, typeItem, i, item, mp4Source, replacement, posterSrc, style, audio; // Adds the flash player function addPlayer(video_src, poster_src) { var baseUri, flashVars, flashVarsOutput, params, flashPlayer; flashPlayer = editor.getParam('flash_video_player_url', self.convertUrl(self.url + '/moxieplayer.swf')); if (flashPlayer) { baseUri = editor.documentBaseURI; data.params.src = flashPlayer; // Convert the movie url to absolute urls if (editor.getParam('flash_video_player_absvideourl', true)) { video_src = baseUri.toAbsolute(video_src || '', true); poster_src = baseUri.toAbsolute(poster_src || '', true); } // Generate flash vars flashVarsOutput = ''; flashVars = editor.getParam('flash_video_player_flashvars', {url : '$url', poster : '$poster'}); tinymce.each(flashVars, function(value, name) { // Replace $url and $poster variables in flashvars value value = value.replace(/\$url/, video_src || ''); value = value.replace(/\$poster/, poster_src || ''); if (value.length > 0) flashVarsOutput += (flashVarsOutput ? '&' : '') + name + '=' + escape(value); }); if (flashVarsOutput.length) data.params.flashvars = flashVarsOutput; params = editor.getParam('flash_video_player_params', { allowfullscreen: true, allowscriptaccess: true }); tinymce.each(params, function(value, name) { data.params[name] = "" + value; }); } }; data = node.attr('data-mce-json'); if (!data) return; data = JSON.parse(data); typeItem = this.getType(node.attr('class')); style = node.attr('data-mce-style'); if (!style) { style = node.attr('style'); if (style) style = editor.dom.serializeStyle(editor.dom.parseStyle(style, 'img')); } // Use node width/height to override the data width/height when the placeholder is resized data.width = node.attr('width') || data.width; data.height = node.attr('height') || data.height; // Handle iframe if (typeItem.name === 'Iframe') { replacement = new Node('iframe', 1); tinymce.each(rootAttributes, function(name) { var value = node.attr(name); if (name == 'class' && value) value = value.replace(/mceItem.+ ?/g, ''); if (value && value.length > 0) replacement.attr(name, value); }); for (name in data.params) replacement.attr(name, data.params[name]); replacement.attr({ style: style, src: data.params.src }); node.replace(replacement); return; } // Handle scripts if (this.editor.settings.media_use_script) { replacement = new Node('script', 1).attr('type', 'text/javascript'); value = new Node('#text', 3); value.value = 'write' + typeItem.name + '(' + JSON.serialize(tinymce.extend(data.params, { width: node.attr('width'), height: node.attr('height') })) + ');'; replacement.append(value); node.replace(replacement); return; } // Add HTML5 video element if (typeItem.name === 'Video' && data.video.sources && data.video.sources[0]) { // Create new object element video = new Node('video', 1).attr(tinymce.extend({ id : node.attr('id'), width: normalizeSize(node.attr('width')), height: normalizeSize(node.attr('height')), style : style }, data.video.attrs)); // Get poster source and use that for flash fallback if (data.video.attrs) posterSrc = data.video.attrs.poster; sources = data.video.sources = toArray(data.video.sources); for (i = 0; i < sources.length; i++) { if (/\.mp4$/.test(sources[i].src)) mp4Source = sources[i].src; } if (!sources[0].type) { video.attr('src', sources[0].src); sources.splice(0, 1); } for (i = 0; i < sources.length; i++) { source = new Node('source', 1).attr(sources[i]); source.shortEnded = true; video.append(source); } // Create flash fallback for video if we have a mp4 source if (mp4Source) { addPlayer(mp4Source, posterSrc); typeItem = self.getType('flash'); } else data.params.src = ''; } // Add HTML5 audio element if (typeItem.name === 'Audio' && data.video.sources && data.video.sources[0]) { // Create new object element audio = new Node('audio', 1).attr(tinymce.extend({ id : node.attr('id'), width: normalizeSize(node.attr('width')), height: normalizeSize(node.attr('height')), style : style }, data.video.attrs)); // Get poster source and use that for flash fallback if (data.video.attrs) posterSrc = data.video.attrs.poster; sources = data.video.sources = toArray(data.video.sources); if (!sources[0].type) { audio.attr('src', sources[0].src); sources.splice(0, 1); } for (i = 0; i < sources.length; i++) { source = new Node('source', 1).attr(sources[i]); source.shortEnded = true; audio.append(source); } data.params.src = ''; } if (typeItem.name === 'EmbeddedAudio') { embed = new Node('embed', 1); embed.shortEnded = true; embed.attr({ id: node.attr('id'), width: normalizeSize(node.attr('width')), height: normalizeSize(node.attr('height')), style : style, type: node.attr('type') }); for (name in data.params) embed.attr(name, data.params[name]); tinymce.each(rootAttributes, function(name) { if (data[name] && name != 'type') embed.attr(name, data[name]); }); data.params.src = ''; } // Do we have a params src then we can generate object if (data.params.src) { // Is flv movie add player for it if (/\.flv$/i.test(data.params.src)) addPlayer(data.params.src, ''); if (args && args.force_absolute) data.params.src = editor.documentBaseURI.toAbsolute(data.params.src); // Create new object element object = new Node('object', 1).attr({ id : node.attr('id'), width: normalizeSize(node.attr('width')), height: normalizeSize(node.attr('height')), style : style }); tinymce.each(rootAttributes, function(name) { var value = data[name]; if (name == 'class' && value) value = value.replace(/mceItem.+ ?/g, ''); if (value && name != 'type') object.attr(name, value); }); // Add params for (name in data.params) { param = new Node('param', 1); param.shortEnded = true; value = data.params[name]; // Windows media needs to use url instead of src for the media URL if (name === 'src' && typeItem.name === 'WindowsMedia') name = 'url'; param.attr({name: name, value: value}); object.append(param); } // Setup add type and classid if strict is disabled if (this.editor.getParam('media_strict', true)) { object.attr({ data: data.params.src, type: typeItem.mimes[0] }); } else { if ( typeItem.clsids ) object.attr('clsid', typeItem.clsids[0]); object.attr('codebase', typeItem.codebase); embed = new Node('embed', 1); embed.shortEnded = true; embed.attr({ id: node.attr('id'), width: normalizeSize(node.attr('width')), height: normalizeSize(node.attr('height')), style : style, type: typeItem.mimes[0] }); for (name in data.params) embed.attr(name, data.params[name]); tinymce.each(rootAttributes, function(name) { if (data[name] && name != 'type') embed.attr(name, data[name]); }); object.append(embed); } // Insert raw HTML if (data.object_html) { value = new Node('#text', 3); value.raw = true; value.value = data.object_html; object.append(value); } // Append object to video element if it exists if (video) video.append(object); } if (video) { // Insert raw HTML if (data.video_html) { value = new Node('#text', 3); value.raw = true; value.value = data.video_html; video.append(value); } } if (audio) { // Insert raw HTML if (data.video_html) { value = new Node('#text', 3); value.raw = true; value.value = data.video_html; audio.append(value); } } var n = video || audio || object || embed; if (n) node.replace(n); else node.remove(); }, /** * Converts a tinymce.html.Node video/object/embed to an img element. * * The video/object/embed will be converted into an image placeholder with a JSON data attribute like this: * <img class="mceItemMedia mceItemFlash" width="100" height="100" data-mce-json="{..}" /> * * The JSON structure will be like this: * {'params':{'flashvars':'something','quality':'high','src':'someurl'}, 'video':{'sources':[{src: 'someurl', type: 'video/mp4'}]}} */ objectToImg : function(node) { var object, embed, video, iframe, img, name, id, width, height, style, i, html, param, params, source, sources, data, type, lookup = this.lookup, matches, attrs, urlConverter = this.editor.settings.url_converter, urlConverterScope = this.editor.settings.url_converter_scope, hspace, vspace, align, bgcolor; function getInnerHTML(node) { return new tinymce.html.Serializer({ inner: true, validate: false }).serialize(node); }; function lookupAttribute(o, attr) { return lookup[(o.attr(attr) || '').toLowerCase()]; } function lookupExtension(src) { var ext = src.replace(/^.*\.([^.]+)$/, '$1'); return lookup[ext.toLowerCase() || '']; } // If node isn't in document if (!node.parent) return; // Handle media scripts if (node.name === 'script') { if (node.firstChild) matches = scriptRegExp.exec(node.firstChild.value); if (!matches) return; type = matches[1]; data = {video : {}, params : JSON.parse(matches[2])}; width = data.params.width; height = data.params.height; } // Setup data objects data = data || { video : {}, params : {} }; // Setup new image object img = new Node('img', 1); img.attr({ src : this.editor.theme.url + '/img/trans.gif' }); // Video element name = node.name; if (name === 'video' || name == 'audio') { video = node; object = node.getAll('object')[0]; embed = node.getAll('embed')[0]; width = video.attr('width'); height = video.attr('height'); id = video.attr('id'); data.video = {attrs : {}, sources : []}; // Get all video attributes attrs = data.video.attrs; for (name in video.attributes.map) attrs[name] = video.attributes.map[name]; source = node.attr('src'); if (source) data.video.sources.push({src : urlConverter.call(urlConverterScope, source, 'src', node.name)}); // Get all sources sources = video.getAll("source"); for (i = 0; i < sources.length; i++) { source = sources[i].remove(); data.video.sources.push({ src: urlConverter.call(urlConverterScope, source.attr('src'), 'src', 'source'), type: source.attr('type'), media: source.attr('media') }); } // Convert the poster URL if (attrs.poster) attrs.poster = urlConverter.call(urlConverterScope, attrs.poster, 'poster', node.name); } // Object element if (node.name === 'object') { object = node; embed = node.getAll('embed')[0]; } // Embed element if (node.name === 'embed') embed = node; // Iframe element if (node.name === 'iframe') { iframe = node; type = 'Iframe'; } if (object) { // Get width/height width = width || object.attr('width'); height = height || object.attr('height'); style = style || object.attr('style'); id = id || object.attr('id'); hspace = hspace || object.attr('hspace'); vspace = vspace || object.attr('vspace'); align = align || object.attr('align'); bgcolor = bgcolor || object.attr('bgcolor'); data.name = object.attr('name'); // Get all object params params = object.getAll("param"); for (i = 0; i < params.length; i++) { param = params[i]; name = param.remove().attr('name'); if (!excludedAttrs[name]) data.params[name] = param.attr('value'); } data.params.src = data.params.src || object.attr('data'); } if (embed) { // Get width/height width = width || embed.attr('width'); height = height || embed.attr('height'); style = style || embed.attr('style'); id = id || embed.attr('id'); hspace = hspace || embed.attr('hspace'); vspace = vspace || embed.attr('vspace'); align = align || embed.attr('align'); bgcolor = bgcolor || embed.attr('bgcolor'); // Get all embed attributes for (name in embed.attributes.map) { if (!excludedAttrs[name] && !data.params[name]) data.params[name] = embed.attributes.map[name]; } } if (iframe) { // Get width/height width = normalizeSize(iframe.attr('width')); height = normalizeSize(iframe.attr('height')); style = style || iframe.attr('style'); id = iframe.attr('id'); hspace = iframe.attr('hspace'); vspace = iframe.attr('vspace'); align = iframe.attr('align'); bgcolor = iframe.attr('bgcolor'); tinymce.each(rootAttributes, function(name) { img.attr(name, iframe.attr(name)); }); // Get all iframe attributes for (name in iframe.attributes.map) { if (!excludedAttrs[name] && !data.params[name]) data.params[name] = iframe.attributes.map[name]; } } // Use src not movie if (data.params.movie) { data.params.src = data.params.src || data.params.movie; delete data.params.movie; } // Convert the URL to relative/absolute depending on configuration if (data.params.src) data.params.src = urlConverter.call(urlConverterScope, data.params.src, 'src', 'object'); if (video) { if (node.name === 'video') type = lookup.video.name; else if (node.name === 'audio') type = lookup.audio.name; } if (object && !type) type = (lookupAttribute(object, 'clsid') || lookupAttribute(object, 'classid') || lookupAttribute(object, 'type') || {}).name; if (embed && !type) type = (lookupAttribute(embed, 'type') || lookupExtension(data.params.src) || {}).name; // for embedded audio we preserve the original specified type if (embed && type == 'EmbeddedAudio') { data.params.type = embed.attr('type'); } // Replace the video/object/embed element with a placeholder image containing the data node.replace(img); // Remove embed if (embed) embed.remove(); // Serialize the inner HTML of the object element if (object) { html = getInnerHTML(object.remove()); if (html) data.object_html = html; } // Serialize the inner HTML of the video element if (video) { html = getInnerHTML(video.remove()); if (html) data.video_html = html; } data.hspace = hspace; data.vspace = vspace; data.align = align; data.bgcolor = bgcolor; // Set width/height of placeholder img.attr({ id : id, 'class' : 'mceItemMedia mceItem' + (type || 'Flash'), style : style, width : width || (node.name == 'audio' ? "300" : "320"), height : height || (node.name == 'audio' ? "32" : "240"), hspace : hspace, vspace : vspace, align : align, bgcolor : bgcolor, "data-mce-json" : JSON.serialize(data, "'") }); } }); // Register plugin tinymce.PluginManager.add('media', tinymce.plugins.MediaPlugin); })();
JavaScript
(function() { tinymce.create('tinymce.plugins.wpGallery', { init : function(ed, url) { var t = this; t.url = url; t.editor = ed; t._createButtons(); // Register the command so that it can be invoked by using tinyMCE.activeEditor.execCommand('...'); ed.addCommand('WP_Gallery', function() { if ( tinymce.isIE ) ed.selection.moveToBookmark( ed.wpGalleryBookmark ); var el = ed.selection.getNode(), gallery = wp.media.gallery, frame; // Check if the `wp.media.gallery` API exists. if ( typeof wp === 'undefined' || ! wp.media || ! wp.media.gallery ) return; // Make sure we've selected a gallery node. if ( el.nodeName != 'IMG' || ed.dom.getAttrib(el, 'class').indexOf('wp-gallery') == -1 ) return; frame = gallery.edit( '[' + ed.dom.getAttrib( el, 'title' ) + ']' ); frame.state('gallery-edit').on( 'update', function( selection ) { var shortcode = gallery.shortcode( selection ).string().slice( 1, -1 ); ed.dom.setAttrib( el, 'title', shortcode ); }); }); ed.onInit.add(function(ed) { // iOS6 doesn't show the buttons properly on click, show them on 'touchstart' if ( 'ontouchstart' in window ) { ed.dom.events.add(ed.getBody(), 'touchstart', function(e){ var target = e.target; if ( target.nodeName == 'IMG' && ed.dom.hasClass(target, 'wp-gallery') ) { ed.selection.select(target); ed.dom.events.cancel(e); ed.plugins.wordpress._hideButtons(); ed.plugins.wordpress._showButtons(target, 'wp_gallerybtns'); } }); } }); ed.onMouseDown.add(function(ed, e) { if ( e.target.nodeName == 'IMG' && ed.dom.hasClass(e.target, 'wp-gallery') ) { ed.plugins.wordpress._hideButtons(); ed.plugins.wordpress._showButtons(e.target, 'wp_gallerybtns'); } }); ed.onBeforeSetContent.add(function(ed, o) { o.content = t._do_gallery(o.content); }); ed.onPostProcess.add(function(ed, o) { if (o.get) o.content = t._get_gallery(o.content); }); }, _do_gallery : function(co) { return co.replace(/\[gallery([^\]]*)\]/g, function(a,b){ return '<img src="'+tinymce.baseURL+'/plugins/wpgallery/img/t.gif" class="wp-gallery mceItem" title="gallery'+tinymce.DOM.encode(b)+'" />'; }); }, _get_gallery : function(co) { function getAttr(s, n) { n = new RegExp(n + '=\"([^\"]+)\"', 'g').exec(s); return n ? tinymce.DOM.decode(n[1]) : ''; }; return co.replace(/(?:<p[^>]*>)*(<img[^>]+>)(?:<\/p>)*/g, function(a,im) { var cls = getAttr(im, 'class'); if ( cls.indexOf('wp-gallery') != -1 ) return '<p>['+tinymce.trim(getAttr(im, 'title'))+']</p>'; return a; }); }, _createButtons : function() { var t = this, ed = tinymce.activeEditor, DOM = tinymce.DOM, editButton, dellButton, isRetina; if ( DOM.get('wp_gallerybtns') ) return; isRetina = ( window.devicePixelRatio && window.devicePixelRatio > 1 ) || // WebKit, Opera ( window.matchMedia && window.matchMedia('(min-resolution:130dpi)').matches ); // Firefox, IE10, Opera DOM.add(document.body, 'div', { id : 'wp_gallerybtns', style : 'display:none;' }); editButton = DOM.add('wp_gallerybtns', 'img', { src : isRetina ? t.url+'/img/edit-2x.png' : t.url+'/img/edit.png', id : 'wp_editgallery', width : '24', height : '24', title : ed.getLang('wordpress.editgallery') }); tinymce.dom.Event.add(editButton, 'mousedown', function(e) { var ed = tinymce.activeEditor; ed.wpGalleryBookmark = ed.selection.getBookmark('simple'); ed.execCommand("WP_Gallery"); ed.plugins.wordpress._hideButtons(); }); dellButton = DOM.add('wp_gallerybtns', 'img', { src : isRetina ? t.url+'/img/delete-2x.png' : t.url+'/img/delete.png', id : 'wp_delgallery', width : '24', height : '24', title : ed.getLang('wordpress.delgallery') }); tinymce.dom.Event.add(dellButton, 'mousedown', function(e) { var ed = tinymce.activeEditor, el = ed.selection.getNode(); if ( el.nodeName == 'IMG' && ed.dom.hasClass(el, 'wp-gallery') ) { ed.dom.remove(el); ed.execCommand('mceRepaint'); ed.dom.events.cancel(e); } ed.plugins.wordpress._hideButtons(); }); }, getInfo : function() { return { longname : 'Gallery Settings', author : 'WordPress', authorurl : 'http://wordpress.org', infourl : '', version : "1.0" }; } }); tinymce.PluginManager.add('wpgallery', tinymce.plugins.wpGallery); })();
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { var DOM = tinymce.DOM; tinymce.create('tinymce.plugins.FullScreenPlugin', { init : function(ed, url) { var t = this, s = {}, vp, posCss; t.editor = ed; // Register commands ed.addCommand('mceFullScreen', function() { var win, de = DOM.doc.documentElement; if (ed.getParam('fullscreen_is_enabled')) { if (ed.getParam('fullscreen_new_window')) closeFullscreen(); // Call to close in new window else { DOM.win.setTimeout(function() { tinymce.dom.Event.remove(DOM.win, 'resize', t.resizeFunc); tinyMCE.get(ed.getParam('fullscreen_editor_id')).setContent(ed.getContent()); tinyMCE.remove(ed); DOM.remove('mce_fullscreen_container'); de.style.overflow = ed.getParam('fullscreen_html_overflow'); DOM.setStyle(DOM.doc.body, 'overflow', ed.getParam('fullscreen_overflow')); DOM.win.scrollTo(ed.getParam('fullscreen_scrollx'), ed.getParam('fullscreen_scrolly')); tinyMCE.settings = tinyMCE.oldSettings; // Restore old settings }, 10); } return; } if (ed.getParam('fullscreen_new_window')) { win = DOM.win.open(url + "/fullscreen.htm", "mceFullScreenPopup", "fullscreen=yes,menubar=no,toolbar=no,scrollbars=no,resizable=yes,left=0,top=0,width=" + screen.availWidth + ",height=" + screen.availHeight); try { win.resizeTo(screen.availWidth, screen.availHeight); } catch (e) { // Ignore } } else { tinyMCE.oldSettings = tinyMCE.settings; // Store old settings s.fullscreen_overflow = DOM.getStyle(DOM.doc.body, 'overflow', 1) || 'auto'; s.fullscreen_html_overflow = DOM.getStyle(de, 'overflow', 1); vp = DOM.getViewPort(); s.fullscreen_scrollx = vp.x; s.fullscreen_scrolly = vp.y; // Fixes an Opera bug where the scrollbars doesn't reappear if (tinymce.isOpera && s.fullscreen_overflow == 'visible') s.fullscreen_overflow = 'auto'; // Fixes an IE bug where horizontal scrollbars would appear if (tinymce.isIE && s.fullscreen_overflow == 'scroll') s.fullscreen_overflow = 'auto'; // Fixes an IE bug where the scrollbars doesn't reappear if (tinymce.isIE && (s.fullscreen_html_overflow == 'visible' || s.fullscreen_html_overflow == 'scroll')) s.fullscreen_html_overflow = 'auto'; if (s.fullscreen_overflow == '0px') s.fullscreen_overflow = ''; DOM.setStyle(DOM.doc.body, 'overflow', 'hidden'); de.style.overflow = 'hidden'; //Fix for IE6/7 vp = DOM.getViewPort(); DOM.win.scrollTo(0, 0); if (tinymce.isIE) vp.h -= 1; // Use fixed position if it exists if (tinymce.isIE6 || document.compatMode == 'BackCompat') posCss = 'absolute;top:' + vp.y; else posCss = 'fixed;top:0'; n = DOM.add(DOM.doc.body, 'div', { id : 'mce_fullscreen_container', style : 'position:' + posCss + ';left:0;width:' + vp.w + 'px;height:' + vp.h + 'px;z-index:200000;'}); DOM.add(n, 'div', {id : 'mce_fullscreen'}); tinymce.each(ed.settings, function(v, n) { s[n] = v; }); s.id = 'mce_fullscreen'; s.width = n.clientWidth; s.height = n.clientHeight - 15; s.fullscreen_is_enabled = true; s.fullscreen_editor_id = ed.id; s.theme_advanced_resizing = false; s.save_onsavecallback = function() { ed.setContent(tinyMCE.get(s.id).getContent()); ed.execCommand('mceSave'); }; tinymce.each(ed.getParam('fullscreen_settings'), function(v, k) { s[k] = v; }); if (s.theme_advanced_toolbar_location === 'external') s.theme_advanced_toolbar_location = 'top'; t.fullscreenEditor = new tinymce.Editor('mce_fullscreen', s); t.fullscreenEditor.onInit.add(function() { t.fullscreenEditor.setContent(ed.getContent()); t.fullscreenEditor.focus(); }); t.fullscreenEditor.render(); t.fullscreenElement = new tinymce.dom.Element('mce_fullscreen_container'); t.fullscreenElement.update(); //document.body.overflow = 'hidden'; t.resizeFunc = tinymce.dom.Event.add(DOM.win, 'resize', function() { var vp = tinymce.DOM.getViewPort(), fed = t.fullscreenEditor, outerSize, innerSize; // Get outer/inner size to get a delta size that can be used to calc the new iframe size outerSize = fed.dom.getSize(fed.getContainer().getElementsByTagName('table')[0]); innerSize = fed.dom.getSize(fed.getContainer().getElementsByTagName('iframe')[0]); fed.theme.resizeTo(vp.w - outerSize.w + innerSize.w, vp.h - outerSize.h + innerSize.h); }); } }); // Register buttons ed.addButton('fullscreen', {title : 'fullscreen.desc', cmd : 'mceFullScreen'}); ed.onNodeChange.add(function(ed, cm) { cm.setActive('fullscreen', ed.getParam('fullscreen_is_enabled')); }); }, getInfo : function() { return { longname : 'Fullscreen', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/fullscreen', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); // Register plugin tinymce.PluginManager.add('fullscreen', tinymce.plugins.FullScreenPlugin); })();
JavaScript