code
stringlengths
1
2.08M
language
stringclasses
1 value
/* * Async Treeview 0.1 - Lazy-loading extension for Treeview * * http://bassistance.de/jquery-plugins/jquery-plugin-treeview/ * * Copyright (c) 2007 Jörn Zaefferer * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * Revision: $Id$ * */ ;(function($) { function load(settings, root, child, container) { function createNode(parent) { var current = $("<li/>").attr("id", this.id || "").html("<span>" + this.text + "</span>").appendTo(parent); if (this.classes) { current.children("span").addClass(this.classes); } if (this.expanded) { current.addClass("open"); } if (this.hasChildren || this.children && this.children.length) { var branch = $("<ul/>").appendTo(current); if (this.hasChildren) { current.addClass("hasChildren"); createNode.call({ classes: "placeholder", text: "&nbsp;", children:[] }, branch); } if (this.children && this.children.length) { $.each(this.children, createNode, [branch]) } } } $.ajax($.extend(true, { url: settings.url, dataType: "json", data: { root: root }, success: function(response) { child.empty(); $.each(response, createNode, [child]); $(container).treeview({add: child}); } }, settings.ajax)); /* $.getJSON(settings.url, {root: root}, function(response) { function createNode(parent) { var current = $("<li/>").attr("id", this.id || "").html("<span>" + this.text + "</span>").appendTo(parent); if (this.classes) { current.children("span").addClass(this.classes); } if (this.expanded) { current.addClass("open"); } if (this.hasChildren || this.children && this.children.length) { var branch = $("<ul/>").appendTo(current); if (this.hasChildren) { current.addClass("hasChildren"); createNode.call({ classes: "placeholder", text: "&nbsp;", children:[] }, branch); } if (this.children && this.children.length) { $.each(this.children, createNode, [branch]) } } } child.empty(); $.each(response, createNode, [child]); $(container).treeview({add: child}); }); */ } var proxied = $.fn.treeview; $.fn.treeview = function(settings) { if (!settings.url) { return proxied.apply(this, arguments); } var container = this; if (!container.children().size()) load(settings, "source", this, container); var userToggle = settings.toggle; return proxied.call(this, $.extend({}, settings, { collapsed: true, toggle: function() { var $this = $(this); if ($this.hasClass("hasChildren")) { var childList = $this.removeClass("hasChildren").find("ul"); load(settings, this.id, childList, container); } if (userToggle) { userToggle.apply(this, arguments); } } })); }; })(jQuery);
JavaScript
/** * jQuery Yii plugin file. * * @author Qiang Xue <qiang.xue@gmail.com> * @link http://www.yiiframework.com/ * @copyright Copyright &copy; 2008-2010 Yii Software LLC * @license http://www.yiiframework.com/license/ * @version $Id: jquery.yiitab.js 1827 2010-02-20 00:43:32Z qiang.xue $ */ ;(function($) { $.extend($.fn, { yiitab: function() { function activate(id) { var pos = id.indexOf("#"); if (pos>=0) { id = id.substring(pos); } var $tab=$(id); var $container=$tab.parent(); $container.find('>ul a').removeClass('active'); $container.find('>ul a[href="'+id+'"]').addClass('active'); $container.children('div').hide(); $tab.show(); } this.find('>ul a').click(function(event) { var href=$(this).attr('href'); var pos=href.indexOf('#'); activate(href); if(pos==0 || (pos>0 && (window.location.pathname=='' || window.location.pathname==href.substring(0,pos)))) return false; }); // activate a tab based on the current anchor var url = decodeURI(window.location); var pos = url.indexOf("#"); if (pos >= 0) { var id = url.substring(pos); if (this.find('>ul a[href="'+id+'"]').length > 0) { activate(id); return; } } } }); })(jQuery);
JavaScript
/** * Cookie plugin * * Copyright (c) 2006 Klaus Hartl (stilbuero.de) * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * */ /** * Create a cookie with the given name and value and other optional parameters. * * @example $.cookie('the_cookie', 'the_value'); * @desc Set the value of a cookie. * @example $.cookie('the_cookie', 'the_value', {expires: 7, path: '/', domain: 'jquery.com', secure: true}); * @desc Create a cookie with all available options. * @example $.cookie('the_cookie', 'the_value'); * @desc Create a session cookie. * @example $.cookie('the_cookie', null); * @desc Delete a cookie by passing null as value. * * @param String name The name of the cookie. * @param String value The value of the cookie. * @param Object options An object literal containing key/value pairs to provide optional cookie attributes. * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object. * If a negative value is specified (e.g. a date in the past), the cookie will be deleted. * If set to null or omitted, the cookie will be a session cookie and will not be retained * when the the browser exits. * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie). * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie). * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will * require a secure protocol (like HTTPS). * @type undefined * * @name $.cookie * @cat Plugins/Cookie * @author Klaus Hartl/klaus.hartl@stilbuero.de */ /** * Get the value of a cookie with the given name. * * @example $.cookie('the_cookie'); * @desc Get the value of a cookie. * * @param String name The name of the cookie. * @return The value of the cookie. * @type String * * @name $.cookie * @cat Plugins/Cookie * @author Klaus Hartl/klaus.hartl@stilbuero.de */ jQuery.cookie = function(name, value, options) { if (typeof value != 'undefined') { // name and value given, set cookie options = options || {}; if (value === null) { value = ''; options.expires = -1; } var expires = ''; if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) { var date; if (typeof options.expires == 'number') { date = new Date(); date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000)); } else { date = options.expires; } expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE } var path = options.path ? '; path=' + options.path : ''; var domain = options.domain ? '; domain=' + options.domain : ''; var secure = options.secure ? '; secure' : ''; document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join(''); } else { // only name given, get cookie var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } };
JavaScript
/// <reference path="../../../lib/jquery-1.2.6.js" /> /* Masked Input plugin for jQuery Copyright (c) 2007-2009 Josh Bush (digitalbush.com) Licensed under the MIT license (http://digitalbush.com/projects/masked-input-plugin/#license) Version: 1.2.2 (03/09/2009 22:39:06) */ (function($) { var pasteEventName = ($.browser.msie ? 'paste' : 'input') + ".mask"; var iPhone = (window.orientation != undefined); $.mask = { //Predefined character definitions definitions: { '9': "[0-9]", 'a': "[A-Za-z]", '*': "[A-Za-z0-9]" } }; $.fn.extend({ //Helper Function for Caret positioning caret: function(begin, end) { if (this.length == 0) return; if (typeof begin == 'number') { end = (typeof end == 'number') ? end : begin; return this.each(function() { if (this.setSelectionRange) { this.focus(); this.setSelectionRange(begin, end); } else if (this.createTextRange) { var range = this.createTextRange(); range.collapse(true); range.moveEnd('character', end); range.moveStart('character', begin); range.select(); } }); } else { if (this[0].setSelectionRange) { begin = this[0].selectionStart; end = this[0].selectionEnd; } else if (document.selection && document.selection.createRange) { var range = document.selection.createRange(); begin = 0 - range.duplicate().moveStart('character', -100000); end = begin + range.text.length; } return { begin: begin, end: end }; } }, unmask: function() { return this.trigger("unmask"); }, mask: function(mask, settings) { if (!mask && this.length > 0) { var input = $(this[0]); var tests = input.data("tests"); return $.map(input.data("buffer"), function(c, i) { return tests[i] ? c : null; }).join(''); } settings = $.extend({ placeholder: "_", completed: null }, settings); var defs = $.mask.definitions; var tests = []; var partialPosition = mask.length; var firstNonMaskPos = null; var len = mask.length; $.each(mask.split(""), function(i, c) { if (c == '?') { len--; partialPosition = i; } else if (defs[c]) { tests.push(new RegExp(defs[c])); if(firstNonMaskPos==null) firstNonMaskPos = tests.length - 1; } else { tests.push(null); } }); return this.each(function() { var input = $(this); var buffer = $.map(mask.split(""), function(c, i) { if (c != '?') return defs[c] ? settings.placeholder : c }); var ignore = false; //Variable for ignoring control keys var focusText = input.val(); input.data("buffer", buffer).data("tests", tests); function seekNext(pos) { while (++pos <= len && !tests[pos]); return pos; } function shiftL(pos) { while (!tests[pos] && --pos >= 0); for (var i = pos; i < len; i++) { if (tests[i]) { buffer[i] = settings.placeholder; var j = seekNext(i); if (j < len && tests[i].test(buffer[j])) { buffer[i] = buffer[j]; } else break; } } writeBuffer(); input.caret(Math.max(firstNonMaskPos, pos)); } function shiftR(pos) { for (var i = pos, c = settings.placeholder; i < len; i++) { if (tests[i]) { var j = seekNext(i); var t = buffer[i]; buffer[i] = c; if (j < len && tests[j].test(t)) c = t; else break; } } } function keydownEvent(e) { var pos = $(this).caret(); var k = e.keyCode; ignore = (k < 16 || (k > 16 && k < 32) || (k > 32 && k < 41)); //delete selection before proceeding if ((pos.begin - pos.end) != 0 && (!ignore || k == 8 || k == 46)) clearBuffer(pos.begin, pos.end); //backspace, delete, and escape get special treatment if (k == 8 || k == 46 || (iPhone && k == 127)) {//backspace/delete shiftL(pos.begin + (k == 46 ? 0 : -1)); return false; } else if (k == 27) {//escape input.val(focusText); input.caret(0, checkVal()); return false; } } function keypressEvent(e) { if (ignore) { ignore = false; //Fixes Mac FF bug on backspace return (e.keyCode == 8) ? false : null; } e = e || window.event; var k = e.charCode || e.keyCode || e.which; var pos = $(this).caret(); if (e.ctrlKey || e.altKey || e.metaKey) {//Ignore return true; } else if ((k >= 32 && k <= 125) || k > 186) {//typeable characters var p = seekNext(pos.begin - 1); if (p < len) { var c = String.fromCharCode(k); if (tests[p].test(c)) { shiftR(p); buffer[p] = c; writeBuffer(); var next = seekNext(p); $(this).caret(next); if (settings.completed && next == len) settings.completed.call(input); } } } return false; } function clearBuffer(start, end) { for (var i = start; i < end && i < len; i++) { if (tests[i]) buffer[i] = settings.placeholder; } } function writeBuffer() { return input.val(buffer.join('')).val(); } function checkVal(allow) { //try to place characters where they belong var test = input.val(); var lastMatch = -1; for (var i = 0, pos = 0; i < len; i++) { if (tests[i]) { buffer[i] = settings.placeholder; while (pos++ < test.length) { var c = test.charAt(pos - 1); if (tests[i].test(c)) { buffer[i] = c; lastMatch = i; break; } } if (pos > test.length) break; } else if (buffer[i] == test[pos] && i!=partialPosition) { pos++; lastMatch = i; } } if (!allow && lastMatch + 1 < partialPosition) { input.val(""); clearBuffer(0, len); } else if (allow || lastMatch + 1 >= partialPosition) { writeBuffer(); if (!allow) input.val(input.val().substring(0, lastMatch + 1)); } return (partialPosition ? i : firstNonMaskPos); } if (!input.attr("readonly")) input .one("unmask", function() { input .unbind(".mask") .removeData("buffer") .removeData("tests"); }) .bind("focus.mask", function() { focusText = input.val(); var pos = checkVal(); writeBuffer(); setTimeout(function() { if (pos == mask.length) input.caret(0, pos); else input.caret(pos); }, 0); }) .bind("blur.mask", function() { checkVal(); if (input.val() != focusText) input.change(); }) .bind("keydown.mask", keydownEvent) .bind("keypress.mask", keypressEvent) .bind(pasteEventName, function() { setTimeout(function() { input.caret(checkVal(true)); }, 0); }); checkVal(); //Perform initial check for existing values }); } }); })(jQuery);
JavaScript
$(document).ready(function() { if($('div.form.login').length) { // in login page $('input#LoginForm_password').focus(); } $('table.preview input[name="checkAll"]').click(function() { $('table.preview .confirm input').attr('checked', this.checked); }); $('table.preview td.confirm input').click(function() { $('table.preview input[name="checkAll"]').attr('checked', !$('table.preview td.confirm input:not(:checked)').length); }); $('table.preview input[name="checkAll"]').attr('checked', !$('table.preview td.confirm input:not(:checked)').length); $('.form .row.sticky input:not(.error), .form .row.sticky select:not(.error), .form .row.sticky textarea:not(.error)').each(function(){ var value; if(this.tagName=='SELECT') value=this.options[this.selectedIndex].text; else if(this.tagName=='TEXTAREA') value=$(this).html(); else value=$(this).val(); if(value=='') value='[empty]'; $(this).before('<div class="value">'+value+'</div>').hide(); }); $('.form.gii .row.sticky .value').live('click', function(){ $(this).hide(); $(this).next().show().get(0).focus(); }); $('.form.gii .row input, .form.gii .row textarea, .form.gii .row select, .with-tooltip').not('.no-tooltip, .no-tooltip *').tooltip({ position: "center right", offset: [-2, 10] }); $('.form.gii .row input').change(function(){ $('.form.gii .feedback').hide(); $('.form.gii input[name="generate"]').hide(); }); $('.form.gii .view-code').click(function(){ var title=$(this).attr('rel'); $.fancybox.showActivity(); $.ajax({ type: 'POST', cache: false, url: $(this).attr('href'), data: $('.form.gii form').serializeArray(), success: function(data){ $.fancybox(data, { 'title': title, 'titlePosition': 'inside', 'titleFormat': function(title, currentArray, currentIndex, currentOpts) { return '<div id="tip7-title"><span><a href="javascript:;" onclick="$.fancybox.close();">close</a></span>' + (title && title.length ? '<b>' + title + '</b>' : '' ) + '</div>'; }, 'showCloseButton': false, 'autoDimensions': false, 'width': 900, 'height': 'auto', 'onComplete':function(){ $('#fancybox-inner').scrollTop(0); } }); }, error: function(XMLHttpRequest, textStatus, errorThrown) { $.fancybox('<div class="error">'+XMLHttpRequest.responseText+'</div>'); } }); return false; }); $('#fancybox-inner .close-code').live('click', function(){ $.fancybox.close(); return false; }); });
JavaScript
/** * jQuery Yii plugin file. * * @author Qiang Xue <qiang.xue@gmail.com> * @link http://www.yiiframework.com/ * @copyright Copyright &copy; 2008-2010 Yii Software LLC * @license http://www.yiiframework.com/license/ * @version $Id: jquery.yii.js 3053 2011-03-12 21:25:33Z qiang.xue $ */ ;(function($) { $.yii = { version : '1.0', submitForm : function (element, url, params) { var f = $(element).parents('form')[0]; if (!f) { f = document.createElement('form'); f.style.display = 'none'; element.parentNode.appendChild(f); f.method = 'POST'; } if (typeof url == 'string' && url != '') { f.action = url; } if (element.target != null) { f.target = element.target; } var inputs = []; $.each(params, function(name, value) { var input = document.createElement("input"); input.setAttribute("type", "hidden"); input.setAttribute("name", name); input.setAttribute("value", value); f.appendChild(input); inputs.push(input); }); // remember who triggers the form submission // this is used by jquery.yiiactiveform.js $(f).data('submitObject', $(element)); $(f).trigger('submit'); $.each(inputs, function() { f.removeChild(this); }); } }; })(jQuery);
JavaScript
/* ### jQuery Star Rating Plugin v3.13 - 2009-03-26 ### * Home: http://www.fyneworks.com/jquery/star-rating/ * Code: http://code.google.com/p/jquery-star-rating-plugin/ * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html ### */ /*# AVOID COLLISIONS #*/ ;if(window.jQuery) (function($){ // IE6 Background Image Fix if ($.browser.msie) try { document.execCommand("BackgroundImageCache", false, true)} catch(e) { } // Thanks to http://www.visualjquery.com/rating/rating_redux.html // plugin initialization $.fn.rating = function(options){ if(this.length==0) return this; // quick fail // Handle API methods if(typeof arguments[0]=='string'){ // Perform API methods on individual elements if(this.length>1){ var args = arguments; return this.each(function(){ $.fn.rating.apply($(this), args); }); } // Invoke API method handler $.fn.rating[arguments[0]].apply(this, $.makeArray(arguments).slice(1) || []); // Quick exit... return this; } // Initialize options for this call var options = $.extend( {}/* new object */, $.fn.rating.options/* default options */, options || {} /* just-in-time options */ ); // Allow multiple controls with the same name by making each call unique $.fn.rating.calls++; // loop through each matched element this .not('.star-rating-applied') .addClass('star-rating-applied') .each(function(){ // Load control parameters / find context / etc var control, input = $(this); var eid = (this.name || 'unnamed-rating').replace(/\[|\]/g, '_').replace(/^\_+|\_+$/g,''); var context = $(this.form || document.body); // FIX: http://code.google.com/p/jquery-star-rating-plugin/issues/detail?id=23 var raters = context.data('rating'); if(!raters || raters.call!=$.fn.rating.calls) raters = { count:0, call:$.fn.rating.calls }; var rater = raters[eid]; // if rater is available, verify that the control still exists if(rater) control = rater.data('rating'); if(rater && control)//{// save a byte! // add star to control if rater is available and the same control still exists control.count++; //}// save a byte! else{ // create new control if first star or control element was removed/replaced // Initialize options for this raters control = $.extend( {}/* new object */, options || {} /* current call options */, ($.metadata? input.metadata(): ($.meta?input.data():null)) || {}, /* metadata options */ { count:0, stars: [], inputs: [] } ); // increment number of rating controls control.serial = raters.count++; // create rating element rater = $('<span class="star-rating-control"/>'); input.before(rater); // Mark element for initialization (once all stars are ready) rater.addClass('rating-to-be-drawn'); // Accept readOnly setting from 'disabled' property if(input.attr('disabled')) control.readOnly = true; // Create 'cancel' button rater.append( control.cancel = $('<div class="rating-cancel"><a title="' + control.cancel + '">' + control.cancelValue + '</a></div>') .mouseover(function(){ $(this).rating('drain'); $(this).addClass('star-rating-hover'); //$(this).rating('focus'); }) .mouseout(function(){ $(this).rating('draw'); $(this).removeClass('star-rating-hover'); //$(this).rating('blur'); }) .click(function(){ $(this).rating('select'); }) .data('rating', control) ); } // first element of group // insert rating star var star = $('<div class="star-rating rater-'+ control.serial +'"><a title="' + (this.title || this.value) + '">' + this.value + '</a></div>'); rater.append(star); // inherit attributes from input element if(this.id) star.attr('id', this.id); if(this.className) star.addClass(this.className); // Half-stars? if(control.half) control.split = 2; // Prepare division control if(typeof control.split=='number' && control.split>0){ var stw = ($.fn.width ? star.width() : 0) || control.starWidth; var spi = (control.count % control.split), spw = Math.floor(stw/control.split); star // restrict star's width and hide overflow (already in CSS) .width(spw) // move the star left by using a negative margin // this is work-around to IE's stupid box model (position:relative doesn't work) .find('a').css({ 'margin-left':'-'+ (spi*spw) +'px' }) } // readOnly? if(control.readOnly)//{ //save a byte! // Mark star as readOnly so user can customize display star.addClass('star-rating-readonly'); //} //save a byte! else//{ //save a byte! // Enable hover css effects star.addClass('star-rating-live') // Attach mouse events .mouseover(function(){ $(this).rating('fill'); $(this).rating('focus'); }) .mouseout(function(){ $(this).rating('draw'); $(this).rating('blur'); }) .click(function(){ $(this).rating('select'); }) ; //}; //save a byte! // set current selection if(this.checked) control.current = star; // hide input element input.hide(); // backward compatibility, form element to plugin input.change(function(){ $(this).rating('select'); }); // attach reference to star to input element and vice-versa star.data('rating.input', input.data('rating.star', star)); // store control information in form (or body when form not available) control.stars[control.stars.length] = star[0]; control.inputs[control.inputs.length] = input[0]; control.rater = raters[eid] = rater; control.context = context; input.data('rating', control); rater.data('rating', control); star.data('rating', control); context.data('rating', raters); }); // each element // Initialize ratings (first draw) $('.rating-to-be-drawn').rating('draw').removeClass('rating-to-be-drawn'); return this; // don't break the chain... }; /*--------------------------------------------------------*/ /* ### Core functionality and API ### */ $.extend($.fn.rating, { // Used to append a unique serial number to internal control ID // each time the plugin is invoked so same name controls can co-exist calls: 0, focus: function(){ var control = this.data('rating'); if(!control) return this; if(!control.focus) return this; // quick fail if not required // find data for event var input = $(this).data('rating.input') || $( this.tagName=='INPUT' ? this : null ); // focus handler, as requested by focusdigital.co.uk if(control.focus) control.focus.apply(input[0], [input.val(), $('a', input.data('rating.star'))[0]]); }, // $.fn.rating.focus blur: function(){ var control = this.data('rating'); if(!control) return this; if(!control.blur) return this; // quick fail if not required // find data for event var input = $(this).data('rating.input') || $( this.tagName=='INPUT' ? this : null ); // blur handler, as requested by focusdigital.co.uk if(control.blur) control.blur.apply(input[0], [input.val(), $('a', input.data('rating.star'))[0]]); }, // $.fn.rating.blur fill: function(){ // fill to the current mouse position. var control = this.data('rating'); if(!control) return this; // do not execute when control is in read-only mode if(control.readOnly) return; // Reset all stars and highlight them up to this element this.rating('drain'); this.prevAll().andSelf().filter('.rater-'+ control.serial).addClass('star-rating-hover'); },// $.fn.rating.fill drain: function() { // drain all the stars. var control = this.data('rating'); if(!control) return this; // do not execute when control is in read-only mode if(control.readOnly) return; // Reset all stars control.rater.children().filter('.rater-'+ control.serial).removeClass('star-rating-on').removeClass('star-rating-hover'); },// $.fn.rating.drain draw: function(){ // set value and stars to reflect current selection var control = this.data('rating'); if(!control) return this; // Clear all stars this.rating('drain'); // Set control value if(control.current){ control.current.data('rating.input').attr('checked','checked'); control.current.prevAll().andSelf().filter('.rater-'+ control.serial).addClass('star-rating-on'); } else $(control.inputs).removeAttr('checked'); // Show/hide 'cancel' button control.cancel[control.readOnly || control.required?'hide':'show'](); // Add/remove read-only classes to remove hand pointer this.siblings()[control.readOnly?'addClass':'removeClass']('star-rating-readonly'); },// $.fn.rating.draw select: function(value,wantCallBack){ // select a value // ***** MODIFICATION ***** // Thanks to faivre.thomas - http://code.google.com/p/jquery-star-rating-plugin/issues/detail?id=27 // // ***** LIST OF MODIFICATION ***** // ***** added Parameter wantCallBack : false if you don't want a callback. true or undefined if you want postback to be performed at the end of this method' // ***** recursive calls to this method were like : ... .rating('select') it's now like .rating('select',undefined,wantCallBack); (parameters are set.) // ***** line which is calling callback // ***** /LIST OF MODIFICATION ***** var control = this.data('rating'); if(!control) return this; // do not execute when control is in read-only mode if(control.readOnly) return; // clear selection control.current = null; // programmatically (based on user input) if(typeof value!='undefined'){ // select by index (0 based) if(typeof value=='number') return $(control.stars[value]).rating('select',undefined,wantCallBack); // select by literal value (must be passed as a string if(typeof value=='string') //return $.each(control.stars, function(){ if($(this).data('rating.input').val()==value) $(this).rating('select',undefined,wantCallBack); }); } else control.current = this[0].tagName=='INPUT' ? this.data('rating.star') : (this.is('.rater-'+ control.serial) ? this : null); // Update rating control state this.data('rating', control); // Update display this.rating('draw'); // find data for event var input = $( control.current ? control.current.data('rating.input') : null ); // click callback, as requested here: http://plugins.jquery.com/node/1655 // **** MODIFICATION ***** // Thanks to faivre.thomas - http://code.google.com/p/jquery-star-rating-plugin/issues/detail?id=27 // //old line doing the callback : //if(control.callback) control.callback.apply(input[0], [input.val(), $('a', control.current)[0]]);// callback event // //new line doing the callback (if i want :) if((wantCallBack ||wantCallBack == undefined) && control.callback) control.callback.apply(input[0], [input.val(), $('a', control.current)[0]]);// callback event //to ensure retro-compatibility, wantCallBack must be considered as true by default // **** /MODIFICATION ***** },// $.fn.rating.select readOnly: function(toggle, disable){ // make the control read-only (still submits value) var control = this.data('rating'); if(!control) return this; // setread-only status control.readOnly = toggle || toggle==undefined ? true : false; // enable/disable control value submission if(disable) $(control.inputs).attr("disabled", "disabled"); else $(control.inputs).removeAttr("disabled"); // Update rating control state this.data('rating', control); // Update display this.rating('draw'); },// $.fn.rating.readOnly disable: function(){ // make read-only and never submit value this.rating('readOnly', true, true); },// $.fn.rating.disable enable: function(){ // make read/write and submit value this.rating('readOnly', false, false); }// $.fn.rating.select }); /*--------------------------------------------------------*/ /* ### Default Settings ### eg.: You can override default control like this: $.fn.rating.options.cancel = 'Clear'; */ $.fn.rating.options = { //$.extend($.fn.rating, { options: { cancel: 'Cancel Rating', // advisory title for the 'cancel' link cancelValue: '', // value to submit when user click the 'cancel' link split: 0, // split the star into how many parts? // Width of star image in case the plugin can't work it out. This can happen if // the jQuery.dimensions plugin is not available OR the image is hidden at installation starWidth: 16//, //NB.: These don't need to be pre-defined (can be undefined/null) so let's save some code! //half: false, // just a shortcut to control.split = 2 //required: false, // disables the 'cancel' button so user can only select one of the specified values //readOnly: false, // disable rating plugin interaction/ values cannot be changed //focus: function(){}, // executed when stars are focused //blur: function(){}, // executed when stars are focused //callback: function(){}, // executed when a star is clicked }; //} }); /*--------------------------------------------------------*/ /* ### Default implementation ### The plugin will attach itself to file inputs with the class 'multi' when the page loads */ $(function(){ $('input[type=radio].star').rating(); }); /*# AVOID COLLISIONS #*/ })(jQuery);
JavaScript
/** * Ajax Queue Plugin * * Homepage: http://jquery.com/plugins/project/ajaxqueue * Documentation: http://docs.jquery.com/AjaxQueue */ /** <script> $(function(){ jQuery.ajaxQueue({ url: "test.php", success: function(html){ jQuery("ul").append(html); } }); jQuery.ajaxQueue({ url: "test.php", success: function(html){ jQuery("ul").append(html); } }); jQuery.ajaxSync({ url: "test.php", success: function(html){ jQuery("ul").append("<b>"+html+"</b>"); } }); jQuery.ajaxSync({ url: "test.php", success: function(html){ jQuery("ul").append("<b>"+html+"</b>"); } }); }); </script> <ul style="position: absolute; top: 5px; right: 5px;"></ul> */ /* * Queued Ajax requests. * A new Ajax request won't be started until the previous queued * request has finished. */ /* * Synced Ajax requests. * The Ajax request will happen as soon as you call this method, but * the callbacks (success/error/complete) won't fire until all previous * synced requests have been completed. */ (function($) { var ajax = $.ajax; var pendingRequests = {}; var synced = []; var syncedData = []; $.ajax = function(settings) { // create settings for compatibility with ajaxSetup settings = jQuery.extend(settings, jQuery.extend({}, jQuery.ajaxSettings, settings)); var port = settings.port; switch(settings.mode) { case "abort": if ( pendingRequests[port] ) { pendingRequests[port].abort(); } return pendingRequests[port] = ajax.apply(this, arguments); case "queue": var _old = settings.complete; settings.complete = function(){ if ( _old ) _old.apply( this, arguments ); jQuery([ajax]).dequeue("ajax" + port );; }; jQuery([ ajax ]).queue("ajax" + port, function(){ ajax( settings ); }); return; case "sync": var pos = synced.length; synced[ pos ] = { error: settings.error, success: settings.success, complete: settings.complete, done: false }; syncedData[ pos ] = { error: [], success: [], complete: [] }; settings.error = function(){ syncedData[ pos ].error = arguments; }; settings.success = function(){ syncedData[ pos ].success = arguments; }; settings.complete = function(){ syncedData[ pos ].complete = arguments; synced[ pos ].done = true; if ( pos == 0 || !synced[ pos-1 ] ) for ( var i = pos; i < synced.length && synced[i].done; i++ ) { if ( synced[i].error ) synced[i].error.apply( jQuery, syncedData[i].error ); if ( synced[i].success ) synced[i].success.apply( jQuery, syncedData[i].success ); if ( synced[i].complete ) synced[i].complete.apply( jQuery, syncedData[i].complete ); synced[i] = null; syncedData[i] = null; } }; } return ajax.apply(this, arguments); }; })(jQuery);
JavaScript
/* * jQuery Autocomplete plugin 1.1 * * Modified for Yii Framework: * - Renamed "autocomplete" to "legacyautocomplete". * - Fixed IE8 problems (mario.ffranco). * * Copyright (c) 2009 Jörn Zaefferer * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * Revision: $Id: jquery.autocomplete.js 15 2009-08-22 10:30:27Z joern.zaefferer $ */ ;(function($) { $.fn.extend({ legacyautocomplete: function(urlOrData, options) { var isUrl = typeof urlOrData == "string"; options = $.extend({}, $.Autocompleter.defaults, { url: isUrl ? urlOrData : null, data: isUrl ? null : urlOrData, delay: isUrl ? $.Autocompleter.defaults.delay : 10, max: options && !options.scroll ? 10 : 150 }, options); // if highlight is set to false, replace it with a do-nothing function options.highlight = options.highlight || function(value) { return value; }; // if the formatMatch option is not specified, then use formatItem for backwards compatibility options.formatMatch = options.formatMatch || options.formatItem; return this.each(function() { new $.Autocompleter(this, options); }); }, result: function(handler) { return this.bind("result", handler); }, search: function(handler) { return this.trigger("search", [handler]); }, flushCache: function() { return this.trigger("flushCache"); }, setOptions: function(options){ return this.trigger("setOptions", [options]); }, unautocomplete: function() { return this.trigger("unautocomplete"); } }); $.Autocompleter = function(input, options) { var KEY = { UP: 38, DOWN: 40, DEL: 46, TAB: 9, RETURN: 13, ESC: 27, COMMA: 188, PAGEUP: 33, PAGEDOWN: 34, BACKSPACE: 8 }; // Create $ object for input element var $input = $(input).attr("autocomplete", "off").addClass(options.inputClass); var timeout; var previousValue = ""; var cache = $.Autocompleter.Cache(options); var hasFocus = 0; var lastKeyPressCode; var config = { mouseDownOnSelect: false }; var select = $.Autocompleter.Select(options, input, selectCurrent, config); var blockSubmit; // prevent form submit in opera when selecting with return key $.browser.opera && $(input.form).bind("submit.autocomplete", function() { if (blockSubmit) { blockSubmit = false; return false; } }); // only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all $input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) { // a keypress means the input has focus // avoids issue where input had focus before the autocomplete was applied hasFocus = 1; // track last key pressed lastKeyPressCode = event.keyCode; switch(event.keyCode) { case KEY.UP: event.preventDefault(); if ( select.visible() ) { select.prev(); } else { onChange(0, true); } break; case KEY.DOWN: event.preventDefault(); if ( select.visible() ) { select.next(); } else { onChange(0, true); } break; case KEY.PAGEUP: event.preventDefault(); if ( select.visible() ) { select.pageUp(); } else { onChange(0, true); } break; case KEY.PAGEDOWN: event.preventDefault(); if ( select.visible() ) { select.pageDown(); } else { onChange(0, true); } break; // matches also semicolon case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA: case KEY.TAB: case KEY.RETURN: if( selectCurrent() ) { // stop default to prevent a form submit, Opera needs special handling event.preventDefault(); blockSubmit = true; return false; } break; case KEY.ESC: select.hide(); break; default: clearTimeout(timeout); timeout = setTimeout(onChange, options.delay); break; } }).focus(function(){ // track whether the field has focus, we shouldn't process any // results if the field no longer has focus hasFocus++; }).blur(function() { hasFocus = 0; if (!config.mouseDownOnSelect) { hideResults(); } }).click(function() { // show select when clicking in a focused field if ( hasFocus++ > 1 && !select.visible() ) { onChange(0, true); } }).bind("search", function() { // TODO why not just specifying both arguments? var fn = (arguments.length > 1) ? arguments[1] : null; function findValueCallback(q, data) { var result; if( data && data.length ) { for (var i=0; i < data.length; i++) { if( data[i].result.toLowerCase() == q.toLowerCase() ) { result = data[i]; break; } } } if( typeof fn == "function" ) fn(result); else $input.trigger("result", result && [result.data, result.value]); } $.each(trimWords($input.val()), function(i, value) { request(value, findValueCallback, findValueCallback); }); }).bind("flushCache", function() { cache.flush(); }).bind("setOptions", function() { $.extend(options, arguments[1]); // if we've updated the data, repopulate if ( "data" in arguments[1] ) cache.populate(); }).bind("unautocomplete", function() { select.unbind(); $input.unbind(); $(input.form).unbind(".autocomplete"); }); function selectCurrent() { var selected = select.selected(); if( !selected ) return false; var v = selected.result; previousValue = v; if ( options.multiple ) { var words = trimWords($input.val()); if ( words.length > 1 ) { var seperator = options.multipleSeparator.length; var cursorAt = $(input).selection().start; var wordAt, progress = 0; $.each(words, function(i, word) { progress += word.length; if (cursorAt <= progress) { wordAt = i; // Following return caused IE8 to set cursor to the start of the line. // return false; } progress += seperator; }); words[wordAt] = v; // TODO this should set the cursor to the right position, but it gets overriden somewhere //$.Autocompleter.Selection(input, progress + seperator, progress + seperator); v = words.join( options.multipleSeparator ); } v += options.multipleSeparator; } $input.val(v); hideResultsNow(); $input.trigger("result", [selected.data, selected.value]); return true; } function onChange(crap, skipPrevCheck) { if( lastKeyPressCode == KEY.DEL ) { select.hide(); return; } var currentValue = $input.val(); if ( !skipPrevCheck && currentValue == previousValue ) return; previousValue = currentValue; currentValue = lastWord(currentValue); if ( currentValue.length >= options.minChars) { $input.addClass(options.loadingClass); if (!options.matchCase) currentValue = currentValue.toLowerCase(); request(currentValue, receiveData, hideResultsNow); } else { stopLoading(); select.hide(); } }; function trimWords(value) { if (!value) return [""]; if (!options.multiple) return [$.trim(value)]; return $.map(value.split(options.multipleSeparator), function(word) { return $.trim(value).length ? $.trim(word) : null; }); } function lastWord(value) { if ( !options.multiple ) return value; var words = trimWords(value); if (words.length == 1) return words[0]; var cursorAt = $(input).selection().start; if (cursorAt == value.length) { words = trimWords(value) } else { words = trimWords(value.replace(value.substring(cursorAt), "")); } return words[words.length - 1]; } // fills in the input box w/the first match (assumed to be the best match) // q: the term entered // sValue: the first matching result function autoFill(q, sValue){ // autofill in the complete box w/the first match as long as the user hasn't entered in more data // if the last user key pressed was backspace, don't autofill if( options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE ) { // fill in the value (keep the case the user has typed) $input.val($input.val() + sValue.substring(lastWord(previousValue).length)); // select the portion of the value not typed by the user (so the next character will erase) $(input).selection(previousValue.length, previousValue.length + sValue.length); } }; function hideResults() { clearTimeout(timeout); timeout = setTimeout(hideResultsNow, 200); }; function hideResultsNow() { var wasVisible = select.visible(); select.hide(); clearTimeout(timeout); stopLoading(); if (options.mustMatch) { // call search and run callback $input.search( function (result){ // if no value found, clear the input box if( !result ) { if (options.multiple) { var words = trimWords($input.val()).slice(0, -1); $input.val( words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : "") ); } else { $input.val( "" ); $input.trigger("result", null); } } } ); } }; function receiveData(q, data) { if ( data && data.length && hasFocus ) { stopLoading(); select.display(data, q); autoFill(q, data[0].value); select.show(); } else { hideResultsNow(); } }; function request(term, success, failure) { if (!options.matchCase) term = term.toLowerCase(); var data = cache.load(term); // recieve the cached data if (data && data.length) { success(term, data); // if an AJAX url has been supplied, try loading the data now } else if( (typeof options.url == "string") && (options.url.length > 0) ){ var extraParams = { timestamp: +new Date() }; $.each(options.extraParams, function(key, param) { extraParams[key] = typeof param == "function" ? param() : param; }); $.ajax({ // try to leverage ajaxQueue plugin to abort previous requests mode: "abort", // limit abortion to this input port: "autocomplete" + input.name, dataType: options.dataType, url: options.url, data: $.extend({ q: lastWord(term), limit: options.max }, extraParams), success: function(data) { var parsed = options.parse && options.parse(data) || parse(data); cache.add(term, parsed); success(term, parsed); } }); } else { // if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match select.emptyList(); failure(term); } }; function parse(data) { var parsed = []; var rows = data.split("\n"); for (var i=0; i < rows.length; i++) { var row = $.trim(rows[i]); if (row) { row = row.split("|"); parsed[parsed.length] = { data: row, value: row[0], result: options.formatResult && options.formatResult(row, row[0]) || row[0] }; } } return parsed; }; function stopLoading() { $input.removeClass(options.loadingClass); }; }; $.Autocompleter.defaults = { inputClass: "ac_input", resultsClass: "ac_results", loadingClass: "ac_loading", minChars: 1, delay: 400, matchCase: false, matchSubset: true, matchContains: false, cacheLength: 10, max: 100, mustMatch: false, extraParams: {}, selectFirst: true, formatItem: function(row) { return row[0]; }, formatMatch: null, autoFill: false, width: 0, multiple: false, multipleSeparator: ", ", highlight: function(value, term) { return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>"); }, scroll: true, scrollHeight: 180 }; $.Autocompleter.Cache = function(options) { var data = {}; var length = 0; function matchSubset(s, sub) { if (!options.matchCase) s = s.toLowerCase(); var i = s.indexOf(sub); if (options.matchContains == "word"){ i = s.toLowerCase().search("\\b" + sub.toLowerCase()); } if (i == -1) return false; return i == 0 || options.matchContains; }; function add(q, value) { if (length > options.cacheLength){ flush(); } if (!data[q]){ length++; } data[q] = value; } function populate(){ if( !options.data ) return false; // track the matches var stMatchSets = {}, nullData = 0; // no url was specified, we need to adjust the cache length to make sure it fits the local data store if( !options.url ) options.cacheLength = 1; // track all options for minChars = 0 stMatchSets[""] = []; // loop through the array and create a lookup structure for ( var i = 0, ol = options.data.length; i < ol; i++ ) { var rawValue = options.data[i]; // if rawValue is a string, make an array otherwise just reference the array rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue; var value = options.formatMatch(rawValue, i+1, options.data.length); if ( value === false ) continue; var firstChar = value.charAt(0).toLowerCase(); // if no lookup array for this character exists, look it up now if( !stMatchSets[firstChar] ) stMatchSets[firstChar] = []; // if the match is a string var row = { value: value, data: rawValue, result: options.formatResult && options.formatResult(rawValue) || value }; // push the current match into the set list stMatchSets[firstChar].push(row); // keep track of minChars zero items if ( nullData++ < options.max ) { stMatchSets[""].push(row); } }; // add the data items to the cache $.each(stMatchSets, function(i, value) { // increase the cache size options.cacheLength++; // add to the cache add(i, value); }); } // populate any existing data setTimeout(populate, 25); function flush(){ data = {}; length = 0; } return { flush: flush, add: add, populate: populate, load: function(q) { if (!options.cacheLength || !length) return null; /* * if dealing w/local data and matchContains than we must make sure * to loop through all the data collections looking for matches */ if( !options.url && options.matchContains ){ // track all matches var csub = []; // loop through all the data grids for matches for( var k in data ){ // don't search through the stMatchSets[""] (minChars: 0) cache // this prevents duplicates if( k.length > 0 ){ var c = data[k]; $.each(c, function(i, x) { // if we've got a match, add it to the array if (matchSubset(x.value, q)) { csub.push(x); } }); } } return csub; } else // if the exact item exists, use it if (data[q]){ return data[q]; } else if (options.matchSubset) { for (var i = q.length - 1; i >= options.minChars; i--) { var c = data[q.substr(0, i)]; if (c) { var csub = []; $.each(c, function(i, x) { if (matchSubset(x.value, q)) { csub[csub.length] = x; } }); return csub; } } } return null; } }; }; $.Autocompleter.Select = function (options, input, select, config) { var CLASSES = { ACTIVE: "ac_over" }; var listItems, active = -1, data, term = "", needsInit = true, element, list; // Create results function init() { if (!needsInit) return; element = $("<div/>") .hide() .addClass(options.resultsClass) .css("position", "absolute") .appendTo(document.body); list = $("<ul/>").appendTo(element).mouseover( function(event) { if(target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') { active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event)); $(target(event)).addClass(CLASSES.ACTIVE); } }).click(function(event) { $(target(event)).addClass(CLASSES.ACTIVE); select(); // TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus input.focus(); return false; }).mousedown(function() { config.mouseDownOnSelect = true; }).mouseup(function() { config.mouseDownOnSelect = false; }); if( options.width > 0 ) element.css("width", options.width); needsInit = false; } function target(event) { var element = event.target; while(element && element.tagName != "LI") element = element.parentNode; // more fun with IE, sometimes event.target is empty, just ignore it then if(!element) return []; return element; } function moveSelect(step) { listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE); movePosition(step); var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE); if(options.scroll) { var offset = 0; listItems.slice(0, active).each(function() { offset += this.offsetHeight; }); if((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) { list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight()); } else if(offset < list.scrollTop()) { list.scrollTop(offset); } } }; function movePosition(step) { active += step; if (active < 0) { active = listItems.size() - 1; } else if (active >= listItems.size()) { active = 0; } } function limitNumberOfItems(available) { return options.max && options.max < available ? options.max : available; } function fillList() { list.empty(); var max = limitNumberOfItems(data.length); for (var i=0; i < max; i++) { if (!data[i]) continue; var formatted = options.formatItem(data[i].data, i+1, max, data[i].value, term); if ( formatted === false ) continue; var li = $("<li/>").html( options.highlight(formatted, term) ).addClass(i%2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0]; $.data(li, "ac_data", data[i]); } listItems = list.find("li"); if ( options.selectFirst ) { listItems.slice(0, 1).addClass(CLASSES.ACTIVE); active = 0; } // apply bgiframe if available if ( $.fn.bgiframe ) list.bgiframe(); } return { display: function(d, q) { init(); data = d; term = q; fillList(); }, next: function() { moveSelect(1); }, prev: function() { moveSelect(-1); }, pageUp: function() { if (active != 0 && active - 8 < 0) { moveSelect( -active ); } else { moveSelect(-8); } }, pageDown: function() { if (active != listItems.size() - 1 && active + 8 > listItems.size()) { moveSelect( listItems.size() - 1 - active ); } else { moveSelect(8); } }, hide: function() { element && element.hide(); listItems && listItems.removeClass(CLASSES.ACTIVE); active = -1; }, visible : function() { return element && element.is(":visible"); }, current: function() { return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]); }, show: function() { var offset = $(input).offset(); element.css({ width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(), top: offset.top + input.offsetHeight, left: offset.left }).show(); if(options.scroll) { list.scrollTop(0); list.css({ maxHeight: options.scrollHeight, overflow: 'auto' }); if($.browser.msie && typeof document.body.style.maxHeight === "undefined") { var listHeight = 0; listItems.each(function() { listHeight += this.offsetHeight; }); var scrollbarsVisible = listHeight > options.scrollHeight; list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight ); if (!scrollbarsVisible) { // IE doesn't recalculate width when scrollbar disappears listItems.width( list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")) ); } } } }, selected: function() { var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE); return selected && selected.length && $.data(selected[0], "ac_data"); }, emptyList: function (){ list && list.empty(); }, unbind: function() { element && element.remove(); } }; }; $.fn.selection = function(start, end) { if (start !== undefined) { return this.each(function() { if( this.createTextRange ){ var selRange = this.createTextRange(); if (end === undefined || start == end) { selRange.move("character", start); selRange.select(); } else { selRange.collapse(true); selRange.moveStart("character", start); selRange.moveEnd("character", end); selRange.select(); } } else if( this.setSelectionRange ){ this.setSelectionRange(start, end); } else if( this.selectionStart ){ this.selectionStart = start; this.selectionEnd = end; } }); } var field = this[0]; if ( field.createTextRange ) { var range = document.selection.createRange(), orig = field.value, teststring = "<->", textLength = range.text.length; range.text = teststring; var caretAt = field.value.indexOf(teststring); field.value = orig; this.selection(caretAt, caretAt + textLength); return { start: caretAt, end: caretAt + textLength } } else if( field.selectionStart !== undefined ){ return { start: field.selectionStart, end: field.selectionEnd } } }; })(jQuery);
JavaScript
/*! * jQuery BBQ: Back Button & Query Library - v1.2.1 - 2/17/2010 * http://benalman.com/projects/jquery-bbq-plugin/ * * Copyright (c) 2010 "Cowboy" Ben Alman * Dual licensed under the MIT and GPL licenses. * http://benalman.com/about/license/ */ // Script: jQuery BBQ: Back Button & Query Library // // *Version: 1.2.1, Last updated: 2/17/2010* // // Project Home - http://benalman.com/projects/jquery-bbq-plugin/ // GitHub - http://github.com/cowboy/jquery-bbq/ // Source - http://github.com/cowboy/jquery-bbq/raw/master/jquery.ba-bbq.js // (Minified) - http://github.com/cowboy/jquery-bbq/raw/master/jquery.ba-bbq.min.js (4.0kb) // // About: License // // Copyright (c) 2010 "Cowboy" Ben Alman, // Dual licensed under the MIT and GPL licenses. // http://benalman.com/about/license/ // // About: Examples // // These working examples, complete with fully commented code, illustrate a few // ways in which this plugin can be used. // // Basic AJAX - http://benalman.com/code/projects/jquery-bbq/examples/fragment-basic/ // Advanced AJAX - http://benalman.com/code/projects/jquery-bbq/examples/fragment-advanced/ // jQuery UI Tabs - http://benalman.com/code/projects/jquery-bbq/examples/fragment-jquery-ui-tabs/ // Deparam - http://benalman.com/code/projects/jquery-bbq/examples/deparam/ // // About: Support and Testing // // Information about what version or versions of jQuery this plugin has been // tested with, what browsers it has been tested in, and where the unit tests // reside (so you can test it yourself). // // jQuery Versions - 1.3.2, 1.4.1, 1.4.2 // Browsers Tested - Internet Explorer 6-8, Firefox 2-3.7, Safari 3-4, // Chrome 4-5, Opera 9.6-10.1. // Unit Tests - http://benalman.com/code/projects/jquery-bbq/unit/ // // About: Release History // // 1.2.1 - (2/17/2010) Actually fixed the stale window.location Safari bug from // <jQuery hashchange event> in BBQ, which was the main reason for the // previous release! // 1.2 - (2/16/2010) Integrated <jQuery hashchange event> v1.2, which fixes a // Safari bug, the event can now be bound before DOM ready, and IE6/7 // page should no longer scroll when the event is first bound. Also // added the <jQuery.param.fragment.noEscape> method, and reworked the // <hashchange event (BBQ)> internal "add" method to be compatible with // changes made to the jQuery 1.4.2 special events API. // 1.1.1 - (1/22/2010) Integrated <jQuery hashchange event> v1.1, which fixes an // obscure IE8 EmulateIE7 meta tag compatibility mode bug. // 1.1 - (1/9/2010) Broke out the jQuery BBQ event.special <hashchange event> // functionality into a separate plugin for users who want just the // basic event & back button support, without all the extra awesomeness // that BBQ provides. This plugin will be included as part of jQuery BBQ, // but also be available separately. See <jQuery hashchange event> // plugin for more information. Also added the <jQuery.bbq.removeState> // method and added additional <jQuery.deparam> examples. // 1.0.3 - (12/2/2009) Fixed an issue in IE 6 where location.search and // location.hash would report incorrectly if the hash contained the ? // character. Also <jQuery.param.querystring> and <jQuery.param.fragment> // will no longer parse params out of a URL that doesn't contain ? or #, // respectively. // 1.0.2 - (10/10/2009) Fixed an issue in IE 6/7 where the hidden IFRAME caused // a "This page contains both secure and nonsecure items." warning when // used on an https:// page. // 1.0.1 - (10/7/2009) Fixed an issue in IE 8. Since both "IE7" and "IE8 // Compatibility View" modes erroneously report that the browser // supports the native window.onhashchange event, a slightly more // robust test needed to be added. // 1.0 - (10/2/2009) Initial release (function($,window){ '$:nomunge'; // Used by YUI compressor. // Some convenient shortcuts. var undefined, aps = Array.prototype.slice, decode = decodeURIComponent, // Method / object references. jq_param = $.param, jq_param_fragment, jq_deparam, jq_deparam_fragment, jq_bbq = $.bbq = $.bbq || {}, jq_bbq_pushState, jq_bbq_getState, jq_elemUrlAttr, jq_event_special = $.event.special, // Reused strings. str_hashchange = 'hashchange', str_querystring = 'querystring', str_fragment = 'fragment', str_elemUrlAttr = 'elemUrlAttr', str_location = 'location', str_href = 'href', str_src = 'src', // Reused RegExp. re_trim_querystring = /^.*\?|#.*$/g, re_trim_fragment = /^.*\#/, re_no_escape, // Used by jQuery.elemUrlAttr. elemUrlAttr_cache = {}; // A few commonly used bits, broken out to help reduce minified file size. function is_string( arg ) { return typeof arg === 'string'; }; // Why write the same function twice? Let's curry! Mmmm, curry.. function curry( func ) { var args = aps.call( arguments, 1 ); return function() { return func.apply( this, args.concat( aps.call( arguments ) ) ); }; }; // Get location.hash (or what you'd expect location.hash to be) sans any // leading #. Thanks for making this necessary, Firefox! function get_fragment( url ) { return url.replace( /^[^#]*#?(.*)$/, '$1' ); }; // Get location.search (or what you'd expect location.search to be) sans any // leading #. Thanks for making this necessary, IE6! function get_querystring( url ) { return url.replace( /(?:^[^?#]*\?([^#]*).*$)?.*/, '$1' ); }; // Section: Param (to string) // // Method: jQuery.param.querystring // // Retrieve the query string from a URL or if no arguments are passed, the // current window.location. // // Usage: // // > jQuery.param.querystring( [ url ] ); // // Arguments: // // url - (String) A URL containing query string params to be parsed. If url // is not passed, the current window.location is used. // // Returns: // // (String) The parsed query string, with any leading "?" removed. // // Method: jQuery.param.querystring (build url) // // Merge a URL, with or without pre-existing query string params, plus any // object, params string or URL containing query string params into a new URL. // // Usage: // // > jQuery.param.querystring( url, params [, merge_mode ] ); // // Arguments: // // url - (String) A valid URL for params to be merged into. This URL may // contain a query string and/or fragment (hash). // params - (String) A params string or URL containing query string params to // be merged into url. // params - (Object) A params object to be merged into url. // merge_mode - (Number) Merge behavior defaults to 0 if merge_mode is not // specified, and is as-follows: // // * 0: params in the params argument will override any query string // params in url. // * 1: any query string params in url will override params in the params // argument. // * 2: params argument will completely replace any query string in url. // // Returns: // // (String) Either a params string with urlencoded data or a URL with a // urlencoded query string in the format 'a=b&c=d&e=f'. // Method: jQuery.param.fragment // // Retrieve the fragment (hash) from a URL or if no arguments are passed, the // current window.location. // // Usage: // // > jQuery.param.fragment( [ url ] ); // // Arguments: // // url - (String) A URL containing fragment (hash) params to be parsed. If // url is not passed, the current window.location is used. // // Returns: // // (String) The parsed fragment (hash) string, with any leading "#" removed. // Method: jQuery.param.fragment (build url) // // Merge a URL, with or without pre-existing fragment (hash) params, plus any // object, params string or URL containing fragment (hash) params into a new // URL. // // Usage: // // > jQuery.param.fragment( url, params [, merge_mode ] ); // // Arguments: // // url - (String) A valid URL for params to be merged into. This URL may // contain a query string and/or fragment (hash). // params - (String) A params string or URL containing fragment (hash) params // to be merged into url. // params - (Object) A params object to be merged into url. // merge_mode - (Number) Merge behavior defaults to 0 if merge_mode is not // specified, and is as-follows: // // * 0: params in the params argument will override any fragment (hash) // params in url. // * 1: any fragment (hash) params in url will override params in the // params argument. // * 2: params argument will completely replace any query string in url. // // Returns: // // (String) Either a params string with urlencoded data or a URL with a // urlencoded fragment (hash) in the format 'a=b&c=d&e=f'. function jq_param_sub( is_fragment, get_func, url, params, merge_mode ) { var result, qs, matches, url_params, hash; if ( params !== undefined ) { // Build URL by merging params into url string. // matches[1] = url part that precedes params, not including trailing ?/# // matches[2] = params, not including leading ?/# // matches[3] = if in 'querystring' mode, hash including leading #, otherwise '' matches = url.match( is_fragment ? /^([^#]*)\#?(.*)$/ : /^([^#?]*)\??([^#]*)(#?.*)/ ); // Get the hash if in 'querystring' mode, and it exists. hash = matches[3] || ''; if ( merge_mode === 2 && is_string( params ) ) { // If merge_mode is 2 and params is a string, merge the fragment / query // string into the URL wholesale, without converting it into an object. qs = params.replace( is_fragment ? re_trim_fragment : re_trim_querystring, '' ); } else { // Convert relevant params in url to object. url_params = jq_deparam( matches[2] ); params = is_string( params ) // Convert passed params string into object. ? jq_deparam[ is_fragment ? str_fragment : str_querystring ]( params ) // Passed params object. : params; qs = merge_mode === 2 ? params // passed params replace url params : merge_mode === 1 ? $.extend( {}, params, url_params ) // url params override passed params : $.extend( {}, url_params, params ); // passed params override url params // Convert params object to a string. qs = jq_param( qs ); // Unescape characters specified via $.param.noEscape. Since only hash- // history users have requested this feature, it's only enabled for // fragment-related params strings. if ( is_fragment ) { qs = qs.replace( re_no_escape, decode ); } } // Build URL from the base url, querystring and hash. In 'querystring' // mode, ? is only added if a query string exists. In 'fragment' mode, # // is always added. result = matches[1] + ( is_fragment ? '#' : qs || !matches[1] ? '?' : '' ) + qs + hash; } else { // If URL was passed in, parse params from URL string, otherwise parse // params from window.location. result = get_func( url !== undefined ? url : window[ str_location ][ str_href ] ); } return result; }; jq_param[ str_querystring ] = curry( jq_param_sub, 0, get_querystring ); jq_param[ str_fragment ] = jq_param_fragment = curry( jq_param_sub, 1, get_fragment ); // Method: jQuery.param.fragment.noEscape // // Specify characters that will be left unescaped when fragments are created // or merged using <jQuery.param.fragment>, or when the fragment is modified // using <jQuery.bbq.pushState>. This option only applies to serialized data // object fragments, and not set-as-string fragments. Does not affect the // query string. Defaults to ",/" (comma, forward slash). // // Note that this is considered a purely aesthetic option, and will help to // create URLs that "look pretty" in the address bar or bookmarks, without // affecting functionality in any way. That being said, be careful to not // unescape characters that are used as delimiters or serve a special // purpose, such as the "#?&=+" (octothorpe, question mark, ampersand, // equals, plus) characters. // // Usage: // // > jQuery.param.fragment.noEscape( [ chars ] ); // // Arguments: // // chars - (String) The characters to not escape in the fragment. If // unspecified, defaults to empty string (escape all characters). // // Returns: // // Nothing. jq_param_fragment.noEscape = function( chars ) { chars = chars || ''; var arr = $.map( chars.split(''), encodeURIComponent ); re_no_escape = new RegExp( arr.join('|'), 'g' ); }; // A sensible default. These are the characters people seem to complain about // "uglifying up the URL" the most. jq_param_fragment.noEscape( ',/' ); // Section: Deparam (from string) // // Method: jQuery.deparam // // Deserialize a params string into an object, optionally coercing numbers, // booleans, null and undefined values; this method is the counterpart to the // internal jQuery.param method. // // Usage: // // > jQuery.deparam( params [, coerce ] ); // // Arguments: // // params - (String) A params string to be parsed. // coerce - (Boolean) If true, coerces any numbers or true, false, null, and // undefined to their actual value. Defaults to false if omitted. // // Returns: // // (Object) An object representing the deserialized params string. $.deparam = jq_deparam = function( params, coerce ) { var obj = {}, coerce_types = { 'true': !0, 'false': !1, 'null': null }; // Iterate over all name=value pairs. $.each( params.replace( /\+/g, ' ' ).split( '&' ), function(j,v){ var param = v.split( '=' ), key = decode( param[0] ), val, cur = obj, i = 0, // If key is more complex than 'foo', like 'a[]' or 'a[b][c]', split it // into its component parts. keys = key.split( '][' ), keys_last = keys.length - 1; // If the first keys part contains [ and the last ends with ], then [] // are correctly balanced. if ( /\[/.test( keys[0] ) && /\]$/.test( keys[ keys_last ] ) ) { // Remove the trailing ] from the last keys part. keys[ keys_last ] = keys[ keys_last ].replace( /\]$/, '' ); // Split first keys part into two parts on the [ and add them back onto // the beginning of the keys array. keys = keys.shift().split('[').concat( keys ); keys_last = keys.length - 1; } else { // Basic 'foo' style key. keys_last = 0; } // Are we dealing with a name=value pair, or just a name? if ( param.length === 2 ) { val = decode( param[1] ); // Coerce values. if ( coerce ) { val = val && !isNaN(val) ? +val // number : val === 'undefined' ? undefined // undefined : coerce_types[val] !== undefined ? coerce_types[val] // true, false, null : val; // string } if ( keys_last ) { // Complex key, build deep object structure based on a few rules: // * The 'cur' pointer starts at the object top-level. // * [] = array push (n is set to array length), [n] = array if n is // numeric, otherwise object. // * If at the last keys part, set the value. // * For each keys part, if the current level is undefined create an // object or array based on the type of the next keys part. // * Move the 'cur' pointer to the next level. // * Rinse & repeat. for ( ; i <= keys_last; i++ ) { key = keys[i] === '' ? cur.length : keys[i]; cur = cur[key] = i < keys_last ? cur[key] || ( keys[i+1] && isNaN( keys[i+1] ) ? {} : [] ) : val; } } else { // Simple key, even simpler rules, since only scalars and shallow // arrays are allowed. if ( $.isArray( obj[key] ) ) { // val is already an array, so push on the next value. obj[key].push( val ); } else if ( obj[key] !== undefined ) { // val isn't an array, but since a second value has been specified, // convert val into an array. obj[key] = [ obj[key], val ]; } else { // val is a scalar. obj[key] = val; } } } else if ( key ) { // No value was defined, so set something meaningful. obj[key] = coerce ? undefined : ''; } }); return obj; }; // Method: jQuery.deparam.querystring // // Parse the query string from a URL or the current window.location, // deserializing it into an object, optionally coercing numbers, booleans, // null and undefined values. // // Usage: // // > jQuery.deparam.querystring( [ url ] [, coerce ] ); // // Arguments: // // url - (String) An optional params string or URL containing query string // params to be parsed. If url is omitted, the current window.location // is used. // coerce - (Boolean) If true, coerces any numbers or true, false, null, and // undefined to their actual value. Defaults to false if omitted. // // Returns: // // (Object) An object representing the deserialized params string. // Method: jQuery.deparam.fragment // // Parse the fragment (hash) from a URL or the current window.location, // deserializing it into an object, optionally coercing numbers, booleans, // null and undefined values. // // Usage: // // > jQuery.deparam.fragment( [ url ] [, coerce ] ); // // Arguments: // // url - (String) An optional params string or URL containing fragment (hash) // params to be parsed. If url is omitted, the current window.location // is used. // coerce - (Boolean) If true, coerces any numbers or true, false, null, and // undefined to their actual value. Defaults to false if omitted. // // Returns: // // (Object) An object representing the deserialized params string. function jq_deparam_sub( is_fragment, url_or_params, coerce ) { if ( url_or_params === undefined || typeof url_or_params === 'boolean' ) { // url_or_params not specified. coerce = url_or_params; url_or_params = jq_param[ is_fragment ? str_fragment : str_querystring ](); } else { url_or_params = is_string( url_or_params ) ? url_or_params.replace( is_fragment ? re_trim_fragment : re_trim_querystring, '' ) : url_or_params; } return jq_deparam( url_or_params, coerce ); }; jq_deparam[ str_querystring ] = curry( jq_deparam_sub, 0 ); jq_deparam[ str_fragment ] = jq_deparam_fragment = curry( jq_deparam_sub, 1 ); // Section: Element manipulation // // Method: jQuery.elemUrlAttr // // Get the internal "Default URL attribute per tag" list, or augment the list // with additional tag-attribute pairs, in case the defaults are insufficient. // // In the <jQuery.fn.querystring> and <jQuery.fn.fragment> methods, this list // is used to determine which attribute contains the URL to be modified, if // an "attr" param is not specified. // // Default Tag-Attribute List: // // a - href // base - href // iframe - src // img - src // input - src // form - action // link - href // script - src // // Usage: // // > jQuery.elemUrlAttr( [ tag_attr ] ); // // Arguments: // // tag_attr - (Object) An object containing a list of tag names and their // associated default attribute names in the format { tag: 'attr', ... } to // be merged into the internal tag-attribute list. // // Returns: // // (Object) An object containing all stored tag-attribute values. // Only define function and set defaults if function doesn't already exist, as // the urlInternal plugin will provide this method as well. $[ str_elemUrlAttr ] || ($[ str_elemUrlAttr ] = function( obj ) { return $.extend( elemUrlAttr_cache, obj ); })({ a: str_href, base: str_href, iframe: str_src, img: str_src, input: str_src, form: 'action', link: str_href, script: str_src }); jq_elemUrlAttr = $[ str_elemUrlAttr ]; // Method: jQuery.fn.querystring // // Update URL attribute in one or more elements, merging the current URL (with // or without pre-existing query string params) plus any params object or // string into a new URL, which is then set into that attribute. Like // <jQuery.param.querystring (build url)>, but for all elements in a jQuery // collection. // // Usage: // // > jQuery('selector').querystring( [ attr, ] params [, merge_mode ] ); // // Arguments: // // attr - (String) Optional name of an attribute that will contain a URL to // merge params or url into. See <jQuery.elemUrlAttr> for a list of default // attributes. // params - (Object) A params object to be merged into the URL attribute. // params - (String) A URL containing query string params, or params string // to be merged into the URL attribute. // merge_mode - (Number) Merge behavior defaults to 0 if merge_mode is not // specified, and is as-follows: // // * 0: params in the params argument will override any params in attr URL. // * 1: any params in attr URL will override params in the params argument. // * 2: params argument will completely replace any query string in attr // URL. // // Returns: // // (jQuery) The initial jQuery collection of elements, but with modified URL // attribute values. // Method: jQuery.fn.fragment // // Update URL attribute in one or more elements, merging the current URL (with // or without pre-existing fragment/hash params) plus any params object or // string into a new URL, which is then set into that attribute. Like // <jQuery.param.fragment (build url)>, but for all elements in a jQuery // collection. // // Usage: // // > jQuery('selector').fragment( [ attr, ] params [, merge_mode ] ); // // Arguments: // // attr - (String) Optional name of an attribute that will contain a URL to // merge params into. See <jQuery.elemUrlAttr> for a list of default // attributes. // params - (Object) A params object to be merged into the URL attribute. // params - (String) A URL containing fragment (hash) params, or params // string to be merged into the URL attribute. // merge_mode - (Number) Merge behavior defaults to 0 if merge_mode is not // specified, and is as-follows: // // * 0: params in the params argument will override any params in attr URL. // * 1: any params in attr URL will override params in the params argument. // * 2: params argument will completely replace any fragment (hash) in attr // URL. // // Returns: // // (jQuery) The initial jQuery collection of elements, but with modified URL // attribute values. function jq_fn_sub( mode, force_attr, params, merge_mode ) { if ( !is_string( params ) && typeof params !== 'object' ) { // force_attr not specified. merge_mode = params; params = force_attr; force_attr = undefined; } return this.each(function(){ var that = $(this), // Get attribute specified, or default specified via $.elemUrlAttr. attr = force_attr || jq_elemUrlAttr()[ ( this.nodeName || '' ).toLowerCase() ] || '', // Get URL value. url = attr && that.attr( attr ) || ''; // Update attribute with new URL. that.attr( attr, jq_param[ mode ]( url, params, merge_mode ) ); }); }; $.fn[ str_querystring ] = curry( jq_fn_sub, str_querystring ); $.fn[ str_fragment ] = curry( jq_fn_sub, str_fragment ); // Section: History, hashchange event // // Method: jQuery.bbq.pushState // // Adds a 'state' into the browser history at the current position, setting // location.hash and triggering any bound <hashchange event> callbacks // (provided the new state is different than the previous state). // // If no arguments are passed, an empty state is created, which is just a // shortcut for jQuery.bbq.pushState( {}, 2 ). // // Usage: // // > jQuery.bbq.pushState( [ params [, merge_mode ] ] ); // // Arguments: // // params - (String) A serialized params string or a hash string beginning // with # to merge into location.hash. // params - (Object) A params object to merge into location.hash. // merge_mode - (Number) Merge behavior defaults to 0 if merge_mode is not // specified (unless a hash string beginning with # is specified, in which // case merge behavior defaults to 2), and is as-follows: // // * 0: params in the params argument will override any params in the // current state. // * 1: any params in the current state will override params in the params // argument. // * 2: params argument will completely replace current state. // // Returns: // // Nothing. // // Additional Notes: // // * Setting an empty state may cause the browser to scroll. // * Unlike the fragment and querystring methods, if a hash string beginning // with # is specified as the params agrument, merge_mode defaults to 2. jq_bbq.pushState = jq_bbq_pushState = function( params, merge_mode ) { if ( is_string( params ) && /^#/.test( params ) && merge_mode === undefined ) { // Params string begins with # and merge_mode not specified, so completely // overwrite window.location.hash. merge_mode = 2; } var has_args = params !== undefined, // Merge params into window.location using $.param.fragment. url = jq_param_fragment( window[ str_location ][ str_href ], has_args ? params : {}, has_args ? merge_mode : 2 ); // Set new window.location.href. If hash is empty, use just # to prevent // browser from reloading the page. Note that Safari 3 & Chrome barf on // location.hash = '#'. window[ str_location ][ str_href ] = url + ( /#/.test( url ) ? '' : '#' ); }; // Method: jQuery.bbq.getState // // Retrieves the current 'state' from the browser history, parsing // location.hash for a specific key or returning an object containing the // entire state, optionally coercing numbers, booleans, null and undefined // values. // // Usage: // // > jQuery.bbq.getState( [ key ] [, coerce ] ); // // Arguments: // // key - (String) An optional state key for which to return a value. // coerce - (Boolean) If true, coerces any numbers or true, false, null, and // undefined to their actual value. Defaults to false. // // Returns: // // (Anything) If key is passed, returns the value corresponding with that key // in the location.hash 'state', or undefined. If not, an object // representing the entire 'state' is returned. jq_bbq.getState = jq_bbq_getState = function( key, coerce ) { return key === undefined || typeof key === 'boolean' ? jq_deparam_fragment( key ) // 'key' really means 'coerce' here : jq_deparam_fragment( coerce )[ key ]; }; // Method: jQuery.bbq.removeState // // Remove one or more keys from the current browser history 'state', creating // a new state, setting location.hash and triggering any bound // <hashchange event> callbacks (provided the new state is different than // the previous state). // // If no arguments are passed, an empty state is created, which is just a // shortcut for jQuery.bbq.pushState( {}, 2 ). // // Usage: // // > jQuery.bbq.removeState( [ key [, key ... ] ] ); // // Arguments: // // key - (String) One or more key values to remove from the current state, // passed as individual arguments. // key - (Array) A single array argument that contains a list of key values // to remove from the current state. // // Returns: // // Nothing. // // Additional Notes: // // * Setting an empty state may cause the browser to scroll. jq_bbq.removeState = function( arr ) { var state = {}; // If one or more arguments is passed.. if ( arr !== undefined ) { // Get the current state. state = jq_bbq_getState(); // For each passed key, delete the corresponding property from the current // state. $.each( $.isArray( arr ) ? arr : arguments, function(i,v){ delete state[ v ]; }); } // Set the state, completely overriding any existing state. jq_bbq_pushState( state, 2 ); }; // Event: hashchange event (BBQ) // // Usage in jQuery 1.4 and newer: // // In jQuery 1.4 and newer, the event object passed into any hashchange event // callback is augmented with a copy of the location.hash fragment at the time // the event was triggered as its event.fragment property. In addition, the // event.getState method operates on this property (instead of location.hash) // which allows this fragment-as-a-state to be referenced later, even after // window.location may have changed. // // Note that event.fragment and event.getState are not defined according to // W3C (or any other) specification, but will still be available whether or // not the hashchange event exists natively in the browser, because of the // utility they provide. // // The event.fragment property contains the output of <jQuery.param.fragment> // and the event.getState method is equivalent to the <jQuery.bbq.getState> // method. // // > $(window).bind( 'hashchange', function( event ) { // > var hash_str = event.fragment, // > param_obj = event.getState(), // > param_val = event.getState( 'param_name' ), // > param_val_coerced = event.getState( 'param_name', true ); // > ... // > }); // // Usage in jQuery 1.3.2: // // In jQuery 1.3.2, the event object cannot to be augmented as in jQuery 1.4+, // so the fragment state isn't bound to the event object and must instead be // parsed using the <jQuery.param.fragment> and <jQuery.bbq.getState> methods. // // > $(window).bind( 'hashchange', function( event ) { // > var hash_str = $.param.fragment(), // > param_obj = $.bbq.getState(), // > param_val = $.bbq.getState( 'param_name' ), // > param_val_coerced = $.bbq.getState( 'param_name', true ); // > ... // > }); // // Additional Notes: // // * Due to changes in the special events API, jQuery BBQ v1.2 or newer is // required to enable the augmented event object in jQuery 1.4.2 and newer. // * See <jQuery hashchange event> for more detailed information. jq_event_special[ str_hashchange ] = $.extend( jq_event_special[ str_hashchange ], { // Augmenting the event object with the .fragment property and .getState // method requires jQuery 1.4 or newer. Note: with 1.3.2, everything will // work, but the event won't be augmented) add: function( handleObj ) { var old_handler; function new_handler(e) { // e.fragment is set to the value of location.hash (with any leading # // removed) at the time the event is triggered. var hash = e[ str_fragment ] = jq_param_fragment(); // e.getState() works just like $.bbq.getState(), but uses the // e.fragment property stored on the event object. e.getState = function( key, coerce ) { return key === undefined || typeof key === 'boolean' ? jq_deparam( hash, key ) // 'key' really means 'coerce' here : jq_deparam( hash, coerce )[ key ]; }; old_handler.apply( this, arguments ); }; // This may seem a little complicated, but it normalizes the special event // .add method between jQuery 1.4/1.4.1 and 1.4.2+ if ( $.isFunction( handleObj ) ) { // 1.4, 1.4.1 old_handler = handleObj; return new_handler; } else { // 1.4.2+ old_handler = handleObj.handler; handleObj.handler = new_handler; } } }); })(jQuery,this); /*! * jQuery hashchange event - v1.2 - 2/11/2010 * http://benalman.com/projects/jquery-hashchange-plugin/ * * Copyright (c) 2010 "Cowboy" Ben Alman * Dual licensed under the MIT and GPL licenses. * http://benalman.com/about/license/ */ // Script: jQuery hashchange event // // *Version: 1.2, Last updated: 2/11/2010* // // Project Home - http://benalman.com/projects/jquery-hashchange-plugin/ // GitHub - http://github.com/cowboy/jquery-hashchange/ // Source - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.js // (Minified) - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.min.js (1.1kb) // // About: License // // Copyright (c) 2010 "Cowboy" Ben Alman, // Dual licensed under the MIT and GPL licenses. // http://benalman.com/about/license/ // // About: Examples // // This working example, complete with fully commented code, illustrate one way // in which this plugin can be used. // // hashchange event - http://benalman.com/code/projects/jquery-hashchange/examples/hashchange/ // // About: Support and Testing // // Information about what version or versions of jQuery this plugin has been // tested with, what browsers it has been tested in, and where the unit tests // reside (so you can test it yourself). // // jQuery Versions - 1.3.2, 1.4.1, 1.4.2 // Browsers Tested - Internet Explorer 6-8, Firefox 2-3.7, Safari 3-4, Chrome, Opera 9.6-10.1. // Unit Tests - http://benalman.com/code/projects/jquery-hashchange/unit/ // // About: Known issues // // While this jQuery hashchange event implementation is quite stable and robust, // there are a few unfortunate browser bugs surrounding expected hashchange // event-based behaviors, independent of any JavaScript window.onhashchange // abstraction. See the following examples for more information: // // Chrome: Back Button - http://benalman.com/code/projects/jquery-hashchange/examples/bug-chrome-back-button/ // Firefox: Remote XMLHttpRequest - http://benalman.com/code/projects/jquery-hashchange/examples/bug-firefox-remote-xhr/ // WebKit: Back Button in an Iframe - http://benalman.com/code/projects/jquery-hashchange/examples/bug-webkit-hash-iframe/ // Safari: Back Button from a different domain - http://benalman.com/code/projects/jquery-hashchange/examples/bug-safari-back-from-diff-domain/ // // About: Release History // // 1.2 - (2/11/2010) Fixed a bug where coming back to a page using this plugin // from a page on another domain would cause an error in Safari 4. Also, // IE6/7 Iframe is now inserted after the body (this actually works), // which prevents the page from scrolling when the event is first bound. // Event can also now be bound before DOM ready, but it won't be usable // before then in IE6/7. // 1.1 - (1/21/2010) Incorporated document.documentMode test to fix IE8 bug // where browser version is incorrectly reported as 8.0, despite // inclusion of the X-UA-Compatible IE=EmulateIE7 meta tag. // 1.0 - (1/9/2010) Initial Release. Broke out the jQuery BBQ event.special // window.onhashchange functionality into a separate plugin for users // who want just the basic event & back button support, without all the // extra awesomeness that BBQ provides. This plugin will be included as // part of jQuery BBQ, but also be available separately. (function($,window,undefined){ '$:nomunge'; // Used by YUI compressor. // Method / object references. var fake_onhashchange, jq_event_special = $.event.special, // Reused strings. str_location = 'location', str_hashchange = 'hashchange', str_href = 'href', // IE6/7 specifically need some special love when it comes to back-button // support, so let's do a little browser sniffing.. browser = $.browser, mode = document.documentMode, is_old_ie = browser.msie && ( mode === undefined || mode < 8 ), // Does the browser support window.onhashchange? Test for IE version, since // IE8 incorrectly reports this when in "IE7" or "IE8 Compatibility View"! supports_onhashchange = 'on' + str_hashchange in window && !is_old_ie; // Get location.hash (or what you'd expect location.hash to be) sans any // leading #. Thanks for making this necessary, Firefox! function get_fragment( url ) { url = url || window[ str_location ][ str_href ]; return url.replace( /^[^#]*#?(.*)$/, '$1' ); }; // Property: jQuery.hashchangeDelay // // The numeric interval (in milliseconds) at which the <hashchange event> // polling loop executes. Defaults to 100. $[ str_hashchange + 'Delay' ] = 100; // Event: hashchange event // // Fired when location.hash changes. In browsers that support it, the native // window.onhashchange event is used (IE8, FF3.6), otherwise a polling loop is // initialized, running every <jQuery.hashchangeDelay> milliseconds to see if // the hash has changed. In IE 6 and 7, a hidden Iframe is created to allow // the back button and hash-based history to work. // // Usage: // // > $(window).bind( 'hashchange', function(e) { // > var hash = location.hash; // > ... // > }); // // Additional Notes: // // * The polling loop and Iframe are not created until at least one callback // is actually bound to 'hashchange'. // * If you need the bound callback(s) to execute immediately, in cases where // the page 'state' exists on page load (via bookmark or page refresh, for // example) use $(window).trigger( 'hashchange' ); // * The event can be bound before DOM ready, but since it won't be usable // before then in IE6/7 (due to the necessary Iframe), recommended usage is // to bind it inside a $(document).ready() callback. jq_event_special[ str_hashchange ] = $.extend( jq_event_special[ str_hashchange ], { // Called only when the first 'hashchange' event is bound to window. setup: function() { // If window.onhashchange is supported natively, there's nothing to do.. if ( supports_onhashchange ) { return false; } // Otherwise, we need to create our own. And we don't want to call this // until the user binds to the event, just in case they never do, since it // will create a polling loop and possibly even a hidden Iframe. $( fake_onhashchange.start ); }, // Called only when the last 'hashchange' event is unbound from window. teardown: function() { // If window.onhashchange is supported natively, there's nothing to do.. if ( supports_onhashchange ) { return false; } // Otherwise, we need to stop ours (if possible). $( fake_onhashchange.stop ); } }); // fake_onhashchange does all the work of triggering the window.onhashchange // event for browsers that don't natively support it, including creating a // polling loop to watch for hash changes and in IE 6/7 creating a hidden // Iframe to enable back and forward. fake_onhashchange = (function(){ var self = {}, timeout_id, iframe, set_history, get_history; // Initialize. In IE 6/7, creates a hidden Iframe for history handling. function init(){ // Most browsers don't need special methods here.. set_history = get_history = function(val){ return val; }; // But IE6/7 do! if ( is_old_ie ) { // Create hidden Iframe after the end of the body to prevent initial // page load from scrolling unnecessarily. iframe = $('<iframe src="javascript:0"/>').hide().insertAfter( 'body' )[0].contentWindow; // Get history by looking at the hidden Iframe's location.hash. get_history = function() { return get_fragment( iframe.document[ str_location ][ str_href ] ); }; // Set a new history item by opening and then closing the Iframe // document, *then* setting its location.hash. set_history = function( hash, history_hash ) { if ( hash !== history_hash ) { var doc = iframe.document; doc.open().close(); doc[ str_location ].hash = '#' + hash; } }; // Set initial history. set_history( get_fragment() ); } }; // Start the polling loop. self.start = function() { // Polling loop is already running! if ( timeout_id ) { return; } // Remember the initial hash so it doesn't get triggered immediately. var last_hash = get_fragment(); // Initialize if not yet initialized. set_history || init(); // This polling loop checks every $.hashchangeDelay milliseconds to see if // location.hash has changed, and triggers the 'hashchange' event on // window when necessary. (function loopy(){ var hash = get_fragment(), history_hash = get_history( last_hash ); if ( hash !== last_hash ) { set_history( last_hash = hash, history_hash ); $(window).trigger( str_hashchange ); } else if ( history_hash !== last_hash ) { window[ str_location ][ str_href ] = window[ str_location ][ str_href ].replace( /#.*/, '' ) + '#' + history_hash; } timeout_id = setTimeout( loopy, $[ str_hashchange + 'Delay' ] ); })(); }; // Stop the polling loop, but only if an IE6/7 Iframe wasn't created. In // that case, even if there are no longer any bound event handlers, the // polling loop is still necessary for back/next to work at all! self.stop = function() { if ( !iframe ) { timeout_id && clearTimeout( timeout_id ); timeout_id = 0; } }; return self; })(); })(jQuery,this);
JavaScript
/* * Metadata - jQuery plugin for parsing metadata from elements * * Copyright (c) 2006 John Resig, Yehuda Katz, J�örn Zaefferer, Paul McLanahan * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * Revision: $Id: jquery.metadata.js 3640 2007-10-11 18:34:38Z pmclanahan $ * */ /** * Sets the type of metadata to use. Metadata is encoded in JSON, and each property * in the JSON will become a property of the element itself. * * There are four supported types of metadata storage: * * attr: Inside an attribute. The name parameter indicates *which* attribute. * * class: Inside the class attribute, wrapped in curly braces: { } * * elem: Inside a child element (e.g. a script tag). The * name parameter indicates *which* element. * html5: Values are stored in data-* attributes. * * The metadata for an element is loaded the first time the element is accessed via jQuery. * * As a result, you can define the metadata type, use $(expr) to load the metadata into the elements * matched by expr, then redefine the metadata type and run another $(expr) for other elements. * * @name $.metadata.setType * * @example <p id="one" class="some_class {item_id: 1, item_label: 'Label'}">This is a p</p> * @before $.metadata.setType("class") * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label" * @desc Reads metadata from the class attribute * * @example <p id="one" class="some_class" data="{item_id: 1, item_label: 'Label'}">This is a p</p> * @before $.metadata.setType("attr", "data") * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label" * @desc Reads metadata from a "data" attribute * * @example <p id="one" class="some_class"><script>{item_id: 1, item_label: 'Label'}</script>This is a p</p> * @before $.metadata.setType("elem", "script") * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label" * @desc Reads metadata from a nested script element * * @example <p id="one" class="some_class" data-item_id="1" data-item_label="Label">This is a p</p> * @before $.metadata.setType("html5") * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label" * @desc Reads metadata from a series of data-* attributes * * @param String type The encoding type * @param String name The name of the attribute to be used to get metadata (optional) * @cat Plugins/Metadata * @descr Sets the type of encoding to be used when loading metadata for the first time * @type undefined * @see metadata() */ (function($) { $.extend({ metadata : { defaults : { type: 'class', name: 'metadata', cre: /({.*})/, single: 'metadata' }, setType: function( type, name ){ this.defaults.type = type; this.defaults.name = name; }, get: function( elem, opts ){ var settings = $.extend({},this.defaults,opts); // check for empty string in single property if ( !settings.single.length ) settings.single = 'metadata'; var data = $.data(elem, settings.single); // returned cached data if it already exists if ( data ) return data; data = "{}"; var getData = function(data) { if(typeof data != "string") return data; if( data.indexOf('{') < 0 ) { data = eval("(" + data + ")"); } }; var getObject = function(data) { if(typeof data != "string") return data; data = eval("(" + data + ")"); return data; }; if ( settings.type == "html5" ) { var object = {}; $( elem.attributes ).each(function() { var name = this.nodeName; if(name.match(/^data-/)) name = name.replace(/^data-/, ''); else return true; object[name] = getObject(this.nodeValue); }); } else { if ( settings.type == "class" ) { var m = settings.cre.exec( elem.className ); if ( m ) data = m[1]; } else if ( settings.type == "elem" ) { if( !elem.getElementsByTagName ) return; var e = elem.getElementsByTagName(settings.name); if ( e.length ) data = $.trim(e[0].innerHTML); } else if ( elem.getAttribute != undefined ) { var attr = elem.getAttribute( settings.name ); if ( attr ) data = attr; } object = getObject(data.indexOf("{") < 0 ? "{" + data + "}" : data); } $.data( elem, settings.single, object ); return object; } } }); /** * Returns the metadata object for the first member of the jQuery object. * * @name metadata * @descr Returns element's metadata object * @param Object opts An object contianing settings to override the defaults * @type jQuery * @cat Plugins/Metadata */ $.fn.metadata = function( opts ){ return $.metadata.get( this[0], opts ); }; })(jQuery);
JavaScript
/** * jQuery yiiactiveform plugin file. * * @author Qiang Xue <qiang.xue@gmail.com> * @link http://www.yiiframework.com/ * @copyright Copyright &copy; 2008-2010 Yii Software LLC * @license http://www.yiiframework.com/license/ * @version $Id: jquery.yiiactiveform.js 3158 2011-04-02 22:48:01Z qiang.xue $ * @since 1.1.1 */ ;(function($) { /** * yiiactiveform set function. * @param options map settings for the active form plugin. Please see {@link CActiveForm::options} for availablel options. */ $.fn.yiiactiveform = function(options) { return this.each(function() { var settings = $.extend({}, $.fn.yiiactiveform.defaults, options || {}); var $form = $(this); var id = $form.attr('id'); if(settings.validationUrl == undefined) settings.validationUrl = $form.attr('action'); $.each(settings.attributes, function(i,attribute){ settings.attributes[i] = $.extend({ validationDelay : settings.validationDelay, validateOnChange : settings.validateOnChange, validateOnType : settings.validateOnType, hideErrorMessage : settings.hideErrorMessage, inputContainer : settings.inputContainer, errorCssClass : settings.errorCssClass, successCssClass : settings.successCssClass, beforeValidateAttribute : settings.beforeValidateAttribute, afterValidateAttribute : settings.afterValidateAttribute, validatingCssClass : settings.validatingCssClass }, attribute); settings.attributes[i].value = $('#'+attribute.inputID, $form).val(); }); $(this).data('settings', settings); settings.submitting=false; // whether it is waiting for ajax submission result var validate = function(attribute, forceValidate) { if (forceValidate) attribute.status = 2; $.each(settings.attributes, function(){ if (this.value != $('#'+this.inputID, $form).val()) { this.status = 2; forceValidate = true; } }); if (!forceValidate) return; if(settings.timer!=undefined) { clearTimeout(settings.timer); } settings.timer = setTimeout(function(){ if(settings.submitting) return; if(attribute.beforeValidateAttribute==undefined || attribute.beforeValidateAttribute($form, attribute)) { $.each(settings.attributes, function(){ if (this.status == 2) { this.status = 3; $.fn.yiiactiveform.getInputContainer(this, $form).addClass(this.validatingCssClass); } }); $.fn.yiiactiveform.validate($form, function(data) { var hasError=false; $.each(settings.attributes, function(){ if (this.status == 2 || this.status == 3) { hasError = $.fn.yiiactiveform.updateInput(this, data, $form) || hasError; } }); if(attribute.afterValidateAttribute!=undefined) { attribute.afterValidateAttribute($form,attribute,data,hasError); } }); } }, attribute.validationDelay); }; $.each(settings.attributes, function(i, attribute) { if (attribute.validateOnChange) { $('#'+attribute.inputID, $form).change(function(){ var inputType = $('#'+attribute.inputID).attr('type'); validate(attribute, inputType=='checkbox' || inputType=='radio'); }).blur(function(){ if(attribute.status!=2 && attribute.status!=3) validate(attribute, !attribute.status); }); } if (attribute.validateOnType) { $('#'+attribute.inputID, $form).keyup(function(){ if (attribute.value != $('#'+attribute.inputID, $form).val()) validate(attribute, false); }); } }); if (settings.validateOnSubmit) { $form.find(':submit').live('mouseup keyup',function(){ $form.data('submitObject',$(this)); }); var validated = false; $form.submit(function(){ if (validated) return true; if(settings.timer!=undefined) { clearTimeout(settings.timer); } settings.submitting=true; if(settings.beforeValidate==undefined || settings.beforeValidate($form)) { $.fn.yiiactiveform.validate($form, function(data){ var hasError = false; $.each(settings.attributes, function(i, attribute){ hasError = $.fn.yiiactiveform.updateInput(attribute, data, $form) || hasError; }); $.fn.yiiactiveform.updateSummary($form, data); if(settings.afterValidate==undefined || settings.afterValidate($form, data, hasError)) { if(!hasError) { validated = true; var $button = $form.data('submitObject') || $form.find(':submit:first'); // TODO: if the submission is caused by "change" event, it will not work if ($button.length) $button.click(); else // no submit button in the form $form.submit(); return false; } } settings.submitting=false; }); } else { settings.submitting=false; } return false; }); } /* * In case of reseting the form we need to reset error messages * NOTE1: $form.reset - does not exist * NOTE2: $form.live('reset',...) does not work */ $form.bind('reset',function(){ /* * because we bind directly to a form reset event, not to a reset button (that could or could not exist), * when this function is executed form elements values have not been reset yet, * because of that we use the setTimeout */ setTimeout(function(){ $.each(settings.attributes, function(i, attribute){ attribute.status = 0; var $error = $('#'+attribute.errorID, $form); var $container = $.fn.yiiactiveform.getInputContainer(attribute, $form); $container .removeClass(attribute.validatingCssClass) .removeClass(attribute.errorCssClass) .removeClass(attribute.successCssClass); $error.html('').hide(); /* * without the setTimeout() call val() would return the entered value instead of the reseted value */ attribute.value = $('#'+attribute.inputID, $form).val(); /* * If the form is submited (non ajax) with errors, labels and input gets the class 'error' */ $('label,input',$form).each(function(){ $(this).removeClass('error'); }); }); $('#'+settings.summaryID+' ul').html(''); $('#'+settings.summaryID).hide(); //.. set to initial focus on reset if(settings.focus != undefined && !window.location.hash) $(settings.focus).focus(); },1); }); /* * set to initial focus */ if(settings.focus != undefined && !window.location.hash) $(settings.focus).focus(); }); }; /** * Returns the container element of the specified attribute. * @param attribute object the configuration for a particular attribute. * @param form the form jQuery object * @return jquery the jquery representation of the container */ $.fn.yiiactiveform.getInputContainer = function(attribute, form) { if(attribute.inputContainer == undefined) return $('#'+attribute.inputID, form).closest('div'); else return $(attribute.inputContainer).filter(':has("#'+attribute.inputID+'")'); }; /** * updates the error message and the input container for a particular attribute. * @param attribute object the configuration for a particular attribute. * @param messages array the json data obtained from the ajax validation request * @param form the form jQuery object * @return boolean whether there is a validation error for the specified attribute */ $.fn.yiiactiveform.updateInput = function(attribute, messages, form) { attribute.status = 1; var hasError = messages!=null && $.isArray(messages[attribute.id]) && messages[attribute.id].length>0; var $error = $('#'+attribute.errorID, form); var $container = $.fn.yiiactiveform.getInputContainer(attribute, form); $container.removeClass(attribute.validatingCssClass) .removeClass(attribute.errorCssClass) .removeClass(attribute.successCssClass); if(hasError) { $error.html(messages[attribute.id][0]); $container.addClass(attribute.errorCssClass); } else if(attribute.enableAjaxValidation || attribute.clientValidation) { $container.addClass(attribute.successCssClass); } if(!attribute.hideErrorMessage) $error.toggle(hasError); attribute.value = $('#'+attribute.inputID, form).val(); return hasError; }; /** * updates the error summary, if any. * @param form jquery the jquery representation of the form * @param messages array the json data obtained from the ajax validation request */ $.fn.yiiactiveform.updateSummary = function(form, messages) { var settings = $(form).data('settings'); if (settings.summaryID == undefined) return; var content = ''; $.each(settings.attributes, function(i, attribute){ if(messages && $.isArray(messages[attribute.id])) { $.each(messages[attribute.id],function(j,message){ content = content + '<li>' + message + '</li>'; }); } }); $('#'+settings.summaryID+' ul').html(content); $('#'+settings.summaryID).toggle(content!=''); }; /** * Performs the ajax validation request. * This method is invoked internally to trigger the ajax validation. * @param form jquery the jquery representation of the form * @param successCallback function the function to be invoked if the ajax request succeeds * @param errorCallback function the function to be invoked if the ajax request fails */ $.fn.yiiactiveform.validate = function(form, successCallback, errorCallback) { var $form = $(form); var settings = $form.data('settings'); var messages = {}; var needAjaxValidation = false; $.each(settings.attributes, function(){ var msg = []; if (this.clientValidation != undefined && (settings.submitting || this.status == 2 || this.status == 3)) { var value = $('#'+this.inputID, $form).val(); this.clientValidation(value, msg, this); if (msg.length) { messages[this.id] = msg; } } if (this.enableAjaxValidation && !msg.length && (settings.submitting || this.status == 2 || this.status == 3)) needAjaxValidation = true; }); if (!needAjaxValidation || settings.submitting && !$.isEmptyObject(messages)) { if(settings.submitting) { // delay callback so that the form can be submitted without problem setTimeout(function(){ successCallback(messages); },200); } else { successCallback(messages); } return; } $.ajax({ url : settings.validationUrl, type : $form.attr('method'), data : $form.serialize()+'&'+settings.ajaxVar+'='+$form.attr('id'), dataType : 'json', success : function(data) { if (data != null && typeof data == 'object') { $.each(settings.attributes, function() { if (!this.enableAjaxValidation) delete data[this.id]; }); successCallback($.extend({}, messages, data)); } else { successCallback(messages); } }, error : function() { if (errorCallback!=undefined) { errorCallback(); } } }); }; /** * Returns the configuration for the specified form. * The configuration contains all needed information to perform ajax-based validation. * @param form jquery the jquery representation of the form * @return object the configuration for the specified form. */ $.fn.yiiactiveform.getSettings = function(form) { return $(form).data('settings'); }; $.fn.yiiactiveform.defaults = { ajaxVar: 'ajax', validationUrl: undefined, validationDelay: 200, validateOnSubmit : false, validateOnChange : true, validateOnType : false, hideErrorMessage : false, inputContainer : undefined, errorCssClass : 'error', successCssClass : 'success', validatingCssClass : 'validating', summaryID : undefined, timer: undefined, beforeValidateAttribute: undefined, // function(form, attribute) : boolean afterValidateAttribute: undefined, // function(form, attribute, data, hasError) beforeValidate: undefined, // function(form) : boolean afterValidate: undefined, // function(form, data, hasError) : boolean /** * list of attributes to be validated. Each array element is of the following structure: * { * id : 'ModelClass_attribute', // the unique attribute ID * model : 'ModelClass', // the model class name * name : 'name', // attribute name * inputID : 'input-tag-id', * errorID : 'error-tag-id', * value : undefined, * status : 0, // 0: empty, not entered before, 1: validated, 2: pending validation, 3: validating * focus : undefined, // jquery selector that indicates which element to receive input focus initially * validationDelay: 200, * validateOnChange : true, * validateOnType : false, * hideErrorMessage : false, * inputContainer : undefined, * errorCssClass : 'error', * successCssClass : 'success', * validatingCssClass : 'validating', * enableAjaxValidation : true, * enableClientValidation : true, * clientValidation : undefined, // function(value, messages, attribute) : client-side validation * beforeValidateAttribute: undefined, // function(form, attribute) : boolean * afterValidateAttribute: undefined, // function(form, attribute, data, hasError) * } */ attributes : [] }; })(jQuery);
JavaScript
/* * Treeview 1.5pre - jQuery plugin to hide and show branches of a tree * * http://bassistance.de/jquery-plugins/jquery-plugin-treeview/ * http://docs.jquery.com/Plugins/Treeview * * Copyright (c) 2007 Jörn Zaefferer * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * Revision: $Id: jquery.treeview.js 5759 2008-07-01 07:50:28Z joern.zaefferer $ * */ ;(function($) { // TODO rewrite as a widget, removing all the extra plugins $.extend($.fn, { swapClass: function(c1, c2) { var c1Elements = this.filter('.' + c1); this.filter('.' + c2).removeClass(c2).addClass(c1); c1Elements.removeClass(c1).addClass(c2); return this; }, replaceClass: function(c1, c2) { return this.filter('.' + c1).removeClass(c1).addClass(c2).end(); }, hoverClass: function(className) { className = className || "hover"; return this.hover(function() { $(this).addClass(className); }, function() { $(this).removeClass(className); }); }, heightToggle: function(animated, callback) { animated ? this.animate({ height: "toggle" }, animated, callback) : this.each(function(){ jQuery(this)[ jQuery(this).is(":hidden") ? "show" : "hide" ](); if(callback) callback.apply(this, arguments); }); }, heightHide: function(animated, callback) { if (animated) { this.animate({ height: "hide" }, animated, callback); } else { this.hide(); if (callback) this.each(callback); } }, prepareBranches: function(settings) { if (!settings.prerendered) { // mark last tree items this.filter(":last-child:not(ul)").addClass(CLASSES.last); // collapse whole tree, or only those marked as closed, anyway except those marked as open this.filter((settings.collapsed ? "" : "." + CLASSES.closed) + ":not(." + CLASSES.open + ")").find(">ul").hide(); } // return all items with sublists return this.filter(":has(>ul)"); }, applyClasses: function(settings, toggler) { // TODO use event delegation this.filter(":has(>ul):not(:has(>a))").find(">span").unbind("click.treeview").bind("click.treeview", function(event) { // don't handle click events on children, eg. checkboxes if ( this == event.target ) toggler.apply($(this).next()); }).add( $("a", this) ).hoverClass(); if (!settings.prerendered) { // handle closed ones first this.filter(":has(>ul:hidden)") .addClass(CLASSES.expandable) .replaceClass(CLASSES.last, CLASSES.lastExpandable); // handle open ones this.not(":has(>ul:hidden)") .addClass(CLASSES.collapsable) .replaceClass(CLASSES.last, CLASSES.lastCollapsable); // create hitarea if not present var hitarea = this.find("div." + CLASSES.hitarea); if (!hitarea.length) hitarea = this.prepend("<div class=\"" + CLASSES.hitarea + "\"/>").find("div." + CLASSES.hitarea); hitarea.removeClass().addClass(CLASSES.hitarea).each(function() { var classes = ""; $.each($(this).parent().attr("class").split(" "), function() { classes += this + "-hitarea "; }); $(this).addClass( classes ); }) } // apply event to hitarea this.find("div." + CLASSES.hitarea).click( toggler ); }, treeview: function(settings) { settings = $.extend({ cookieId: "treeview" }, settings); if ( settings.toggle ) { var callback = settings.toggle; settings.toggle = function() { return callback.apply($(this).parent()[0], arguments); }; } // factory for treecontroller function treeController(tree, control) { // factory for click handlers function handler(filter) { return function() { // reuse toggle event handler, applying the elements to toggle // start searching for all hitareas toggler.apply( $("div." + CLASSES.hitarea, tree).filter(function() { // for plain toggle, no filter is provided, otherwise we need to check the parent element return filter ? $(this).parent("." + filter).length : true; }) ); return false; }; } // click on first element to collapse tree $("a:eq(0)", control).click( handler(CLASSES.collapsable) ); // click on second to expand tree $("a:eq(1)", control).click( handler(CLASSES.expandable) ); // click on third to toggle tree $("a:eq(2)", control).click( handler() ); } // handle toggle event function toggler() { $(this) .parent() // swap classes for hitarea .find(">.hitarea") .swapClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea ) .swapClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea ) .end() // swap classes for parent li .swapClass( CLASSES.collapsable, CLASSES.expandable ) .swapClass( CLASSES.lastCollapsable, CLASSES.lastExpandable ) // find child lists .find( ">ul" ) // toggle them .heightToggle( settings.animated, settings.toggle ); if ( settings.unique ) { $(this).parent() .siblings() // swap classes for hitarea .find(">.hitarea") .replaceClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea ) .replaceClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea ) .end() .replaceClass( CLASSES.collapsable, CLASSES.expandable ) .replaceClass( CLASSES.lastCollapsable, CLASSES.lastExpandable ) .find( ">ul" ) .heightHide( settings.animated, settings.toggle ); } } this.data("toggler", toggler); function serialize() { function binary(arg) { return arg ? 1 : 0; } var data = []; branches.each(function(i, e) { data[i] = $(e).is(":has(>ul:visible)") ? 1 : 0; }); $.cookie(settings.cookieId, data.join(""), settings.cookieOptions ); } function deserialize() { var stored = $.cookie(settings.cookieId); if ( stored ) { var data = stored.split(""); branches.each(function(i, e) { $(e).find(">ul")[ parseInt(data[i]) ? "show" : "hide" ](); }); } } // add treeview class to activate styles this.addClass("treeview"); // prepare branches and find all tree items with child lists var branches = this.find("li").prepareBranches(settings); switch(settings.persist) { case "cookie": var toggleCallback = settings.toggle; settings.toggle = function() { serialize(); if (toggleCallback) { toggleCallback.apply(this, arguments); } }; deserialize(); break; case "location": var current = this.find("a").filter(function() { return this.href.toLowerCase() == location.href.toLowerCase(); }); if ( current.length ) { // TODO update the open/closed classes var items = current.addClass("selected").parents("ul, li").add( current.next() ).show(); if (settings.prerendered) { // if prerendered is on, replicate the basic class swapping items.filter("li") .swapClass( CLASSES.collapsable, CLASSES.expandable ) .swapClass( CLASSES.lastCollapsable, CLASSES.lastExpandable ) .find(">.hitarea") .swapClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea ) .swapClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea ); } } break; } branches.applyClasses(settings, toggler); // if control option is set, create the treecontroller and show it if ( settings.control ) { treeController(this, settings.control); $(settings.control).show(); } return this; } }); // classes used by the plugin // need to be styled via external stylesheet, see first example $.treeview = {}; var CLASSES = ($.treeview.classes = { open: "open", closed: "closed", expandable: "expandable", expandableHitarea: "expandable-hitarea", lastExpandableHitarea: "lastExpandable-hitarea", collapsable: "collapsable", collapsableHitarea: "collapsable-hitarea", lastCollapsableHitarea: "lastCollapsable-hitarea", lastCollapsable: "lastCollapsable", lastExpandable: "lastExpandable", last: "last", hitarea: "hitarea" }); })(jQuery);
JavaScript
(function($) { var CLASSES = $.treeview.classes; var proxied = $.fn.treeview; $.fn.treeview = function(settings) { settings = $.extend({}, settings); if (settings.add) { return this.trigger("add", [settings.add]); } if (settings.remove) { return this.trigger("remove", [settings.remove]); } return proxied.apply(this, arguments).bind("add", function(event, branches) { $(branches).prev() .removeClass(CLASSES.last) .removeClass(CLASSES.lastCollapsable) .removeClass(CLASSES.lastExpandable) .find(">.hitarea") .removeClass(CLASSES.lastCollapsableHitarea) .removeClass(CLASSES.lastExpandableHitarea); $(branches).find("li").andSelf().prepareBranches(settings).applyClasses(settings, $(this).data("toggler")); }).bind("remove", function(event, branches) { var prev = $(branches).prev(); var parent = $(branches).parent(); $(branches).remove(); prev.filter(":last-child").addClass(CLASSES.last) .filter("." + CLASSES.expandable).replaceClass(CLASSES.last, CLASSES.lastExpandable).end() .find(">.hitarea").replaceClass(CLASSES.expandableHitarea, CLASSES.lastExpandableHitarea).end() .filter("." + CLASSES.collapsable).replaceClass(CLASSES.last, CLASSES.lastCollapsable).end() .find(">.hitarea").replaceClass(CLASSES.collapsableHitarea, CLASSES.lastCollapsableHitarea); if (parent.is(":not(:has(>))") && parent[0] != this) { parent.parent().removeClass(CLASSES.collapsable).removeClass(CLASSES.expandable); parent.siblings(".hitarea").andSelf().remove(); } }); }; })(jQuery);
JavaScript
/*! Copyright (c) 2010 Brandon Aaron (http://brandonaaron.net) * Licensed under the MIT License (LICENSE.txt). * * Version 2.1.2 */ (function($){ $.fn.bgiframe = ($.browser.msie && /msie 6\.0/i.test(navigator.userAgent) ? function(s) { s = $.extend({ top : 'auto', // auto == .currentStyle.borderTopWidth left : 'auto', // auto == .currentStyle.borderLeftWidth width : 'auto', // auto == offsetWidth height : 'auto', // auto == offsetHeight opacity : true, src : 'javascript:false;' }, s); var html = '<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+ 'style="display:block;position:absolute;z-index:-1;'+ (s.opacity !== false?'filter:Alpha(Opacity=\'0\');':'')+ 'top:'+(s.top=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')':prop(s.top))+';'+ 'left:'+(s.left=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')':prop(s.left))+';'+ 'width:'+(s.width=='auto'?'expression(this.parentNode.offsetWidth+\'px\')':prop(s.width))+';'+ 'height:'+(s.height=='auto'?'expression(this.parentNode.offsetHeight+\'px\')':prop(s.height))+';'+ '"/>'; return this.each(function() { if ( $(this).children('iframe.bgiframe').length === 0 ) this.insertBefore( document.createElement(html), this.firstChild ); }); } : function() { return this; }); // old alias $.fn.bgIframe = $.fn.bgiframe; function prop(n) { return n && n.constructor === Number ? n + 'px' : n; } })(jQuery);
JavaScript
/* * Async Treeview 0.1 - Lazy-loading extension for Treeview * * http://bassistance.de/jquery-plugins/jquery-plugin-treeview/ * * Copyright (c) 2007 Jörn Zaefferer * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * Revision: $Id$ * */ ;(function($) { function load(settings, root, child, container) { function createNode(parent) { var current = $("<li/>").attr("id", this.id || "").html("<span>" + this.text + "</span>").appendTo(parent); if (this.classes) { current.children("span").addClass(this.classes); } if (this.expanded) { current.addClass("open"); } if (this.hasChildren || this.children && this.children.length) { var branch = $("<ul/>").appendTo(current); if (this.hasChildren) { current.addClass("hasChildren"); createNode.call({ classes: "placeholder", text: "&nbsp;", children:[] }, branch); } if (this.children && this.children.length) { $.each(this.children, createNode, [branch]) } } } $.ajax($.extend(true, { url: settings.url, dataType: "json", data: { root: root }, success: function(response) { child.empty(); $.each(response, createNode, [child]); $(container).treeview({add: child}); } }, settings.ajax)); /* $.getJSON(settings.url, {root: root}, function(response) { function createNode(parent) { var current = $("<li/>").attr("id", this.id || "").html("<span>" + this.text + "</span>").appendTo(parent); if (this.classes) { current.children("span").addClass(this.classes); } if (this.expanded) { current.addClass("open"); } if (this.hasChildren || this.children && this.children.length) { var branch = $("<ul/>").appendTo(current); if (this.hasChildren) { current.addClass("hasChildren"); createNode.call({ classes: "placeholder", text: "&nbsp;", children:[] }, branch); } if (this.children && this.children.length) { $.each(this.children, createNode, [branch]) } } } child.empty(); $.each(response, createNode, [child]); $(container).treeview({add: child}); }); */ } var proxied = $.fn.treeview; $.fn.treeview = function(settings) { if (!settings.url) { return proxied.apply(this, arguments); } var container = this; if (!container.children().size()) load(settings, "source", this, container); var userToggle = settings.toggle; return proxied.call(this, $.extend({}, settings, { collapsed: true, toggle: function() { var $this = $(this); if ($this.hasClass("hasChildren")) { var childList = $this.removeClass("hasChildren").find("ul"); load(settings, this.id, childList, container); } if (userToggle) { userToggle.apply(this, arguments); } } })); }; })(jQuery);
JavaScript
/** * jQuery Yii plugin file. * * @author Qiang Xue <qiang.xue@gmail.com> * @link http://www.yiiframework.com/ * @copyright Copyright &copy; 2008-2010 Yii Software LLC * @license http://www.yiiframework.com/license/ * @version $Id: jquery.yiitab.js 1827 2010-02-20 00:43:32Z qiang.xue $ */ ;(function($) { $.extend($.fn, { yiitab: function() { function activate(id) { var pos = id.indexOf("#"); if (pos>=0) { id = id.substring(pos); } var $tab=$(id); var $container=$tab.parent(); $container.find('>ul a').removeClass('active'); $container.find('>ul a[href="'+id+'"]').addClass('active'); $container.children('div').hide(); $tab.show(); } this.find('>ul a').click(function(event) { var href=$(this).attr('href'); var pos=href.indexOf('#'); activate(href); if(pos==0 || (pos>0 && (window.location.pathname=='' || window.location.pathname==href.substring(0,pos)))) return false; }); // activate a tab based on the current anchor var url = decodeURI(window.location); var pos = url.indexOf("#"); if (pos >= 0) { var id = url.substring(pos); if (this.find('>ul a[href="'+id+'"]').length > 0) { activate(id); return; } } } }); })(jQuery);
JavaScript
/** * Cookie plugin * * Copyright (c) 2006 Klaus Hartl (stilbuero.de) * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * */ /** * Create a cookie with the given name and value and other optional parameters. * * @example $.cookie('the_cookie', 'the_value'); * @desc Set the value of a cookie. * @example $.cookie('the_cookie', 'the_value', {expires: 7, path: '/', domain: 'jquery.com', secure: true}); * @desc Create a cookie with all available options. * @example $.cookie('the_cookie', 'the_value'); * @desc Create a session cookie. * @example $.cookie('the_cookie', null); * @desc Delete a cookie by passing null as value. * * @param String name The name of the cookie. * @param String value The value of the cookie. * @param Object options An object literal containing key/value pairs to provide optional cookie attributes. * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object. * If a negative value is specified (e.g. a date in the past), the cookie will be deleted. * If set to null or omitted, the cookie will be a session cookie and will not be retained * when the the browser exits. * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie). * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie). * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will * require a secure protocol (like HTTPS). * @type undefined * * @name $.cookie * @cat Plugins/Cookie * @author Klaus Hartl/klaus.hartl@stilbuero.de */ /** * Get the value of a cookie with the given name. * * @example $.cookie('the_cookie'); * @desc Get the value of a cookie. * * @param String name The name of the cookie. * @return The value of the cookie. * @type String * * @name $.cookie * @cat Plugins/Cookie * @author Klaus Hartl/klaus.hartl@stilbuero.de */ jQuery.cookie = function(name, value, options) { if (typeof value != 'undefined') { // name and value given, set cookie options = options || {}; if (value === null) { value = ''; options.expires = -1; } var expires = ''; if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) { var date; if (typeof options.expires == 'number') { date = new Date(); date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000)); } else { date = options.expires; } expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE } var path = options.path ? '; path=' + options.path : ''; var domain = options.domain ? '; domain=' + options.domain : ''; var secure = options.secure ? '; secure' : ''; document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join(''); } else { // only name given, get cookie var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } };
JavaScript
/// <reference path="../../../lib/jquery-1.2.6.js" /> /* Masked Input plugin for jQuery Copyright (c) 2007-2009 Josh Bush (digitalbush.com) Licensed under the MIT license (http://digitalbush.com/projects/masked-input-plugin/#license) Version: 1.2.2 (03/09/2009 22:39:06) */ (function($) { var pasteEventName = ($.browser.msie ? 'paste' : 'input') + ".mask"; var iPhone = (window.orientation != undefined); $.mask = { //Predefined character definitions definitions: { '9': "[0-9]", 'a': "[A-Za-z]", '*': "[A-Za-z0-9]" } }; $.fn.extend({ //Helper Function for Caret positioning caret: function(begin, end) { if (this.length == 0) return; if (typeof begin == 'number') { end = (typeof end == 'number') ? end : begin; return this.each(function() { if (this.setSelectionRange) { this.focus(); this.setSelectionRange(begin, end); } else if (this.createTextRange) { var range = this.createTextRange(); range.collapse(true); range.moveEnd('character', end); range.moveStart('character', begin); range.select(); } }); } else { if (this[0].setSelectionRange) { begin = this[0].selectionStart; end = this[0].selectionEnd; } else if (document.selection && document.selection.createRange) { var range = document.selection.createRange(); begin = 0 - range.duplicate().moveStart('character', -100000); end = begin + range.text.length; } return { begin: begin, end: end }; } }, unmask: function() { return this.trigger("unmask"); }, mask: function(mask, settings) { if (!mask && this.length > 0) { var input = $(this[0]); var tests = input.data("tests"); return $.map(input.data("buffer"), function(c, i) { return tests[i] ? c : null; }).join(''); } settings = $.extend({ placeholder: "_", completed: null }, settings); var defs = $.mask.definitions; var tests = []; var partialPosition = mask.length; var firstNonMaskPos = null; var len = mask.length; $.each(mask.split(""), function(i, c) { if (c == '?') { len--; partialPosition = i; } else if (defs[c]) { tests.push(new RegExp(defs[c])); if(firstNonMaskPos==null) firstNonMaskPos = tests.length - 1; } else { tests.push(null); } }); return this.each(function() { var input = $(this); var buffer = $.map(mask.split(""), function(c, i) { if (c != '?') return defs[c] ? settings.placeholder : c }); var ignore = false; //Variable for ignoring control keys var focusText = input.val(); input.data("buffer", buffer).data("tests", tests); function seekNext(pos) { while (++pos <= len && !tests[pos]); return pos; } function shiftL(pos) { while (!tests[pos] && --pos >= 0); for (var i = pos; i < len; i++) { if (tests[i]) { buffer[i] = settings.placeholder; var j = seekNext(i); if (j < len && tests[i].test(buffer[j])) { buffer[i] = buffer[j]; } else break; } } writeBuffer(); input.caret(Math.max(firstNonMaskPos, pos)); } function shiftR(pos) { for (var i = pos, c = settings.placeholder; i < len; i++) { if (tests[i]) { var j = seekNext(i); var t = buffer[i]; buffer[i] = c; if (j < len && tests[j].test(t)) c = t; else break; } } } function keydownEvent(e) { var pos = $(this).caret(); var k = e.keyCode; ignore = (k < 16 || (k > 16 && k < 32) || (k > 32 && k < 41)); //delete selection before proceeding if ((pos.begin - pos.end) != 0 && (!ignore || k == 8 || k == 46)) clearBuffer(pos.begin, pos.end); //backspace, delete, and escape get special treatment if (k == 8 || k == 46 || (iPhone && k == 127)) {//backspace/delete shiftL(pos.begin + (k == 46 ? 0 : -1)); return false; } else if (k == 27) {//escape input.val(focusText); input.caret(0, checkVal()); return false; } } function keypressEvent(e) { if (ignore) { ignore = false; //Fixes Mac FF bug on backspace return (e.keyCode == 8) ? false : null; } e = e || window.event; var k = e.charCode || e.keyCode || e.which; var pos = $(this).caret(); if (e.ctrlKey || e.altKey || e.metaKey) {//Ignore return true; } else if ((k >= 32 && k <= 125) || k > 186) {//typeable characters var p = seekNext(pos.begin - 1); if (p < len) { var c = String.fromCharCode(k); if (tests[p].test(c)) { shiftR(p); buffer[p] = c; writeBuffer(); var next = seekNext(p); $(this).caret(next); if (settings.completed && next == len) settings.completed.call(input); } } } return false; } function clearBuffer(start, end) { for (var i = start; i < end && i < len; i++) { if (tests[i]) buffer[i] = settings.placeholder; } } function writeBuffer() { return input.val(buffer.join('')).val(); } function checkVal(allow) { //try to place characters where they belong var test = input.val(); var lastMatch = -1; for (var i = 0, pos = 0; i < len; i++) { if (tests[i]) { buffer[i] = settings.placeholder; while (pos++ < test.length) { var c = test.charAt(pos - 1); if (tests[i].test(c)) { buffer[i] = c; lastMatch = i; break; } } if (pos > test.length) break; } else if (buffer[i] == test[pos] && i!=partialPosition) { pos++; lastMatch = i; } } if (!allow && lastMatch + 1 < partialPosition) { input.val(""); clearBuffer(0, len); } else if (allow || lastMatch + 1 >= partialPosition) { writeBuffer(); if (!allow) input.val(input.val().substring(0, lastMatch + 1)); } return (partialPosition ? i : firstNonMaskPos); } if (!input.attr("readonly")) input .one("unmask", function() { input .unbind(".mask") .removeData("buffer") .removeData("tests"); }) .bind("focus.mask", function() { focusText = input.val(); var pos = checkVal(); writeBuffer(); setTimeout(function() { if (pos == mask.length) input.caret(0, pos); else input.caret(pos); }, 0); }) .bind("blur.mask", function() { checkVal(); if (input.val() != focusText) input.change(); }) .bind("keydown.mask", keydownEvent) .bind("keypress.mask", keypressEvent) .bind(pasteEventName, function() { setTimeout(function() { input.caret(checkVal(true)); }, 0); }); checkVal(); //Perform initial check for existing values }); } }); })(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
(function(d, w) { var addEvent = function( obj, type, fn ) { if (obj.addEventListener) obj.addEventListener(type, fn, false); else if (obj.attachEvent) obj.attachEvent('on' + type, function() { return fn.call(obj, window.event);}); }, aB, hc = new RegExp('\\bhover\\b', 'g'), q = [], rselected = new RegExp('\\bselected\\b', 'g'), /** * Get the timeout ID of the given element */ getTOID = function(el) { var i = q.length; while( i-- ) if ( q[i] && el == q[i][1] ) return q[i][0]; return false; }, addHoverClass = function(t) { var i, id, inA, hovering, ul, li, ancestors = [], ancestorLength = 0; while ( t && t != aB && t != d ) { if( 'LI' == t.nodeName.toUpperCase() ) { ancestors[ ancestors.length ] = t; id = getTOID(t); if ( id ) clearTimeout( id ); t.className = t.className ? ( t.className.replace(hc, '') + ' hover' ) : 'hover'; hovering = t; } t = t.parentNode; } // Remove any selected classes. if ( hovering && hovering.parentNode ) { ul = hovering.parentNode; if ( ul && 'UL' == ul.nodeName.toUpperCase() ) { i = ul.childNodes.length; while ( i-- ) { li = ul.childNodes[i]; if ( li != hovering ) li.className = li.className ? li.className.replace( rselected, '' ) : ''; } } } /* remove the hover class for any objects not in the immediate element's ancestry */ i = q.length; while ( i-- ) { inA = false; ancestorLength = ancestors.length; while( ancestorLength-- ) { if ( ancestors[ ancestorLength ] == q[i][1] ) inA = true; } if ( ! inA ) q[i][1].className = q[i][1].className ? q[i][1].className.replace(hc, '') : ''; } }, removeHoverClass = function(t) { while ( t && t != aB && t != d ) { if( 'LI' == t.nodeName.toUpperCase() ) { (function(t) { var to = setTimeout(function() { t.className = t.className ? t.className.replace(hc, '') : ''; }, 500); q[q.length] = [to, t]; })(t); } t = t.parentNode; } }, clickShortlink = function(e) { var i, l, node, t = e.target || e.srcElement; // Make t the shortlink menu item, or return. while ( true ) { // Check if we've gone past the shortlink node, // or if the user is clicking on the input. if ( ! t || t == d || t == aB ) return; // Check if we've found the shortlink node. if ( t.id && t.id == 'wp-admin-bar-get-shortlink' ) break; t = t.parentNode; } // IE doesn't support preventDefault, and does support returnValue if ( e.preventDefault ) e.preventDefault(); e.returnValue = false; if ( -1 == t.className.indexOf('selected') ) t.className += ' selected'; for ( i = 0, l = t.childNodes.length; i < l; i++ ) { node = t.childNodes[i]; if ( node.className && -1 != node.className.indexOf('shortlink-input') ) { node.focus(); node.select(); node.onblur = function() { t.className = t.className ? t.className.replace( rselected, '' ) : ''; }; break; } } return false; }; addEvent(w, 'load', function() { aB = d.getElementById('wpadminbar'); if ( d.body && aB ) { d.body.appendChild( aB ); addEvent(aB, 'mouseover', function(e) { addHoverClass( e.target || e.srcElement ); }); addEvent(aB, 'mouseout', function(e) { removeHoverClass( e.target || e.srcElement ); }); addEvent(aB, 'click', clickShortlink ); } if ( w.location.hash ) w.scrollBy(0,-32); }); })(document, window);
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
/* 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
/* 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
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('#media-items').append('<div id="media-item-' + fileObj.id + '" class="media-item child-of-' + post_id + '"><div class="progress"><div class="bar"></div></div><div class="filename original"><span class="percent"></span> ' + fileObj.name + '</div></div>'); // 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: 'admin-ajax.php', 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: 'admin-ajax.php', 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
/** * 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
/** * jquery.Jcrop.js v0.9.8 * jQuery Image Cropping Plugin * @author Kelly Hallman <khallman@gmail.com> * Copyright (c) 2008-2009 Kelly Hallman - released under MIT License {{{ * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * }}} */ (function($) { $.Jcrop = function(obj,opt) { // Initialization {{{ // Sanitize some options {{{ var obj = obj, opt = opt; if (typeof(obj) !== 'object') obj = $(obj)[0]; if (typeof(opt) !== 'object') opt = { }; // Some on-the-fly fixes for MSIE...sigh if (!('trackDocument' in opt)) { opt.trackDocument = $.browser.msie ? false : true; if ($.browser.msie && $.browser.version.split('.')[0] == '8') opt.trackDocument = true; } if (!('keySupport' in opt)) opt.keySupport = $.browser.msie ? false : true; // }}} // Extend the default options {{{ var defaults = { // Basic Settings trackDocument: false, baseClass: 'jcrop', addClass: null, // Styling Options bgColor: 'black', bgOpacity: .6, borderOpacity: .4, handleOpacity: .5, handlePad: 5, handleSize: 9, handleOffset: 5, edgeMargin: 14, aspectRatio: 0, keySupport: true, cornerHandles: true, sideHandles: true, drawBorders: true, dragEdges: true, boxWidth: 0, boxHeight: 0, boundary: 8, animationDelay: 20, swingSpeed: 3, allowSelect: true, allowMove: true, allowResize: true, minSelect: [ 0, 0 ], maxSize: [ 0, 0 ], minSize: [ 0, 0 ], // Callbacks / Event Handlers onChange: function() { }, onSelect: function() { } }; var options = defaults; setOptions(opt); // }}} // Initialize some jQuery objects {{{ var $origimg = $(obj); var $img = $origimg.clone().removeAttr('id').css({ position: 'absolute' }); $img.width($origimg.width()); $img.height($origimg.height()); $origimg.after($img).hide(); presize($img,options.boxWidth,options.boxHeight); var boundx = $img.width(), boundy = $img.height(), $div = $('<div />') .width(boundx).height(boundy) .addClass(cssClass('holder')) .css({ position: 'relative', backgroundColor: options.bgColor }).insertAfter($origimg).append($img); ; if (options.addClass) $div.addClass(options.addClass); //$img.wrap($div); var $img2 = $('<img />')/*{{{*/ .attr('src',$img.attr('src')) .css('position','absolute') .width(boundx).height(boundy) ;/*}}}*/ var $img_holder = $('<div />')/*{{{*/ .width(pct(100)).height(pct(100)) .css({ zIndex: 310, position: 'absolute', overflow: 'hidden' }) .append($img2) ;/*}}}*/ var $hdl_holder = $('<div />')/*{{{*/ .width(pct(100)).height(pct(100)) .css('zIndex',320); /*}}}*/ var $sel = $('<div />')/*{{{*/ .css({ position: 'absolute', zIndex: 300 }) .insertBefore($img) .append($img_holder,$hdl_holder) ;/*}}}*/ var bound = options.boundary; var $trk = newTracker().width(boundx+(bound*2)).height(boundy+(bound*2)) .css({ position: 'absolute', top: px(-bound), left: px(-bound), zIndex: 290 }) .mousedown(newSelection); /* }}} */ // Set more variables {{{ var xlimit, ylimit, xmin, ymin; var xscale, yscale, enabled = true; var docOffset = getPos($img), // Internal states btndown, lastcurs, dimmed, animating, shift_down; // }}} // }}} // Internal Modules {{{ var Coords = function()/*{{{*/ { var x1 = 0, y1 = 0, x2 = 0, y2 = 0, ox, oy; function setPressed(pos)/*{{{*/ { var pos = rebound(pos); x2 = x1 = pos[0]; y2 = y1 = pos[1]; }; /*}}}*/ function setCurrent(pos)/*{{{*/ { var pos = rebound(pos); ox = pos[0] - x2; oy = pos[1] - y2; x2 = pos[0]; y2 = pos[1]; }; /*}}}*/ function getOffset()/*{{{*/ { return [ ox, oy ]; }; /*}}}*/ function moveOffset(offset)/*{{{*/ { var ox = offset[0], oy = offset[1]; if (0 > x1 + ox) ox -= ox + x1; if (0 > y1 + oy) oy -= oy + y1; if (boundy < y2 + oy) oy += boundy - (y2 + oy); if (boundx < x2 + ox) ox += boundx - (x2 + ox); x1 += ox; x2 += ox; y1 += oy; y2 += oy; }; /*}}}*/ function getCorner(ord)/*{{{*/ { var c = getFixed(); switch(ord) { case 'ne': return [ c.x2, c.y ]; case 'nw': return [ c.x, c.y ]; case 'se': return [ c.x2, c.y2 ]; case 'sw': return [ c.x, c.y2 ]; } }; /*}}}*/ function getFixed()/*{{{*/ { if (!options.aspectRatio) return getRect(); // This function could use some optimization I think... var aspect = options.aspectRatio, min_x = options.minSize[0]/xscale, min_y = options.minSize[1]/yscale, max_x = options.maxSize[0]/xscale, max_y = options.maxSize[1]/yscale, rw = x2 - x1, rh = y2 - y1, rwa = Math.abs(rw), rha = Math.abs(rh), real_ratio = rwa / rha, xx, yy ; if (max_x == 0) { max_x = boundx * 10 } if (max_y == 0) { max_y = boundy * 10 } if (real_ratio < aspect) { yy = y2; w = rha * aspect; xx = rw < 0 ? x1 - w : w + x1; if (xx < 0) { xx = 0; h = Math.abs((xx - x1) / aspect); yy = rh < 0 ? y1 - h: h + y1; } else if (xx > boundx) { xx = boundx; h = Math.abs((xx - x1) / aspect); yy = rh < 0 ? y1 - h : h + y1; } } else { xx = x2; h = rwa / aspect; yy = rh < 0 ? y1 - h : y1 + h; if (yy < 0) { yy = 0; w = Math.abs((yy - y1) * aspect); xx = rw < 0 ? x1 - w : w + x1; } else if (yy > boundy) { yy = boundy; w = Math.abs(yy - y1) * aspect; xx = rw < 0 ? x1 - w : w + x1; } } // Magic %-) if(xx > x1) { // right side if(xx - x1 < min_x) { xx = x1 + min_x; } else if (xx - x1 > max_x) { xx = x1 + max_x; } if(yy > y1) { yy = y1 + (xx - x1)/aspect; } else { yy = y1 - (xx - x1)/aspect; } } else if (xx < x1) { // left side if(x1 - xx < min_x) { xx = x1 - min_x } else if (x1 - xx > max_x) { xx = x1 - max_x; } if(yy > y1) { yy = y1 + (x1 - xx)/aspect; } else { yy = y1 - (x1 - xx)/aspect; } } if(xx < 0) { x1 -= xx; xx = 0; } else if (xx > boundx) { x1 -= xx - boundx; xx = boundx; } if(yy < 0) { y1 -= yy; yy = 0; } else if (yy > boundy) { y1 -= yy - boundy; yy = boundy; } return last = makeObj(flipCoords(x1,y1,xx,yy)); }; /*}}}*/ function rebound(p)/*{{{*/ { if (p[0] < 0) p[0] = 0; if (p[1] < 0) p[1] = 0; if (p[0] > boundx) p[0] = boundx; if (p[1] > boundy) p[1] = boundy; return [ p[0], p[1] ]; }; /*}}}*/ function flipCoords(x1,y1,x2,y2)/*{{{*/ { var xa = x1, xb = x2, ya = y1, yb = y2; if (x2 < x1) { xa = x2; xb = x1; } if (y2 < y1) { ya = y2; yb = y1; } return [ Math.round(xa), Math.round(ya), Math.round(xb), Math.round(yb) ]; }; /*}}}*/ function getRect()/*{{{*/ { var xsize = x2 - x1; var ysize = y2 - y1; if (xlimit && (Math.abs(xsize) > xlimit)) x2 = (xsize > 0) ? (x1 + xlimit) : (x1 - xlimit); if (ylimit && (Math.abs(ysize) > ylimit)) y2 = (ysize > 0) ? (y1 + ylimit) : (y1 - ylimit); if (ymin && (Math.abs(ysize) < ymin)) y2 = (ysize > 0) ? (y1 + ymin) : (y1 - ymin); if (xmin && (Math.abs(xsize) < xmin)) x2 = (xsize > 0) ? (x1 + xmin) : (x1 - xmin); if (x1 < 0) { x2 -= x1; x1 -= x1; } if (y1 < 0) { y2 -= y1; y1 -= y1; } if (x2 < 0) { x1 -= x2; x2 -= x2; } if (y2 < 0) { y1 -= y2; y2 -= y2; } if (x2 > boundx) { var delta = x2 - boundx; x1 -= delta; x2 -= delta; } if (y2 > boundy) { var delta = y2 - boundy; y1 -= delta; y2 -= delta; } if (x1 > boundx) { var delta = x1 - boundy; y2 -= delta; y1 -= delta; } if (y1 > boundy) { var delta = y1 - boundy; y2 -= delta; y1 -= delta; } return makeObj(flipCoords(x1,y1,x2,y2)); }; /*}}}*/ function makeObj(a)/*{{{*/ { return { x: a[0], y: a[1], x2: a[2], y2: a[3], w: a[2] - a[0], h: a[3] - a[1] }; }; /*}}}*/ return { flipCoords: flipCoords, setPressed: setPressed, setCurrent: setCurrent, getOffset: getOffset, moveOffset: moveOffset, getCorner: getCorner, getFixed: getFixed }; }(); /*}}}*/ var Selection = function()/*{{{*/ { var start, end, dragmode, awake, hdep = 370; var borders = { }; var handle = { }; var seehandles = false; var hhs = options.handleOffset; /* Insert draggable elements {{{*/ // Insert border divs for outline if (options.drawBorders) { borders = { top: insertBorder('hline') .css('top',$.browser.msie?px(-1):px(0)), bottom: insertBorder('hline'), left: insertBorder('vline'), right: insertBorder('vline') }; } // Insert handles on edges if (options.dragEdges) { handle.t = insertDragbar('n'); handle.b = insertDragbar('s'); handle.r = insertDragbar('e'); handle.l = insertDragbar('w'); } // Insert side handles options.sideHandles && createHandles(['n','s','e','w']); // Insert corner handles options.cornerHandles && createHandles(['sw','nw','ne','se']); /*}}}*/ // Private Methods function insertBorder(type)/*{{{*/ { var jq = $('<div />') .css({position: 'absolute', opacity: options.borderOpacity }) .addClass(cssClass(type)); $img_holder.append(jq); return jq; }; /*}}}*/ function dragDiv(ord,zi)/*{{{*/ { var jq = $('<div />') .mousedown(createDragger(ord)) .css({ cursor: ord+'-resize', position: 'absolute', zIndex: zi }) ; $hdl_holder.append(jq); return jq; }; /*}}}*/ function insertHandle(ord)/*{{{*/ { return dragDiv(ord,hdep++) .css({ top: px(-hhs+1), left: px(-hhs+1), opacity: options.handleOpacity }) .addClass(cssClass('handle')); }; /*}}}*/ function insertDragbar(ord)/*{{{*/ { var s = options.handleSize, o = hhs, h = s, w = s, t = o, l = o; switch(ord) { case 'n': case 's': w = pct(100); break; case 'e': case 'w': h = pct(100); break; } return dragDiv(ord,hdep++).width(w).height(h) .css({ top: px(-t+1), left: px(-l+1)}); }; /*}}}*/ function createHandles(li)/*{{{*/ { for(i in li) handle[li[i]] = insertHandle(li[i]); }; /*}}}*/ function moveHandles(c)/*{{{*/ { var midvert = Math.round((c.h / 2) - hhs), midhoriz = Math.round((c.w / 2) - hhs), north = west = -hhs+1, east = c.w - hhs, south = c.h - hhs, x, y; 'e' in handle && handle.e.css({ top: px(midvert), left: px(east) }) && handle.w.css({ top: px(midvert) }) && handle.s.css({ top: px(south), left: px(midhoriz) }) && handle.n.css({ left: px(midhoriz) }); 'ne' in handle && handle.ne.css({ left: px(east) }) && handle.se.css({ top: px(south), left: px(east) }) && handle.sw.css({ top: px(south) }); 'b' in handle && handle.b.css({ top: px(south) }) && handle.r.css({ left: px(east) }); }; /*}}}*/ function moveto(x,y)/*{{{*/ { $img2.css({ top: px(-y), left: px(-x) }); $sel.css({ top: px(y), left: px(x) }); }; /*}}}*/ function resize(w,h)/*{{{*/ { $sel.width(w).height(h); }; /*}}}*/ function refresh()/*{{{*/ { var c = Coords.getFixed(); Coords.setPressed([c.x,c.y]); Coords.setCurrent([c.x2,c.y2]); updateVisible(); }; /*}}}*/ // Internal Methods function updateVisible()/*{{{*/ { if (awake) return update(); }; /*}}}*/ function update()/*{{{*/ { var c = Coords.getFixed(); resize(c.w,c.h); moveto(c.x,c.y); options.drawBorders && borders['right'].css({ left: px(c.w-1) }) && borders['bottom'].css({ top: px(c.h-1) }); seehandles && moveHandles(c); awake || show(); options.onChange(unscale(c)); }; /*}}}*/ function show()/*{{{*/ { $sel.show(); $img.css('opacity',options.bgOpacity); awake = true; }; /*}}}*/ function release()/*{{{*/ { disableHandles(); $sel.hide(); $img.css('opacity',1); awake = false; }; /*}}}*/ function showHandles()//{{{ { if (seehandles) { moveHandles(Coords.getFixed()); $hdl_holder.show(); } }; //}}} function enableHandles()/*{{{*/ { seehandles = true; if (options.allowResize) { moveHandles(Coords.getFixed()); $hdl_holder.show(); return true; } }; /*}}}*/ function disableHandles()/*{{{*/ { seehandles = false; $hdl_holder.hide(); }; /*}}}*/ function animMode(v)/*{{{*/ { (animating = v) ? disableHandles(): enableHandles(); }; /*}}}*/ function done()/*{{{*/ { animMode(false); refresh(); }; /*}}}*/ var $track = newTracker().mousedown(createDragger('move')) .css({ cursor: 'move', position: 'absolute', zIndex: 360 }) $img_holder.append($track); disableHandles(); return { updateVisible: updateVisible, update: update, release: release, refresh: refresh, setCursor: function (cursor) { $track.css('cursor',cursor); }, enableHandles: enableHandles, enableOnly: function() { seehandles = true; }, showHandles: showHandles, disableHandles: disableHandles, animMode: animMode, done: done }; }(); /*}}}*/ var Tracker = function()/*{{{*/ { var onMove = function() { }, onDone = function() { }, trackDoc = options.trackDocument; if (!trackDoc) { $trk .mousemove(trackMove) .mouseup(trackUp) .mouseout(trackUp) ; } function toFront()/*{{{*/ { $trk.css({zIndex:450}); if (trackDoc) { $(document) .mousemove(trackMove) .mouseup(trackUp) ; } } /*}}}*/ function toBack()/*{{{*/ { $trk.css({zIndex:290}); if (trackDoc) { $(document) .unbind('mousemove',trackMove) .unbind('mouseup',trackUp) ; } } /*}}}*/ function trackMove(e)/*{{{*/ { onMove(mouseAbs(e)); }; /*}}}*/ function trackUp(e)/*{{{*/ { e.preventDefault(); e.stopPropagation(); if (btndown) { btndown = false; onDone(mouseAbs(e)); options.onSelect(unscale(Coords.getFixed())); toBack(); onMove = function() { }; onDone = function() { }; } return false; }; /*}}}*/ function activateHandlers(move,done)/* {{{ */ { btndown = true; onMove = move; onDone = done; toFront(); return false; }; /* }}} */ function setCursor(t) { $trk.css('cursor',t); }; $img.before($trk); return { activateHandlers: activateHandlers, setCursor: setCursor }; }(); /*}}}*/ var KeyManager = function()/*{{{*/ { var $keymgr = $('<input type="radio" />') .css({ position: 'absolute', left: '-30px' }) .keypress(parseKey) .blur(onBlur), $keywrap = $('<div />') .css({ position: 'absolute', overflow: 'hidden' }) .append($keymgr) ; function watchKeys()/*{{{*/ { if (options.keySupport) { $keymgr.show(); $keymgr.focus(); } }; /*}}}*/ function onBlur(e)/*{{{*/ { $keymgr.hide(); }; /*}}}*/ function doNudge(e,x,y)/*{{{*/ { if (options.allowMove) { Coords.moveOffset([x,y]); Selection.updateVisible(); }; e.preventDefault(); e.stopPropagation(); }; /*}}}*/ function parseKey(e)/*{{{*/ { if (e.ctrlKey) return true; shift_down = e.shiftKey ? true : false; var nudge = shift_down ? 10 : 1; switch(e.keyCode) { case 37: doNudge(e,-nudge,0); break; case 39: doNudge(e,nudge,0); break; case 38: doNudge(e,0,-nudge); break; case 40: doNudge(e,0,nudge); break; case 27: Selection.release(); break; case 9: return true; } return nothing(e); }; /*}}}*/ if (options.keySupport) $keywrap.insertBefore($img); return { watchKeys: watchKeys }; }(); /*}}}*/ // }}} // Internal Methods {{{ function px(n) { return '' + parseInt(n) + 'px'; }; function pct(n) { return '' + parseInt(n) + '%'; }; function cssClass(cl) { return options.baseClass + '-' + cl; }; function getPos(obj)/*{{{*/ { // Updated in v0.9.4 to use built-in dimensions plugin var pos = $(obj).offset(); return [ pos.left, pos.top ]; }; /*}}}*/ function mouseAbs(e)/*{{{*/ { return [ (e.pageX - docOffset[0]), (e.pageY - docOffset[1]) ]; }; /*}}}*/ function myCursor(type)/*{{{*/ { if (type != lastcurs) { Tracker.setCursor(type); //Handles.xsetCursor(type); lastcurs = type; } }; /*}}}*/ function startDragMode(mode,pos)/*{{{*/ { docOffset = getPos($img); Tracker.setCursor(mode=='move'?mode:mode+'-resize'); if (mode == 'move') return Tracker.activateHandlers(createMover(pos), doneSelect); var fc = Coords.getFixed(); var opp = oppLockCorner(mode); var opc = Coords.getCorner(oppLockCorner(opp)); Coords.setPressed(Coords.getCorner(opp)); Coords.setCurrent(opc); Tracker.activateHandlers(dragmodeHandler(mode,fc),doneSelect); }; /*}}}*/ function dragmodeHandler(mode,f)/*{{{*/ { return function(pos) { if (!options.aspectRatio) switch(mode) { case 'e': pos[1] = f.y2; break; case 'w': pos[1] = f.y2; break; case 'n': pos[0] = f.x2; break; case 's': pos[0] = f.x2; break; } else switch(mode) { case 'e': pos[1] = f.y+1; break; case 'w': pos[1] = f.y+1; break; case 'n': pos[0] = f.x+1; break; case 's': pos[0] = f.x+1; break; } Coords.setCurrent(pos); Selection.update(); }; }; /*}}}*/ function createMover(pos)/*{{{*/ { var lloc = pos; KeyManager.watchKeys(); return function(pos) { Coords.moveOffset([pos[0] - lloc[0], pos[1] - lloc[1]]); lloc = pos; Selection.update(); }; }; /*}}}*/ function oppLockCorner(ord)/*{{{*/ { switch(ord) { case 'n': return 'sw'; case 's': return 'nw'; case 'e': return 'nw'; case 'w': return 'ne'; case 'ne': return 'sw'; case 'nw': return 'se'; case 'se': return 'nw'; case 'sw': return 'ne'; }; }; /*}}}*/ function createDragger(ord)/*{{{*/ { return function(e) { if (options.disabled) return false; if ((ord == 'move') && !options.allowMove) return false; btndown = true; startDragMode(ord,mouseAbs(e)); e.stopPropagation(); e.preventDefault(); return false; }; }; /*}}}*/ function presize($obj,w,h)/*{{{*/ { var nw = $obj.width(), nh = $obj.height(); if ((nw > w) && w > 0) { nw = w; nh = (w/$obj.width()) * $obj.height(); } if ((nh > h) && h > 0) { nh = h; nw = (h/$obj.height()) * $obj.width(); } xscale = $obj.width() / nw; yscale = $obj.height() / nh; $obj.width(nw).height(nh); }; /*}}}*/ function unscale(c)/*{{{*/ { return { x: parseInt(c.x * xscale), y: parseInt(c.y * yscale), x2: parseInt(c.x2 * xscale), y2: parseInt(c.y2 * yscale), w: parseInt(c.w * xscale), h: parseInt(c.h * yscale) }; }; /*}}}*/ function doneSelect(pos)/*{{{*/ { var c = Coords.getFixed(); if (c.w > options.minSelect[0] && c.h > options.minSelect[1]) { Selection.enableHandles(); Selection.done(); } else { Selection.release(); } Tracker.setCursor( options.allowSelect?'crosshair':'default' ); }; /*}}}*/ function newSelection(e)/*{{{*/ { if (options.disabled) return false; if (!options.allowSelect) return false; btndown = true; docOffset = getPos($img); Selection.disableHandles(); myCursor('crosshair'); var pos = mouseAbs(e); Coords.setPressed(pos); Tracker.activateHandlers(selectDrag,doneSelect); KeyManager.watchKeys(); Selection.update(); e.stopPropagation(); e.preventDefault(); return false; }; /*}}}*/ function selectDrag(pos)/*{{{*/ { Coords.setCurrent(pos); Selection.update(); }; /*}}}*/ function newTracker() { var trk = $('<div></div>').addClass(cssClass('tracker')); $.browser.msie && trk.css({ opacity: 0, backgroundColor: 'white' }); return trk; }; // }}} // API methods {{{ function animateTo(a)/*{{{*/ { var x1 = a[0] / xscale, y1 = a[1] / yscale, x2 = a[2] / xscale, y2 = a[3] / yscale; if (animating) return; var animto = Coords.flipCoords(x1,y1,x2,y2); var c = Coords.getFixed(); var animat = initcr = [ c.x, c.y, c.x2, c.y2 ]; var interv = options.animationDelay; var x = animat[0]; var y = animat[1]; var x2 = animat[2]; var y2 = animat[3]; var ix1 = animto[0] - initcr[0]; var iy1 = animto[1] - initcr[1]; var ix2 = animto[2] - initcr[2]; var iy2 = animto[3] - initcr[3]; var pcent = 0; var velocity = options.swingSpeed; Selection.animMode(true); var animator = function() { return function() { pcent += (100 - pcent) / velocity; animat[0] = x + ((pcent / 100) * ix1); animat[1] = y + ((pcent / 100) * iy1); animat[2] = x2 + ((pcent / 100) * ix2); animat[3] = y2 + ((pcent / 100) * iy2); if (pcent < 100) animateStart(); else Selection.done(); if (pcent >= 99.8) pcent = 100; setSelectRaw(animat); }; }(); function animateStart() { window.setTimeout(animator,interv); }; animateStart(); }; /*}}}*/ function setSelect(rect)//{{{ { setSelectRaw([rect[0]/xscale,rect[1]/yscale,rect[2]/xscale,rect[3]/yscale]); }; //}}} function setSelectRaw(l) /*{{{*/ { Coords.setPressed([l[0],l[1]]); Coords.setCurrent([l[2],l[3]]); Selection.update(); }; /*}}}*/ function setOptions(opt)/*{{{*/ { if (typeof(opt) != 'object') opt = { }; options = $.extend(options,opt); if (typeof(options.onChange)!=='function') options.onChange = function() { }; if (typeof(options.onSelect)!=='function') options.onSelect = function() { }; }; /*}}}*/ function tellSelect()/*{{{*/ { return unscale(Coords.getFixed()); }; /*}}}*/ function tellScaled()/*{{{*/ { return Coords.getFixed(); }; /*}}}*/ function setOptionsNew(opt)/*{{{*/ { setOptions(opt); interfaceUpdate(); }; /*}}}*/ function disableCrop()//{{{ { options.disabled = true; Selection.disableHandles(); Selection.setCursor('default'); Tracker.setCursor('default'); }; //}}} function enableCrop()//{{{ { options.disabled = false; interfaceUpdate(); }; //}}} function cancelCrop()//{{{ { Selection.done(); Tracker.activateHandlers(null,null); }; //}}} function destroy()//{{{ { $div.remove(); $origimg.show(); }; //}}} function interfaceUpdate(alt)//{{{ // This method tweaks the interface based on options object. // Called when options are changed and at end of initialization. { options.allowResize ? alt?Selection.enableOnly():Selection.enableHandles(): Selection.disableHandles(); Tracker.setCursor( options.allowSelect? 'crosshair': 'default' ); Selection.setCursor( options.allowMove? 'move': 'default' ); $div.css('backgroundColor',options.bgColor); if ('setSelect' in options) { setSelect(opt.setSelect); Selection.done(); delete(options.setSelect); } if ('trueSize' in options) { xscale = options.trueSize[0] / boundx; yscale = options.trueSize[1] / boundy; } xlimit = options.maxSize[0] || 0; ylimit = options.maxSize[1] || 0; xmin = options.minSize[0] || 0; ymin = options.minSize[1] || 0; if ('outerImage' in options) { $img.attr('src',options.outerImage); delete(options.outerImage); } Selection.refresh(); }; //}}} // }}} $hdl_holder.hide(); interfaceUpdate(true); var api = { animateTo: animateTo, setSelect: setSelect, setOptions: setOptionsNew, tellSelect: tellSelect, tellScaled: tellScaled, disable: disableCrop, enable: enableCrop, cancel: cancelCrop, focus: KeyManager.watchKeys, getBounds: function() { return [ boundx * xscale, boundy * yscale ]; }, getWidgetSize: function() { return [ boundx, boundy ]; }, release: Selection.release, destroy: destroy }; $origimg.data('Jcrop',api); return api; }; $.fn.Jcrop = function(options)/*{{{*/ { function attachWhenDone(from)/*{{{*/ { var loadsrc = options.useImg || from.src; var img = new Image(); img.onload = function() { $.Jcrop(from,options); }; img.src = loadsrc; }; /*}}}*/ if (typeof(options) !== 'object') options = { }; // Iterate over each object, attach Jcrop this.each(function() { // If we've already attached to this object if ($(this).data('Jcrop')) { // The API can be requested this way (undocumented) if (options == 'api') return $(this).data('Jcrop'); // Otherwise, we just reset the options... else $(this).data('Jcrop').setOptions(options); } // If we haven't been attached, preload and attach else attachWhenDone(this); }); // Return "this" so we're chainable a la jQuery plugin-style! return this; }; /*}}}*/ })(jQuery);
JavaScript
(function($) { var fs = {add:'ajaxAdd',del:'ajaxDel',dim:'ajaxDim',process:'process',recolor:'recolor'}, wpList; wpList = { settings: { url: ajaxurl, type: 'POST', response: 'ajax-response', what: '', alt: 'alternate', altOffset: 0, addColor: null, delColor: null, dimAddColor: null, dimDelColor: null, confirm: null, addBefore: null, addAfter: null, delBefore: null, delAfter: null, dimBefore: null, dimAfter: null }, nonce: function(e,s) { var url = wpAjax.unserialize(e.attr('href')); return s.nonce || url._ajax_nonce || $('#' + s.element + ' input[name="_ajax_nonce"]').val() || url._wpnonce || $('#' + s.element + ' input[name="_wpnonce"]').val() || 0; }, parseClass: function(e,t) { var c = [], cl; try { cl = $(e).attr('class') || ''; cl = cl.match(new RegExp(t+':[\\S]+')); if ( cl ) c = cl[0].split(':'); } catch(r) {} return c; }, pre: function(e,s,a) { var bg, r; s = $.extend( {}, this.wpList.settings, { element: null, nonce: 0, target: e.get(0) }, s || {} ); if ( $.isFunction( s.confirm ) ) { if ( 'add' != a ) { bg = $('#' + s.element).css('backgroundColor'); $('#' + s.element).css('backgroundColor', '#FF9966'); } r = s.confirm.call(this, e, s, a, bg); if ( 'add' != a ) $('#' + s.element).css('backgroundColor', bg ); if ( !r ) return false; } return s; }, ajaxAdd: function( e, s ) { e = $(e); s = s || {}; var list = this, cls = wpList.parseClass(e,'add'), es, valid, formData, res, rres; s = wpList.pre.call( list, e, s, 'add' ); s.element = cls[2] || e.attr( 'id' ) || s.element || null; if ( cls[3] ) s.addColor = '#' + cls[3]; else s.addColor = s.addColor || '#FFFF33'; if ( !s ) return false; if ( !e.is('[class^="add:' + list.id + ':"]') ) return !wpList.add.call( list, e, s ); if ( !s.element ) return true; s.action = 'add-' + s.what; s.nonce = wpList.nonce(e,s); es = $('#' + s.element + ' :input').not('[name="_ajax_nonce"], [name="_wpnonce"], [name="action"]'); valid = wpAjax.validateForm( '#' + s.element ); if ( !valid ) return false; s.data = $.param( $.extend( { _ajax_nonce: s.nonce, action: s.action }, wpAjax.unserialize( cls[4] || '' ) ) ); formData = $.isFunction(es.fieldSerialize) ? es.fieldSerialize() : es.serialize(); if ( formData ) s.data += '&' + formData; if ( $.isFunction(s.addBefore) ) { s = s.addBefore( s ); if ( !s ) return true; } if ( !s.data.match(/_ajax_nonce=[a-f0-9]+/) ) return true; s.success = function(r) { res = wpAjax.parseAjaxResponse(r, s.response, s.element); rres = r; if ( !res || res.errors ) return false; if ( true === res ) return true; jQuery.each( res.responses, function() { wpList.add.call( list, this.data, $.extend( {}, s, { // this.firstChild.nodevalue pos: this.position || 0, id: this.id || 0, oldId: this.oldId || null } ) ); } ); list.wpList.recolor(); $(list).trigger( 'wpListAddEnd', [ s, list.wpList ] ); wpList.clear.call(list,'#' + s.element); }; s.complete = function(x, st) { if ( $.isFunction(s.addAfter) ) { var _s = $.extend( { xml: x, status: st, parsed: res }, s ); s.addAfter( rres, _s ); } }; $.ajax( s ); return false; }, ajaxDel: function( e, s ) { e = $(e); s = s || {}; var list = this, cls = wpList.parseClass(e,'delete'), element, res, rres; s = wpList.pre.call( list, e, s, 'delete' ); s.element = cls[2] || s.element || null; if ( cls[3] ) s.delColor = '#' + cls[3]; else s.delColor = s.delColor || '#faa'; if ( !s || !s.element ) return false; s.action = 'delete-' + s.what; s.nonce = wpList.nonce(e,s); s.data = $.extend( { action: s.action, id: s.element.split('-').pop(), _ajax_nonce: s.nonce }, wpAjax.unserialize( cls[4] || '' ) ); if ( $.isFunction(s.delBefore) ) { s = s.delBefore( s, list ); if ( !s ) return true; } if ( !s.data._ajax_nonce ) return true; element = $('#' + s.element); if ( 'none' != s.delColor ) { element.css( 'backgroundColor', s.delColor ).fadeOut( 350, function(){ list.wpList.recolor(); $(list).trigger( 'wpListDelEnd', [ s, list.wpList ] ); }); } else { list.wpList.recolor(); $(list).trigger( 'wpListDelEnd', [ s, list.wpList ] ); } s.success = function(r) { res = wpAjax.parseAjaxResponse(r, s.response, s.element); rres = r; if ( !res || res.errors ) { element.stop().stop().css( 'backgroundColor', '#faa' ).show().queue( function() { list.wpList.recolor(); $(this).dequeue(); } ); return false; } }; s.complete = function(x, st) { if ( $.isFunction(s.delAfter) ) { element.queue( function() { var _s = $.extend( { xml: x, status: st, parsed: res }, s ); s.delAfter( rres, _s ); }).dequeue(); } } $.ajax( s ); return false; }, ajaxDim: function( e, s ) { if ( $(e).parent().css('display') == 'none' ) // Prevent hidden links from being clicked by hotkeys return false; e = $(e); s = s || {}; var list = this, cls = wpList.parseClass(e,'dim'), element, isClass, color, dimColor, res, rres; s = wpList.pre.call( list, e, s, 'dim' ); s.element = cls[2] || s.element || null; s.dimClass = cls[3] || s.dimClass || null; if ( cls[4] ) s.dimAddColor = '#' + cls[4]; else s.dimAddColor = s.dimAddColor || '#FFFF33'; if ( cls[5] ) s.dimDelColor = '#' + cls[5]; else s.dimDelColor = s.dimDelColor || '#FF3333'; if ( !s || !s.element || !s.dimClass ) return true; s.action = 'dim-' + s.what; s.nonce = wpList.nonce(e,s); s.data = $.extend( { action: s.action, id: s.element.split('-').pop(), dimClass: s.dimClass, _ajax_nonce : s.nonce }, wpAjax.unserialize( cls[6] || '' ) ); if ( $.isFunction(s.dimBefore) ) { s = s.dimBefore( s ); if ( !s ) return true; } element = $('#' + s.element); isClass = element.toggleClass(s.dimClass).is('.' + s.dimClass); color = wpList.getColor( element ); element.toggleClass( s.dimClass ); dimColor = isClass ? s.dimAddColor : s.dimDelColor; if ( 'none' != dimColor ) { element .animate( { backgroundColor: dimColor }, 'fast' ) .queue( function() { element.toggleClass(s.dimClass); $(this).dequeue(); } ) .animate( { backgroundColor: color }, { complete: function() { $(this).css( 'backgroundColor', '' ); $(list).trigger( 'wpListDimEnd', [ s, list.wpList ] ); } }); } else { $(list).trigger( 'wpListDimEnd', [ s, list.wpList ] ); } if ( !s.data._ajax_nonce ) return true; s.success = function(r) { res = wpAjax.parseAjaxResponse(r, s.response, s.element); rres = r; if ( !res || res.errors ) { element.stop().stop().css( 'backgroundColor', '#FF3333' )[isClass?'removeClass':'addClass'](s.dimClass).show().queue( function() { list.wpList.recolor(); $(this).dequeue(); } ); return false; } }; s.complete = function(x, st) { if ( $.isFunction(s.dimAfter) ) { element.queue( function() { var _s = $.extend( { xml: x, status: st, parsed: res }, s ); s.dimAfter( rres, _s ); }).dequeue(); } }; $.ajax( s ); return false; }, getColor: function( el ) { var color = jQuery(el).css('backgroundColor'); return color || '#ffffff'; }, add: function( e, s ) { e = $(e); var list = $(this), old = false, _s = { pos: 0, id: 0, oldId: null }, ba, ref, color; if ( 'string' == typeof s ) s = { what: s }; s = $.extend(_s, this.wpList.settings, s); if ( !e.size() || !s.what ) return false; if ( s.oldId ) old = $('#' + s.what + '-' + s.oldId); if ( s.id && ( s.id != s.oldId || !old || !old.size() ) ) $('#' + s.what + '-' + s.id).remove(); if ( old && old.size() ) { old.before(e); old.remove(); } else if ( isNaN(s.pos) ) { ba = 'after'; if ( '-' == s.pos.substr(0,1) ) { s.pos = s.pos.substr(1); ba = 'before'; } ref = list.find( '#' + s.pos ); if ( 1 === ref.size() ) ref[ba](e); else list.append(e); } else if ( 'comment' != s.what || 0 === $('#' + s.element).length ) { if ( s.pos < 0 ) { list.prepend(e); } else { list.append(e); } } if ( s.alt ) { if ( ( list.children(':visible').index( e[0] ) + s.altOffset ) % 2 ) { e.removeClass( s.alt ); } else { e.addClass( s.alt ); } } if ( 'none' != s.addColor ) { color = wpList.getColor( e ); e.css( 'backgroundColor', s.addColor ).animate( { backgroundColor: color }, { complete: function() { $(this).css( 'backgroundColor', '' ); } } ); } list.each( function() { this.wpList.process( e ); } ); return e; }, clear: function(e) { var list = this, t, tag; e = $(e); if ( list.wpList && e.parents( '#' + list.id ).size() ) return; e.find(':input').each( function() { if ( $(this).parents('.form-no-clear').size() ) return; t = this.type.toLowerCase(); tag = this.tagName.toLowerCase(); if ( 'text' == t || 'password' == t || 'textarea' == tag ) this.value = ''; else if ( 'checkbox' == t || 'radio' == t ) this.checked = false; else if ( 'select' == tag ) this.selectedIndex = null; }); }, process: function(el) { var list = this, $el = $(el || document); $el.delegate( 'form[class^="add:' + list.id + ':"]', 'submit', function(){ return list.wpList.add(this); }); $el.delegate( '[class^="add:' + list.id + ':"]:not(form)', 'click', function(){ return list.wpList.add(this); }); $el.delegate( '[class^="delete:' + list.id + ':"]', 'click', function(){ return list.wpList.del(this); }); $el.delegate( '[class^="dim:' + list.id + ':"]', 'click', function(){ return list.wpList.dim(this); }); }, recolor: function() { var list = this, items, eo; if ( !list.wpList.settings.alt ) return; items = $('.list-item:visible', list); if ( !items.size() ) items = $(list).children(':visible'); eo = [':even',':odd']; if ( list.wpList.settings.altOffset % 2 ) eo.reverse(); items.filter(eo[0]).addClass(list.wpList.settings.alt).end().filter(eo[1]).removeClass(list.wpList.settings.alt); }, init: function() { var lists = this; lists.wpList.process = function(a) { lists.each( function() { this.wpList.process(a); } ); }; lists.wpList.recolor = function() { lists.each( function() { this.wpList.recolor(); } ); }; } }; $.fn.wpList = function( settings ) { this.each( function() { var _this = this; this.wpList = { settings: $.extend( {}, wpList.settings, { what: wpList.parseClass(this,'list')[1] || '' }, settings ) }; $.each( fs, function(i,f) { _this.wpList[i] = function( e, s ) { return wpList[f].call( _this, e, s ); }; } ); } ); wpList.init.call(this); this.wpList.process(); return this; }; })(jQuery);
JavaScript
// script.aculo.us unittest.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009 // Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) // (c) 2005-2009 Jon Tirsen (http://www.tirsen.com) // (c) 2005-2009 Michael Schuerig (http://www.schuerig.de/michael/) // // script.aculo.us is freely distributable under the terms of an MIT-style license. // For details, see the script.aculo.us web site: http://script.aculo.us/ // experimental, Firefox-only Event.simulateMouse = function(element, eventName) { var options = Object.extend({ pointerX: 0, pointerY: 0, buttons: 0, ctrlKey: false, altKey: false, shiftKey: false, metaKey: false }, arguments[2] || {}); var oEvent = document.createEvent("MouseEvents"); oEvent.initMouseEvent(eventName, true, true, document.defaultView, options.buttons, options.pointerX, options.pointerY, options.pointerX, options.pointerY, options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, 0, $(element)); if(this.mark) Element.remove(this.mark); this.mark = document.createElement('div'); this.mark.appendChild(document.createTextNode(" ")); document.body.appendChild(this.mark); this.mark.style.position = 'absolute'; this.mark.style.top = options.pointerY + "px"; this.mark.style.left = options.pointerX + "px"; this.mark.style.width = "5px"; this.mark.style.height = "5px;"; this.mark.style.borderTop = "1px solid red;"; this.mark.style.borderLeft = "1px solid red;"; if(this.step) alert('['+new Date().getTime().toString()+'] '+eventName+'/'+Test.Unit.inspect(options)); $(element).dispatchEvent(oEvent); }; // Note: Due to a fix in Firefox 1.0.5/6 that probably fixed "too much", this doesn't work in 1.0.6 or DP2. // You need to downgrade to 1.0.4 for now to get this working // See https://bugzilla.mozilla.org/show_bug.cgi?id=289940 for the fix that fixed too much Event.simulateKey = function(element, eventName) { var options = Object.extend({ ctrlKey: false, altKey: false, shiftKey: false, metaKey: false, keyCode: 0, charCode: 0 }, arguments[2] || {}); var oEvent = document.createEvent("KeyEvents"); oEvent.initKeyEvent(eventName, true, true, window, options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.keyCode, options.charCode ); $(element).dispatchEvent(oEvent); }; Event.simulateKeys = function(element, command) { for(var i=0; i<command.length; i++) { Event.simulateKey(element,'keypress',{charCode:command.charCodeAt(i)}); } }; var Test = {}; Test.Unit = {}; // security exception workaround Test.Unit.inspect = Object.inspect; Test.Unit.Logger = Class.create(); Test.Unit.Logger.prototype = { initialize: function(log) { this.log = $(log); if (this.log) { this._createLogTable(); } }, start: function(testName) { if (!this.log) return; this.testName = testName; this.lastLogLine = document.createElement('tr'); this.statusCell = document.createElement('td'); this.nameCell = document.createElement('td'); this.nameCell.className = "nameCell"; this.nameCell.appendChild(document.createTextNode(testName)); this.messageCell = document.createElement('td'); this.lastLogLine.appendChild(this.statusCell); this.lastLogLine.appendChild(this.nameCell); this.lastLogLine.appendChild(this.messageCell); this.loglines.appendChild(this.lastLogLine); }, finish: function(status, summary) { if (!this.log) return; this.lastLogLine.className = status; this.statusCell.innerHTML = status; this.messageCell.innerHTML = this._toHTML(summary); this.addLinksToResults(); }, message: function(message) { if (!this.log) return; this.messageCell.innerHTML = this._toHTML(message); }, summary: function(summary) { if (!this.log) return; this.logsummary.innerHTML = this._toHTML(summary); }, _createLogTable: function() { this.log.innerHTML = '<div id="logsummary"></div>' + '<table id="logtable">' + '<thead><tr><th>Status</th><th>Test</th><th>Message</th></tr></thead>' + '<tbody id="loglines"></tbody>' + '</table>'; this.logsummary = $('logsummary'); this.loglines = $('loglines'); }, _toHTML: function(txt) { return txt.escapeHTML().replace(/\n/g,"<br/>"); }, addLinksToResults: function(){ $$("tr.failed .nameCell").each( function(td){ // todo: limit to children of this.log td.title = "Run only this test"; Event.observe(td, 'click', function(){ window.location.search = "?tests=" + td.innerHTML;}); }); $$("tr.passed .nameCell").each( function(td){ // todo: limit to children of this.log td.title = "Run all tests"; Event.observe(td, 'click', function(){ window.location.search = "";}); }); } }; Test.Unit.Runner = Class.create(); Test.Unit.Runner.prototype = { initialize: function(testcases) { this.options = Object.extend({ testLog: 'testlog' }, arguments[1] || {}); this.options.resultsURL = this.parseResultsURLQueryParameter(); this.options.tests = this.parseTestsQueryParameter(); if (this.options.testLog) { this.options.testLog = $(this.options.testLog) || null; } if(this.options.tests) { this.tests = []; for(var i = 0; i < this.options.tests.length; i++) { if(/^test/.test(this.options.tests[i])) { this.tests.push(new Test.Unit.Testcase(this.options.tests[i], testcases[this.options.tests[i]], testcases["setup"], testcases["teardown"])); } } } else { if (this.options.test) { this.tests = [new Test.Unit.Testcase(this.options.test, testcases[this.options.test], testcases["setup"], testcases["teardown"])]; } else { this.tests = []; for(var testcase in testcases) { if(/^test/.test(testcase)) { this.tests.push( new Test.Unit.Testcase( this.options.context ? ' -> ' + this.options.titles[testcase] : testcase, testcases[testcase], testcases["setup"], testcases["teardown"] )); } } } } this.currentTest = 0; this.logger = new Test.Unit.Logger(this.options.testLog); setTimeout(this.runTests.bind(this), 1000); }, parseResultsURLQueryParameter: function() { return window.location.search.parseQuery()["resultsURL"]; }, parseTestsQueryParameter: function(){ if (window.location.search.parseQuery()["tests"]){ return window.location.search.parseQuery()["tests"].split(','); }; }, // Returns: // "ERROR" if there was an error, // "FAILURE" if there was a failure, or // "SUCCESS" if there was neither getResult: function() { var hasFailure = false; for(var i=0;i<this.tests.length;i++) { if (this.tests[i].errors > 0) { return "ERROR"; } if (this.tests[i].failures > 0) { hasFailure = true; } } if (hasFailure) { return "FAILURE"; } else { return "SUCCESS"; } }, postResults: function() { if (this.options.resultsURL) { new Ajax.Request(this.options.resultsURL, { method: 'get', parameters: 'result=' + this.getResult(), asynchronous: false }); } }, runTests: function() { var test = this.tests[this.currentTest]; if (!test) { // finished! this.postResults(); this.logger.summary(this.summary()); return; } if(!test.isWaiting) { this.logger.start(test.name); } test.run(); if(test.isWaiting) { this.logger.message("Waiting for " + test.timeToWait + "ms"); setTimeout(this.runTests.bind(this), test.timeToWait || 1000); } else { this.logger.finish(test.status(), test.summary()); this.currentTest++; // tail recursive, hopefully the browser will skip the stackframe this.runTests(); } }, summary: function() { var assertions = 0; var failures = 0; var errors = 0; var messages = []; for(var i=0;i<this.tests.length;i++) { assertions += this.tests[i].assertions; failures += this.tests[i].failures; errors += this.tests[i].errors; } return ( (this.options.context ? this.options.context + ': ': '') + this.tests.length + " tests, " + assertions + " assertions, " + failures + " failures, " + errors + " errors"); } }; Test.Unit.Assertions = Class.create(); Test.Unit.Assertions.prototype = { initialize: function() { this.assertions = 0; this.failures = 0; this.errors = 0; this.messages = []; }, summary: function() { return ( this.assertions + " assertions, " + this.failures + " failures, " + this.errors + " errors" + "\n" + this.messages.join("\n")); }, pass: function() { this.assertions++; }, fail: function(message) { this.failures++; this.messages.push("Failure: " + message); }, info: function(message) { this.messages.push("Info: " + message); }, error: function(error) { this.errors++; this.messages.push(error.name + ": "+ error.message + "(" + Test.Unit.inspect(error) +")"); }, status: function() { if (this.failures > 0) return 'failed'; if (this.errors > 0) return 'error'; return 'passed'; }, assert: function(expression) { var message = arguments[1] || 'assert: got "' + Test.Unit.inspect(expression) + '"'; try { expression ? this.pass() : this.fail(message); } catch(e) { this.error(e); } }, assertEqual: function(expected, actual) { var message = arguments[2] || "assertEqual"; try { (expected == actual) ? this.pass() : this.fail(message + ': expected "' + Test.Unit.inspect(expected) + '", actual "' + Test.Unit.inspect(actual) + '"'); } catch(e) { this.error(e); } }, assertInspect: function(expected, actual) { var message = arguments[2] || "assertInspect"; try { (expected == actual.inspect()) ? this.pass() : this.fail(message + ': expected "' + Test.Unit.inspect(expected) + '", actual "' + Test.Unit.inspect(actual) + '"'); } catch(e) { this.error(e); } }, assertEnumEqual: function(expected, actual) { var message = arguments[2] || "assertEnumEqual"; try { $A(expected).length == $A(actual).length && expected.zip(actual).all(function(pair) { return pair[0] == pair[1] }) ? this.pass() : this.fail(message + ': expected ' + Test.Unit.inspect(expected) + ', actual ' + Test.Unit.inspect(actual)); } catch(e) { this.error(e); } }, assertNotEqual: function(expected, actual) { var message = arguments[2] || "assertNotEqual"; try { (expected != actual) ? this.pass() : this.fail(message + ': got "' + Test.Unit.inspect(actual) + '"'); } catch(e) { this.error(e); } }, assertIdentical: function(expected, actual) { var message = arguments[2] || "assertIdentical"; try { (expected === actual) ? this.pass() : this.fail(message + ': expected "' + Test.Unit.inspect(expected) + '", actual "' + Test.Unit.inspect(actual) + '"'); } catch(e) { this.error(e); } }, assertNotIdentical: function(expected, actual) { var message = arguments[2] || "assertNotIdentical"; try { !(expected === actual) ? this.pass() : this.fail(message + ': expected "' + Test.Unit.inspect(expected) + '", actual "' + Test.Unit.inspect(actual) + '"'); } catch(e) { this.error(e); } }, assertNull: function(obj) { var message = arguments[1] || 'assertNull'; try { (obj==null) ? this.pass() : this.fail(message + ': got "' + Test.Unit.inspect(obj) + '"'); } catch(e) { this.error(e); } }, assertMatch: function(expected, actual) { var message = arguments[2] || 'assertMatch'; var regex = new RegExp(expected); try { (regex.exec(actual)) ? this.pass() : this.fail(message + ' : regex: "' + Test.Unit.inspect(expected) + ' did not match: ' + Test.Unit.inspect(actual) + '"'); } catch(e) { this.error(e); } }, assertHidden: function(element) { var message = arguments[1] || 'assertHidden'; this.assertEqual("none", element.style.display, message); }, assertNotNull: function(object) { var message = arguments[1] || 'assertNotNull'; this.assert(object != null, message); }, assertType: function(expected, actual) { var message = arguments[2] || 'assertType'; try { (actual.constructor == expected) ? this.pass() : this.fail(message + ': expected "' + Test.Unit.inspect(expected) + '", actual "' + (actual.constructor) + '"'); } catch(e) { this.error(e); } }, assertNotOfType: function(expected, actual) { var message = arguments[2] || 'assertNotOfType'; try { (actual.constructor != expected) ? this.pass() : this.fail(message + ': expected "' + Test.Unit.inspect(expected) + '", actual "' + (actual.constructor) + '"'); } catch(e) { this.error(e); } }, assertInstanceOf: function(expected, actual) { var message = arguments[2] || 'assertInstanceOf'; try { (actual instanceof expected) ? this.pass() : this.fail(message + ": object was not an instance of the expected type"); } catch(e) { this.error(e); } }, assertNotInstanceOf: function(expected, actual) { var message = arguments[2] || 'assertNotInstanceOf'; try { !(actual instanceof expected) ? this.pass() : this.fail(message + ": object was an instance of the not expected type"); } catch(e) { this.error(e); } }, assertRespondsTo: function(method, obj) { var message = arguments[2] || 'assertRespondsTo'; try { (obj[method] && typeof obj[method] == 'function') ? this.pass() : this.fail(message + ": object doesn't respond to [" + method + "]"); } catch(e) { this.error(e); } }, assertReturnsTrue: function(method, obj) { var message = arguments[2] || 'assertReturnsTrue'; try { var m = obj[method]; if(!m) m = obj['is'+method.charAt(0).toUpperCase()+method.slice(1)]; m() ? this.pass() : this.fail(message + ": method returned false"); } catch(e) { this.error(e); } }, assertReturnsFalse: function(method, obj) { var message = arguments[2] || 'assertReturnsFalse'; try { var m = obj[method]; if(!m) m = obj['is'+method.charAt(0).toUpperCase()+method.slice(1)]; !m() ? this.pass() : this.fail(message + ": method returned true"); } catch(e) { this.error(e); } }, assertRaise: function(exceptionName, method) { var message = arguments[2] || 'assertRaise'; try { method(); this.fail(message + ": exception expected but none was raised"); } catch(e) { ((exceptionName == null) || (e.name==exceptionName)) ? this.pass() : this.error(e); } }, assertElementsMatch: function() { var expressions = $A(arguments), elements = $A(expressions.shift()); if (elements.length != expressions.length) { this.fail('assertElementsMatch: size mismatch: ' + elements.length + ' elements, ' + expressions.length + ' expressions'); return false; } elements.zip(expressions).all(function(pair, index) { var element = $(pair.first()), expression = pair.last(); if (element.match(expression)) return true; this.fail('assertElementsMatch: (in index ' + index + ') expected ' + expression.inspect() + ' but got ' + element.inspect()); }.bind(this)) && this.pass(); }, assertElementMatches: function(element, expression) { this.assertElementsMatch([element], expression); }, benchmark: function(operation, iterations) { var startAt = new Date(); (iterations || 1).times(operation); var timeTaken = ((new Date())-startAt); this.info((arguments[2] || 'Operation') + ' finished ' + iterations + ' iterations in ' + (timeTaken/1000)+'s' ); return timeTaken; }, _isVisible: function(element) { element = $(element); if(!element.parentNode) return true; this.assertNotNull(element); if(element.style && Element.getStyle(element, 'display') == 'none') return false; return this._isVisible(element.parentNode); }, assertNotVisible: function(element) { this.assert(!this._isVisible(element), Test.Unit.inspect(element) + " was not hidden and didn't have a hidden parent either. " + ("" || arguments[1])); }, assertVisible: function(element) { this.assert(this._isVisible(element), Test.Unit.inspect(element) + " was not visible. " + ("" || arguments[1])); }, benchmark: function(operation, iterations) { var startAt = new Date(); (iterations || 1).times(operation); var timeTaken = ((new Date())-startAt); this.info((arguments[2] || 'Operation') + ' finished ' + iterations + ' iterations in ' + (timeTaken/1000)+'s' ); return timeTaken; } }; Test.Unit.Testcase = Class.create(); Object.extend(Object.extend(Test.Unit.Testcase.prototype, Test.Unit.Assertions.prototype), { initialize: function(name, test, setup, teardown) { Test.Unit.Assertions.prototype.initialize.bind(this)(); this.name = name; if(typeof test == 'string') { test = test.gsub(/(\.should[^\(]+\()/,'#{0}this,'); test = test.gsub(/(\.should[^\(]+)\(this,\)/,'#{1}(this)'); this.test = function() { eval('with(this){'+test+'}'); } } else { this.test = test || function() {}; } this.setup = setup || function() {}; this.teardown = teardown || function() {}; this.isWaiting = false; this.timeToWait = 1000; }, wait: function(time, nextPart) { this.isWaiting = true; this.test = nextPart; this.timeToWait = time; }, run: function() { try { try { if (!this.isWaiting) this.setup.bind(this)(); this.isWaiting = false; this.test.bind(this)(); } finally { if(!this.isWaiting) { this.teardown.bind(this)(); } } } catch(e) { this.error(e); } } }); // *EXPERIMENTAL* BDD-style testing to please non-technical folk // This draws many ideas from RSpec http://rspec.rubyforge.org/ Test.setupBDDExtensionMethods = function(){ var METHODMAP = { shouldEqual: 'assertEqual', shouldNotEqual: 'assertNotEqual', shouldEqualEnum: 'assertEnumEqual', shouldBeA: 'assertType', shouldNotBeA: 'assertNotOfType', shouldBeAn: 'assertType', shouldNotBeAn: 'assertNotOfType', shouldBeNull: 'assertNull', shouldNotBeNull: 'assertNotNull', shouldBe: 'assertReturnsTrue', shouldNotBe: 'assertReturnsFalse', shouldRespondTo: 'assertRespondsTo' }; var makeAssertion = function(assertion, args, object) { this[assertion].apply(this,(args || []).concat([object])); }; Test.BDDMethods = {}; $H(METHODMAP).each(function(pair) { Test.BDDMethods[pair.key] = function() { var args = $A(arguments); var scope = args.shift(); makeAssertion.apply(scope, [pair.value, args, this]); }; }); [Array.prototype, String.prototype, Number.prototype, Boolean.prototype].each( function(p){ Object.extend(p, Test.BDDMethods) } ); }; Test.context = function(name, spec, log){ Test.setupBDDExtensionMethods(); var compiledSpec = {}; var titles = {}; for(specName in spec) { switch(specName){ case "setup": case "teardown": compiledSpec[specName] = spec[specName]; break; default: var testName = 'test'+specName.gsub(/\s+/,'-').camelize(); var body = spec[specName].toString().split('\n').slice(1); if(/^\{/.test(body[0])) body = body.slice(1); body.pop(); body = body.map(function(statement){ return statement.strip() }); compiledSpec[testName] = body.join('\n'); titles[testName] = specName; } } new Test.Unit.Runner(compiledSpec, { titles: titles, testLog: log || 'testlog', context: name }); };
JavaScript
// script.aculo.us slider.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009 // Copyright (c) 2005-2009 Marty Haught, Thomas Fuchs // // script.aculo.us is freely distributable under the terms of an MIT-style license. // For details, see the script.aculo.us web site: http://script.aculo.us/ if (!Control) var Control = { }; // options: // axis: 'vertical', or 'horizontal' (default) // // callbacks: // onChange(value) // onSlide(value) Control.Slider = Class.create({ initialize: function(handle, track, options) { var slider = this; if (Object.isArray(handle)) { this.handles = handle.collect( function(e) { return $(e) }); } else { this.handles = [$(handle)]; } this.track = $(track); this.options = options || { }; this.axis = this.options.axis || 'horizontal'; this.increment = this.options.increment || 1; this.step = parseInt(this.options.step || '1'); this.range = this.options.range || $R(0,1); this.value = 0; // assure backwards compat this.values = this.handles.map( function() { return 0 }); this.spans = this.options.spans ? this.options.spans.map(function(s){ return $(s) }) : false; this.options.startSpan = $(this.options.startSpan || null); this.options.endSpan = $(this.options.endSpan || null); this.restricted = this.options.restricted || false; this.maximum = this.options.maximum || this.range.end; this.minimum = this.options.minimum || this.range.start; // Will be used to align the handle onto the track, if necessary this.alignX = parseInt(this.options.alignX || '0'); this.alignY = parseInt(this.options.alignY || '0'); this.trackLength = this.maximumOffset() - this.minimumOffset(); this.handleLength = this.isVertical() ? (this.handles[0].offsetHeight != 0 ? this.handles[0].offsetHeight : this.handles[0].style.height.replace(/px$/,"")) : (this.handles[0].offsetWidth != 0 ? this.handles[0].offsetWidth : this.handles[0].style.width.replace(/px$/,"")); this.active = false; this.dragging = false; this.disabled = false; if (this.options.disabled) this.setDisabled(); // Allowed values array this.allowedValues = this.options.values ? this.options.values.sortBy(Prototype.K) : false; if (this.allowedValues) { this.minimum = this.allowedValues.min(); this.maximum = this.allowedValues.max(); } this.eventMouseDown = this.startDrag.bindAsEventListener(this); this.eventMouseUp = this.endDrag.bindAsEventListener(this); this.eventMouseMove = this.update.bindAsEventListener(this); // Initialize handles in reverse (make sure first handle is active) this.handles.each( function(h,i) { i = slider.handles.length-1-i; slider.setValue(parseFloat( (Object.isArray(slider.options.sliderValue) ? slider.options.sliderValue[i] : slider.options.sliderValue) || slider.range.start), i); h.makePositioned().observe("mousedown", slider.eventMouseDown); }); this.track.observe("mousedown", this.eventMouseDown); document.observe("mouseup", this.eventMouseUp); document.observe("mousemove", this.eventMouseMove); this.initialized = true; }, dispose: function() { var slider = this; Event.stopObserving(this.track, "mousedown", this.eventMouseDown); Event.stopObserving(document, "mouseup", this.eventMouseUp); Event.stopObserving(document, "mousemove", this.eventMouseMove); this.handles.each( function(h) { Event.stopObserving(h, "mousedown", slider.eventMouseDown); }); }, setDisabled: function(){ this.disabled = true; }, setEnabled: function(){ this.disabled = false; }, getNearestValue: function(value){ if (this.allowedValues){ if (value >= this.allowedValues.max()) return(this.allowedValues.max()); if (value <= this.allowedValues.min()) return(this.allowedValues.min()); var offset = Math.abs(this.allowedValues[0] - value); var newValue = this.allowedValues[0]; this.allowedValues.each( function(v) { var currentOffset = Math.abs(v - value); if (currentOffset <= offset){ newValue = v; offset = currentOffset; } }); return newValue; } if (value > this.range.end) return this.range.end; if (value < this.range.start) return this.range.start; return value; }, setValue: function(sliderValue, handleIdx){ if (!this.active) { this.activeHandleIdx = handleIdx || 0; this.activeHandle = this.handles[this.activeHandleIdx]; this.updateStyles(); } handleIdx = handleIdx || this.activeHandleIdx || 0; if (this.initialized && this.restricted) { if ((handleIdx>0) && (sliderValue<this.values[handleIdx-1])) sliderValue = this.values[handleIdx-1]; if ((handleIdx < (this.handles.length-1)) && (sliderValue>this.values[handleIdx+1])) sliderValue = this.values[handleIdx+1]; } sliderValue = this.getNearestValue(sliderValue); this.values[handleIdx] = sliderValue; this.value = this.values[0]; // assure backwards compat this.handles[handleIdx].style[this.isVertical() ? 'top' : 'left'] = this.translateToPx(sliderValue); this.drawSpans(); if (!this.dragging || !this.event) this.updateFinished(); }, setValueBy: function(delta, handleIdx) { this.setValue(this.values[handleIdx || this.activeHandleIdx || 0] + delta, handleIdx || this.activeHandleIdx || 0); }, translateToPx: function(value) { return Math.round( ((this.trackLength-this.handleLength)/(this.range.end-this.range.start)) * (value - this.range.start)) + "px"; }, translateToValue: function(offset) { return ((offset/(this.trackLength-this.handleLength) * (this.range.end-this.range.start)) + this.range.start); }, getRange: function(range) { var v = this.values.sortBy(Prototype.K); range = range || 0; return $R(v[range],v[range+1]); }, minimumOffset: function(){ return(this.isVertical() ? this.alignY : this.alignX); }, maximumOffset: function(){ return(this.isVertical() ? (this.track.offsetHeight != 0 ? this.track.offsetHeight : this.track.style.height.replace(/px$/,"")) - this.alignY : (this.track.offsetWidth != 0 ? this.track.offsetWidth : this.track.style.width.replace(/px$/,"")) - this.alignX); }, isVertical: function(){ return (this.axis == 'vertical'); }, drawSpans: function() { var slider = this; if (this.spans) $R(0, this.spans.length-1).each(function(r) { slider.setSpan(slider.spans[r], slider.getRange(r)) }); if (this.options.startSpan) this.setSpan(this.options.startSpan, $R(0, this.values.length>1 ? this.getRange(0).min() : this.value )); if (this.options.endSpan) this.setSpan(this.options.endSpan, $R(this.values.length>1 ? this.getRange(this.spans.length-1).max() : this.value, this.maximum)); }, setSpan: function(span, range) { if (this.isVertical()) { span.style.top = this.translateToPx(range.start); span.style.height = this.translateToPx(range.end - range.start + this.range.start); } else { span.style.left = this.translateToPx(range.start); span.style.width = this.translateToPx(range.end - range.start + this.range.start); } }, updateStyles: function() { this.handles.each( function(h){ Element.removeClassName(h, 'selected') }); Element.addClassName(this.activeHandle, 'selected'); }, startDrag: function(event) { if (Event.isLeftClick(event)) { if (!this.disabled){ this.active = true; var handle = Event.element(event); var pointer = [Event.pointerX(event), Event.pointerY(event)]; var track = handle; if (track==this.track) { var offsets = this.track.cumulativeOffset(); this.event = event; this.setValue(this.translateToValue( (this.isVertical() ? pointer[1]-offsets[1] : pointer[0]-offsets[0])-(this.handleLength/2) )); var offsets = this.activeHandle.cumulativeOffset(); this.offsetX = (pointer[0] - offsets[0]); this.offsetY = (pointer[1] - offsets[1]); } else { // find the handle (prevents issues with Safari) while((this.handles.indexOf(handle) == -1) && handle.parentNode) handle = handle.parentNode; if (this.handles.indexOf(handle)!=-1) { this.activeHandle = handle; this.activeHandleIdx = this.handles.indexOf(this.activeHandle); this.updateStyles(); var offsets = this.activeHandle.cumulativeOffset(); this.offsetX = (pointer[0] - offsets[0]); this.offsetY = (pointer[1] - offsets[1]); } } } Event.stop(event); } }, update: function(event) { if (this.active) { if (!this.dragging) this.dragging = true; this.draw(event); if (Prototype.Browser.WebKit) window.scrollBy(0,0); Event.stop(event); } }, draw: function(event) { var pointer = [Event.pointerX(event), Event.pointerY(event)]; var offsets = this.track.cumulativeOffset(); pointer[0] -= this.offsetX + offsets[0]; pointer[1] -= this.offsetY + offsets[1]; this.event = event; this.setValue(this.translateToValue( this.isVertical() ? pointer[1] : pointer[0] )); if (this.initialized && this.options.onSlide) this.options.onSlide(this.values.length>1 ? this.values : this.value, this); }, endDrag: function(event) { if (this.active && this.dragging) { this.finishDrag(event, true); Event.stop(event); } this.active = false; this.dragging = false; }, finishDrag: function(event, success) { this.active = false; this.dragging = false; this.updateFinished(); }, updateFinished: function() { if (this.initialized && this.options.onChange) this.options.onChange(this.values.length>1 ? this.values : this.value, this); this.event = null; } });
JavaScript
// script.aculo.us scriptaculous.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009 // Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // For details, see the script.aculo.us web site: http://script.aculo.us/ var Scriptaculous = { Version: '1.8.3', require: function(libraryName) { try{ // inserting via DOM fails in Safari 2.0, so brute force approach document.write('<script type="text/javascript" src="'+libraryName+'"><\/script>'); } catch(e) { // for xhtml+xml served content, fall back to DOM methods var script = document.createElement('script'); script.type = 'text/javascript'; script.src = libraryName; document.getElementsByTagName('head')[0].appendChild(script); } }, REQUIRED_PROTOTYPE: '1.6.0.3', load: function() { function convertVersionString(versionString) { var v = versionString.replace(/_.*|\./g, ''); v = parseInt(v + '0'.times(4-v.length)); return versionString.indexOf('_') > -1 ? v-1 : v; } if((typeof Prototype=='undefined') || (typeof Element == 'undefined') || (typeof Element.Methods=='undefined') || (convertVersionString(Prototype.Version) < convertVersionString(Scriptaculous.REQUIRED_PROTOTYPE))) throw("script.aculo.us requires the Prototype JavaScript framework >= " + Scriptaculous.REQUIRED_PROTOTYPE); var js = /scriptaculous\.js(\?.*)?$/; $$('head script[src]').findAll(function(s) { return s.src.match(js); }).each(function(s) { var path = s.src.replace(js, ''), includes = s.src.match(/\?.*load=([a-z,]*)/); // Modified for WordPress to work with enqueue_script if ( includes ) { includes[1].split(',').each( function(include) { Scriptaculous.require(path+include+'.js') }); } }); } }; Scriptaculous.load();
JavaScript
// script.aculo.us sound.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009 // Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) // // Based on code created by Jules Gravinese (http://www.webveteran.com/) // // script.aculo.us is freely distributable under the terms of an MIT-style license. // For details, see the script.aculo.us web site: http://script.aculo.us/ Sound = { tracks: {}, _enabled: true, template: new Template('<embed style="height:0" id="sound_#{track}_#{id}" src="#{url}" loop="false" autostart="true" hidden="true"/>'), enable: function(){ Sound._enabled = true; }, disable: function(){ Sound._enabled = false; }, play: function(url){ if(!Sound._enabled) return; var options = Object.extend({ track: 'global', url: url, replace: false }, arguments[1] || {}); if(options.replace && this.tracks[options.track]) { $R(0, this.tracks[options.track].id).each(function(id){ var sound = $('sound_'+options.track+'_'+id); sound.Stop && sound.Stop(); sound.remove(); }); this.tracks[options.track] = null; } if(!this.tracks[options.track]) this.tracks[options.track] = { id: 0 }; else this.tracks[options.track].id++; options.id = this.tracks[options.track].id; $$('body')[0].insert( Prototype.Browser.IE ? new Element('bgsound',{ id: 'sound_'+options.track+'_'+options.id, src: options.url, loop: 1, autostart: true }) : Sound.template.evaluate(options)); } }; if(Prototype.Browser.Gecko && navigator.userAgent.indexOf("Win") > 0){ if(navigator.plugins && $A(navigator.plugins).detect(function(p){ return p.name.indexOf('QuickTime') != -1 })) Sound.template = new Template('<object id="sound_#{track}_#{id}" width="0" height="0" type="audio/mpeg" data="#{url}"/>'); else if(navigator.plugins && $A(navigator.plugins).detect(function(p){ return p.name.indexOf('Windows Media') != -1 })) Sound.template = new Template('<object id="sound_#{track}_#{id}" type="application/x-mplayer2" data="#{url}"></object>'); else if(navigator.plugins && $A(navigator.plugins).detect(function(p){ return p.name.indexOf('RealPlayer') != -1 })) Sound.template = new Template('<embed type="audio/x-pn-realaudio-plugin" style="height:0" id="sound_#{track}_#{id}" src="#{url}" loop="false" autostart="true" hidden="true"/>'); else Sound.play = function(){}; }
JavaScript
// script.aculo.us scriptaculous.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009 // Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // For details, see the script.aculo.us web site: http://script.aculo.us/ var Scriptaculous = { Version: '1.8.3', require: function(libraryName) { try{ // inserting via DOM fails in Safari 2.0, so brute force approach document.write('<script type="text/javascript" src="'+libraryName+'"><\/script>'); } catch(e) { // for xhtml+xml served content, fall back to DOM methods var script = document.createElement('script'); script.type = 'text/javascript'; script.src = libraryName; document.getElementsByTagName('head')[0].appendChild(script); } }, REQUIRED_PROTOTYPE: '1.6.0.3', load: function() { function convertVersionString(versionString) { var v = versionString.replace(/_.*|\./g, ''); v = parseInt(v + '0'.times(4-v.length)); return versionString.indexOf('_') > -1 ? v-1 : v; } if((typeof Prototype=='undefined') || (typeof Element == 'undefined') || (typeof Element.Methods=='undefined') || (convertVersionString(Prototype.Version) < convertVersionString(Scriptaculous.REQUIRED_PROTOTYPE))) throw("script.aculo.us requires the Prototype JavaScript framework >= " + Scriptaculous.REQUIRED_PROTOTYPE); var js = /scriptaculous\.js(\?.*)?$/; $$('head script[src]').findAll(function(s) { return s.src.match(js); }).each(function(s) { var path = s.src.replace(js, ''), includes = s.src.match(/\?.*load=([a-z,]*)/); (includes ? includes[1] : 'builder,effects,dragdrop,controls,slider,sound').split(',').each( function(include) { Scriptaculous.require(path+include+'.js') }); }); } }; Scriptaculous.load();
JavaScript
// script.aculo.us builder.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009 // Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) // // script.aculo.us is freely distributable under the terms of an MIT-style license. // For details, see the script.aculo.us web site: http://script.aculo.us/ var Builder = { NODEMAP: { AREA: 'map', CAPTION: 'table', COL: 'table', COLGROUP: 'table', LEGEND: 'fieldset', OPTGROUP: 'select', OPTION: 'select', PARAM: 'object', TBODY: 'table', TD: 'table', TFOOT: 'table', TH: 'table', THEAD: 'table', TR: 'table' }, // note: For Firefox < 1.5, OPTION and OPTGROUP tags are currently broken, // due to a Firefox bug node: function(elementName) { elementName = elementName.toUpperCase(); // try innerHTML approach var parentTag = this.NODEMAP[elementName] || 'div'; var parentElement = document.createElement(parentTag); try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707 parentElement.innerHTML = "<" + elementName + "></" + elementName + ">"; } catch(e) {} var element = parentElement.firstChild || null; // see if browser added wrapping tags if(element && (element.tagName.toUpperCase() != elementName)) element = element.getElementsByTagName(elementName)[0]; // fallback to createElement approach if(!element) element = document.createElement(elementName); // abort if nothing could be created if(!element) return; // attributes (or text) if(arguments[1]) if(this._isStringOrNumber(arguments[1]) || (arguments[1] instanceof Array) || arguments[1].tagName) { this._children(element, arguments[1]); } else { var attrs = this._attributes(arguments[1]); if(attrs.length) { try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707 parentElement.innerHTML = "<" +elementName + " " + attrs + "></" + elementName + ">"; } catch(e) {} element = parentElement.firstChild || null; // workaround firefox 1.0.X bug if(!element) { element = document.createElement(elementName); for(attr in arguments[1]) element[attr == 'class' ? 'className' : attr] = arguments[1][attr]; } if(element.tagName.toUpperCase() != elementName) element = parentElement.getElementsByTagName(elementName)[0]; } } // text, or array of children if(arguments[2]) this._children(element, arguments[2]); return $(element); }, _text: function(text) { return document.createTextNode(text); }, ATTR_MAP: { 'className': 'class', 'htmlFor': 'for' }, _attributes: function(attributes) { var attrs = []; for(attribute in attributes) attrs.push((attribute in this.ATTR_MAP ? this.ATTR_MAP[attribute] : attribute) + '="' + attributes[attribute].toString().escapeHTML().gsub(/"/,'&quot;') + '"'); return attrs.join(" "); }, _children: function(element, children) { if(children.tagName) { element.appendChild(children); return; } if(typeof children=='object') { // array can hold nodes and text children.flatten().each( function(e) { if(typeof e=='object') element.appendChild(e); else if(Builder._isStringOrNumber(e)) element.appendChild(Builder._text(e)); }); } else if(Builder._isStringOrNumber(children)) element.appendChild(Builder._text(children)); }, _isStringOrNumber: function(param) { return(typeof param=='string' || typeof param=='number'); }, build: function(html) { var element = this.node('div'); $(element).update(html.strip()); return element.down(); }, dump: function(scope) { if(typeof scope != 'object' && typeof scope != 'function') scope = window; //global scope var tags = ("A ABBR ACRONYM ADDRESS APPLET AREA B BASE BASEFONT BDO BIG BLOCKQUOTE BODY " + "BR BUTTON CAPTION CENTER CITE CODE COL COLGROUP DD DEL DFN DIR DIV DL DT EM FIELDSET " + "FONT FORM FRAME FRAMESET H1 H2 H3 H4 H5 H6 HEAD HR HTML I IFRAME IMG INPUT INS ISINDEX "+ "KBD LABEL LEGEND LI LINK MAP MENU META NOFRAMES NOSCRIPT OBJECT OL OPTGROUP OPTION P "+ "PARAM PRE Q S SAMP SCRIPT SELECT SMALL SPAN STRIKE STRONG STYLE SUB SUP TABLE TBODY TD "+ "TEXTAREA TFOOT TH THEAD TITLE TR TT U UL VAR").split(/\s+/); tags.each( function(tag){ scope[tag] = function() { return Builder.node.apply(Builder, [tag].concat($A(arguments))); }; }); } };
JavaScript
/** * hoverIntent is similar to jQuery's built-in "hover" function except that * instead of firing the onMouseOver event immediately, hoverIntent checks * to see if the user's mouse has slowed down (beneath the sensitivity * threshold) before firing the onMouseOver event. * * hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+ * <http://cherne.net/brian/resources/jquery.hoverIntent.html> * * hoverIntent is currently available for use in all personal or commercial * projects under both MIT and GPL licenses. This means that you can choose * the license that best suits your project, and use it accordingly. * * // basic usage (just like .hover) receives onMouseOver and onMouseOut functions * $("ul li").hoverIntent( showNav , hideNav ); * * // advanced usage receives configuration object only * $("ul li").hoverIntent({ * sensitivity: 7, // number = sensitivity threshold (must be 1 or higher) * interval: 100, // number = milliseconds of polling interval * over: showNav, // function = onMouseOver callback (required) * timeout: 0, // number = milliseconds delay before onMouseOut function call * out: hideNav // function = onMouseOut callback (required) * }); * * @param f onMouseOver function || An object with configuration options * @param g onMouseOut function || Nothing (use configuration options object) * @author Brian Cherne <brian@cherne.net> */ (function($) { $.fn.hoverIntent = function(f,g) { // default configuration options var cfg = { sensitivity: 7, interval: 100, timeout: 0 }; // override configuration options with user supplied object cfg = $.extend(cfg, g ? { over: f, out: g } : f ); // 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).unbind("mousemove",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]); }; // workaround for Mozilla bug: not firing mouseout/mouseleave on absolute positioned elements over textareas and input type="text" var handleHover = function(e) { var t = this; // next two lines copied from jQuery.hover, ignore children onMouseOver/onMouseOut var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget; while ( p && p != this ) { try { p = p.parentNode; } catch(e) { p = this; } } if ( p == this ) { if ( $.browser.mozilla ) { if ( e.type == "mouseout" ) { t.mtout = setTimeout( function(){doHover(e,t);}, 30 ); } else { if (t.mtout) { t.mtout = clearTimeout(t.mtout); } } } return; } else { if (t.mtout) { t.mtout = clearTimeout(t.mtout); } doHover(e,t); } }; // A private function for handling mouse 'hovering' var doHover = function(e,ob) { // copy objects to be passed into t (required for event object to be passed in IE) var ev = jQuery.extend({},e); // cancel hoverIntent timer if it exists if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); } // else e.type == "onmouseover" if (e.type == "mouseover") { // 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).bind("mousemove",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 == "onmouseout" } else { // unbind expensive mousemove event $(ob).unbind("mousemove",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 );} } }; // bind the function to the two event listeners return this.mouseover(handleHover).mouseout(handleHover); }; })(jQuery);
JavaScript
var autosave, autosaveLast = '', autosavePeriodical, autosaveOldMessage = '', autosaveDelayPreview = false, notSaved = true, blockSave = false, fullscreen; jQuery(document).ready( function($) { var dotabkey = true; autosaveLast = $('#post #title').val() + $('#post #content').val(); autosavePeriodical = $.schedule({time: autosaveL10n.autosaveInterval * 1000, func: function() { autosave(); }, repeat: true, protect: true}); //Disable autosave after the form has been submitted $("#post").submit(function() { $.cancel(autosavePeriodical); }); $('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' ) $('#ajax-loading').css('visibility', 'visible'); else $('#draft-ajax-loading').css('visibility', 'visible'); }); window.onbeforeunload = function(){ var mce = typeof(tinyMCE) != 'undefined' ? tinyMCE.activeEditor : false, title, content; if ( mce && !mce.isHidden() ) { if ( mce.isDirty() ) return autosaveL10n.saveAlert; } else { if ( fullscreen && fullscreen.settings.visible ) { title = $('#wp-fullscreen-title').val(); content = $("#wp_mce_fullscreen").val(); } else { title = $('#post #title').val(); content = $('#post #content').val(); } if ( ( title || content ) && title + content != autosaveLast ) return autosaveL10n.saveAlert; } }; // 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', ''); $('input#wp-preview').val(''); } // This code is meant to allow tabbing from Title to Post if tinyMCE is defined. if ( typeof tinyMCE != 'undefined' ) { $('#title')[$.browser.opera ? 'keypress' : 'keydown'](function (e) { if ( e.which == 9 && !e.shiftKey && !e.controlKey && !e.altKey ) { if ( ($('#auto_draft').val() == '1') && ($("#title").val().length > 0) ) { autosave(); } if ( tinyMCE.activeEditor && ! tinyMCE.activeEditor.isHidden() && dotabkey ) { e.preventDefault(); dotabkey = false; tinyMCE.activeEditor.focus(); return false; } } }); } // autosave new posts after a title is typed but not if Publish or Save Draft is clicked if ( '1' == $('#auto_draft').val() ) { $('#title').blur( function() { if ( !this.value || $('#auto_draft').val() != '1' ) return; delayed_autosave(); }); } }); function autosave_parse_response(response) { var res = wpAjax.parseAjaxResponse(response, 'autosave'), message = '', postID, sup; if ( res && res.responses && res.responses.length ) { message = res.responses[0].data; // The saved message or error. // someone else is editing: disable autosave, set errors if ( res.responses[0].supplemental ) { sup = res.responses[0].supplemental; if ( 'disable' == sup['disable_autosave'] ) { autosave = function() {}; res = { errors: true }; } if ( sup['alert'] ) { jQuery('#autosave-alert').remove(); jQuery('#titlediv').after('<div id="autosave-alert" class="error below-h2"><p>' + sup['alert'] + '</p></div>'); } jQuery.each(sup, function(selector, value) { if ( selector.match(/^replace-/) ) { jQuery('#'+selector.replace('replace-', '')).val(value); } }); } // if no errors: add slug UI if ( !res.errors ) { postID = parseInt( res.responses[0].id, 10 ); if ( !isNaN(postID) && postID > 0 ) { autosave_update_slug(postID); } } } if ( message ) { // update autosave message jQuery('.autosave-message').html(message); } else if ( autosaveOldMessage && res ) { jQuery('.autosave-message').html( autosaveOldMessage ); } return res; } // called when autosaving pre-existing post function autosave_saved(response) { blockSave = false; autosave_parse_response(response); // parse the ajax response autosave_enable_buttons(); // re-enable disabled form buttons } // called when autosaving new post function autosave_saved_new(response) { blockSave = false; var res = autosave_parse_response(response), postID; if ( res && res.responses.length && !res.errors ) { // An ID is sent only for real auto-saves, not for autosave=0 "keepalive" saves postID = parseInt( res.responses[0].id, 10 ); if ( !isNaN(postID) && postID > 0 ) { notSaved = false; jQuery('#auto_draft').val('0'); // No longer an auto-draft } autosave_enable_buttons(); if ( autosaveDelayPreview ) { autosaveDelayPreview = false; doPreview(); } } else { autosave_enable_buttons(); // re-enable disabled form buttons } } function autosave_update_slug(post_id) { // create slug area only if not already there if ( 'undefined' != makeSlugeditClickable && jQuery.isFunction(makeSlugeditClickable) && !jQuery('#edit-slug-box > *').size() ) { jQuery.post( ajaxurl, { action: 'sample-permalink', post_id: post_id, new_title: fullscreen && fullscreen.settings.visible ? jQuery('#wp-fullscreen-title').val() : jQuery('#title').val(), samplepermalinknonce: jQuery('#samplepermalinknonce').val() }, function(data) { if ( data !== '-1' ) { jQuery('#edit-slug-box').html(data); makeSlugeditClickable(); } } ); } } function autosave_loading() { jQuery('.autosave-message').html(autosaveL10n.savingText); } function autosave_enable_buttons() { // delay that a bit to avoid some rare collisions while the DOM is being updated. setTimeout(function(){ jQuery(':button, :submit', '#submitpost').removeAttr('disabled'); jQuery('.ajax-loading').css('visibility', 'hidden'); }, 500); } function autosave_disable_buttons() { jQuery(':button, :submit', '#submitpost').prop('disabled', true); // Re-enable 5 sec later. Just gives autosave a head start to avoid collisions. setTimeout(autosave_enable_buttons, 5000); } function delayed_autosave() { setTimeout(function(){ if ( blockSave ) return; autosave(); }, 200); } autosave = function() { // (bool) is rich editor enabled and active blockSave = true; var rich = (typeof tinyMCE != "undefined") && tinyMCE.activeEditor && !tinyMCE.activeEditor.isHidden(), post_data, doAutoSave, ed, origStatus, successCallback; autosave_disable_buttons(); post_data = { action: "autosave", post_ID: jQuery("#post_ID").val() || 0, autosavenonce: jQuery('#autosavenonce').val(), post_type: jQuery('#post_type').val() || "", autosave: 1 }; jQuery('.tags-input').each( function() { post_data[this.name] = this.value; } ); // We always send the ajax request in order to keep the post lock fresh. // This (bool) tells whether or not to write the post to the DB during the ajax request. doAutoSave = true; // No autosave while thickbox is open (media buttons) if ( jQuery("#TB_window").css('display') == 'block' ) doAutoSave = false; /* Gotta do this up here so we can check the length when tinyMCE is in use */ if ( rich && doAutoSave ) { ed = tinyMCE.activeEditor; // Don't run while the TinyMCE spellcheck is on. It resets all found words. if ( ed.plugins.spellchecker && ed.plugins.spellchecker.active ) { doAutoSave = false; } else { if ( 'mce_fullscreen' == ed.id || 'wp_mce_fullscreen' == ed.id ) tinyMCE.get('content').setContent(ed.getContent({format : 'raw'}), {format : 'raw'}); tinyMCE.triggerSave(); } } if ( fullscreen && fullscreen.settings.visible ) { post_data["post_title"] = jQuery('#wp-fullscreen-title').val(); post_data["content"] = jQuery("#wp_mce_fullscreen").val(); } else { post_data["post_title"] = jQuery("#title").val() post_data["content"] = jQuery("#content").val(); } if ( jQuery('#post_name').val() ) post_data["post_name"] = jQuery('#post_name').val(); // Nothing to save or no change. if ( ( post_data["post_title"].length == 0 && post_data["content"].length == 0 ) || post_data["post_title"] + post_data["content"] == autosaveLast ) { doAutoSave = false; } origStatus = jQuery('#original_post_status').val(); goodcats = ([]); jQuery("[name='post_category[]']:checked").each( function(i) { goodcats.push(this.value); } ); post_data["catslist"] = goodcats.join(","); if ( jQuery("#comment_status").prop("checked") ) post_data["comment_status"] = 'open'; if ( jQuery("#ping_status").prop("checked") ) post_data["ping_status"] = 'open'; if ( jQuery("#excerpt").size() ) post_data["excerpt"] = jQuery("#excerpt").val(); if ( jQuery("#post_author").size() ) post_data["post_author"] = jQuery("#post_author").val(); if ( jQuery("#parent_id").val() ) post_data["parent_id"] = jQuery("#parent_id").val(); post_data["user_ID"] = jQuery("#user-id").val(); if ( jQuery('#auto_draft').val() == '1' ) post_data["auto_draft"] = '1'; if ( doAutoSave ) { autosaveLast = post_data["post_title"] + post_data["content"]; jQuery(document).triggerHandler('wpcountwords', [ post_data["content"] ]); } else { post_data['autosave'] = 0; } if ( post_data["auto_draft"] == '1' ) { successCallback = autosave_saved_new; // new post } else { successCallback = autosave_saved; // pre-existing post } autosaveOldMessage = jQuery('#autosave').html(); jQuery.ajax({ data: post_data, beforeSend: doAutoSave ? autosave_loading : null, type: "POST", url: ajaxurl, success: successCallback }); }
JavaScript
/* http://www.JSON.org/json2.js 2011-02-23 Public Domain. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. See http://www.JSON.org/js.html This code should be minified before deployment. See http://javascript.crockford.com/jsmin.html USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO NOT CONTROL. This file creates a global JSON object containing two methods: stringify and parse. JSON.stringify(value, replacer, space) value any JavaScript value, usually an object or array. replacer an optional parameter that determines how object values are stringified for objects. It can be a function or an array of strings. space an optional parameter that specifies the indentation of nested structures. If it is omitted, the text will be packed without extra whitespace. If it is a number, it will specify the number of spaces to indent at each level. If it is a string (such as '\t' or '&nbsp;'), it contains the characters used to indent at each level. This method produces a JSON text from a JavaScript value. When an object value is found, if the object contains a toJSON method, its toJSON method will be called and the result will be stringified. A toJSON method does not serialize: it returns the value represented by the name/value pair that should be serialized, or undefined if nothing should be serialized. The toJSON method will be passed the key associated with the value, and this will be bound to the value For example, this would serialize Dates as ISO strings. Date.prototype.toJSON = function (key) { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } return this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z'; }; You can provide an optional replacer method. It will be passed the key and value of each member, with this bound to the containing object. The value that is returned from your method will be serialized. If your method returns undefined, then the member will be excluded from the serialization. If the replacer parameter is an array of strings, then it will be used to select the members to be serialized. It filters the results such that only members with keys listed in the replacer array are stringified. Values that do not have JSON representations, such as undefined or functions, will not be serialized. Such values in objects will be dropped; in arrays they will be replaced with null. You can use a replacer function to replace those with JSON values. JSON.stringify(undefined) returns undefined. The optional space parameter produces a stringification of the value that is filled with line breaks and indentation to make it easier to read. If the space parameter is a non-empty string, then that string will be used for indentation. If the space parameter is a number, then the indentation will be that many spaces. Example: text = JSON.stringify(['e', {pluribus: 'unum'}]); // text is '["e",{"pluribus":"unum"}]' text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' text = JSON.stringify([new Date()], function (key, value) { return this[key] instanceof Date ? 'Date(' + this[key] + ')' : value; }); // text is '["Date(---current time---)"]' JSON.parse(text, reviver) This method parses a JSON text to produce an object or array. It can throw a SyntaxError exception. The optional reviver parameter is a function that can filter and transform the results. It receives each of the keys and values, and its return value is used instead of the original value. If it returns what it received, then the structure is not modified. If it returns undefined then the member is deleted. Example: // Parse the text. Values that look like ISO date strings will // be converted to Date objects. myData = JSON.parse(text, function (key, value) { var a; if (typeof value === 'string') { a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); if (a) { return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); } } return value; }); myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { var d; if (typeof value === 'string' && value.slice(0, 5) === 'Date(' && value.slice(-1) === ')') { d = new Date(value.slice(5, -1)); if (d) { return d; } } return value; }); This is a reference implementation. You are free to copy, modify, or redistribute. */ /*jslint evil: true, strict: false, regexp: false */ /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length, parse, prototype, push, replace, slice, stringify, test, toJSON, toString, valueOf */ // Create a JSON object only if one does not already exist. We create the // methods in a closure to avoid creating global variables. var JSON; if (!JSON) { JSON = {}; } (function () { "use strict"; function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } if (typeof Date.prototype.toJSON !== 'function') { Date.prototype.toJSON = function (key) { return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function (key) { return this.valueOf(); }; } var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }, rep; function quote(string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { // Produce a string from holder[key]. var i, // The loop counter. k, // The member key. v, // The member value. length, mind = gap, partial, value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder, key, value); } // What happens next depends on the value's type. switch (typeof value) { case 'string': return quote(value); case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value); // If the type is 'object', we might be dealing with an object or an array or // null. case 'object': // Due to a specification blunder in ECMAScript, typeof null is 'object', // so watch out for that case. if (!value) { return 'null'; } // Make an array to hold the partial results of stringifying this object value. gap += indent; partial = []; // Is the value an array? if (Object.prototype.toString.apply(value) === '[object Array]') { // The value is an array. Stringify every element. Use null as a placeholder // for non-JSON values. length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } // Join all of the elements together, separated with commas, and wrap them in // brackets. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } // If the replacer is an array, use it to select the members to be stringified. if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { if (typeof rep[i] === 'string') { k = rep[i]; v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { // Otherwise, iterate through all of the keys in the object. for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } // Join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } // If the JSON object does not yet have a stringify method, give it one. if (typeof JSON.stringify !== 'function') { JSON.stringify = function (value, replacer, space) { // The stringify method takes a value and an optional replacer, and an optional // space parameter, and returns a JSON text. The replacer can be a function // that can replace values, or an array of strings that will select the keys. // A default replacer method can be provided. Use of the space parameter can // produce text that is more easily readable. var i; gap = ''; indent = ''; // If the space parameter is a number, make an indent string containing that // many spaces. if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } // If the space parameter is a string, it will be used as the indent string. } else if (typeof space === 'string') { indent = space; } // If there is a replacer, it must be a function or an array. // Otherwise, throw an error. rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return str('', {'': value}); }; } // If the JSON object does not yet have a parse method, give it one. if (typeof JSON.parse !== 'function') { JSON.parse = function (text, reviver) { // The parse method takes a text and an optional reviver function, and returns // a JavaScript value if the text is a valid JSON text. var j; function walk(holder, key) { // The walk method is used to recursively walk the resulting structure so // that modifications can be made. var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } // Parsing happens in four stages. In the first stage, we replace certain // Unicode characters with escape sequences. JavaScript handles many characters // incorrectly, either silently deleting them, or treating them as line endings. text = String(text); cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } // In the second stage, we run the text against regular expressions that look // for non-JSON patterns. We are especially concerned with '()' and 'new' // because they can cause invocation, and '=' because it can cause mutation. // But just to be safe, we want to reject all unexpected forms. // We split the second stage into 4 regexp operations in order to work around // crippling inefficiencies in IE's and Safari's regexp engines. First we // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we // replace all simple value tokens with ']' characters. Third, we delete all // open brackets that follow a colon or comma or that begin the text. Finally, // we look to see that the remaining characters are only whitespace or ']' or // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. if (/^[\],:{}\s]*$/ .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { // In the third stage we use the eval function to compile the text into a // JavaScript structure. The '{' operator is subject to a syntactic ambiguity // in JavaScript: it can begin a block or an object literal. We wrap the text // in parens to eliminate the ambiguity. j = eval('(' + text + ')'); // In the optional fourth stage, we recursively walk the new structure, passing // each name/value pair to a reviver function for possible transformation. return typeof reviver === 'function' ? walk({'': j}, '') : j; } // If the text is not JSON parseable, then a SyntaxError is thrown. throw new SyntaxError('JSON.parse'); }; } }());
JavaScript
/*! * jQuery Form Plugin * version: 2.73 (03-MAY-2011) * @requires jQuery v1.3.2 or later * * Examples and documentation at: http://malsup.com/jquery/form/ * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html */ ;(function($) { /* Usage Note: ----------- Do not use both ajaxSubmit and ajaxForm on the same form. These functions are intended to be exclusive. Use ajaxSubmit if you want to bind your own submit handler to the form. For example, $(document).ready(function() { $('#myForm').bind('submit', function(e) { e.preventDefault(); // <-- important $(this).ajaxSubmit({ target: '#output' }); }); }); Use ajaxForm when you want the plugin to manage all the event binding for you. For example, $(document).ready(function() { $('#myForm').ajaxForm({ target: '#output' }); }); When using ajaxForm, the ajaxSubmit function will be invoked for you at the appropriate time. */ /** * ajaxSubmit() provides a mechanism for immediately submitting * an HTML form using AJAX. */ $.fn.ajaxSubmit = function(options) { // fast fail if nothing selected (http://dev.jquery.com/ticket/2752) if (!this.length) { log('ajaxSubmit: skipping submit process - no element selected'); return this; } if (typeof options == 'function') { options = { success: options }; } var action = this.attr('action'); var url = (typeof action === 'string') ? $.trim(action) : ''; if (url) { // clean url (don't include hash vaue) url = (url.match(/^([^#]+)/)||[])[1]; } url = url || window.location.href || ''; options = $.extend(true, { url: url, success: $.ajaxSettings.success, type: this[0].getAttribute('method') || 'GET', // IE7 massage (see issue 57) iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank' }, options); // hook for manipulating the form data before it is extracted; // convenient for use with rich editors like tinyMCE or FCKEditor var veto = {}; this.trigger('form-pre-serialize', [this, options, veto]); if (veto.veto) { log('ajaxSubmit: submit vetoed via form-pre-serialize trigger'); return this; } // provide opportunity to alter form data before it is serialized if (options.beforeSerialize && options.beforeSerialize(this, options) === false) { log('ajaxSubmit: submit aborted via beforeSerialize callback'); return this; } var n,v,a = this.formToArray(options.semantic); if (options.data) { options.extraData = options.data; for (n in options.data) { if(options.data[n] instanceof Array) { for (var k in options.data[n]) { a.push( { name: n, value: options.data[n][k] } ); } } else { v = options.data[n]; v = $.isFunction(v) ? v() : v; // if value is fn, invoke it a.push( { name: n, value: v } ); } } } // give pre-submit callback an opportunity to abort the submit if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) { log('ajaxSubmit: submit aborted via beforeSubmit callback'); return this; } // fire vetoable 'validate' event this.trigger('form-submit-validate', [a, this, options, veto]); if (veto.veto) { log('ajaxSubmit: submit vetoed via form-submit-validate trigger'); return this; } var q = $.param(a); if (options.type.toUpperCase() == 'GET') { options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q; options.data = null; // data is null for 'get' } else { options.data = q; // data is the query string for 'post' } var $form = this, callbacks = []; if (options.resetForm) { callbacks.push(function() { $form.resetForm(); }); } if (options.clearForm) { callbacks.push(function() { $form.clearForm(); }); } // perform a load on the target only if dataType is not provided if (!options.dataType && options.target) { var oldSuccess = options.success || function(){}; callbacks.push(function(data) { var fn = options.replaceTarget ? 'replaceWith' : 'html'; $(options.target)[fn](data).each(oldSuccess, arguments); }); } else if (options.success) { callbacks.push(options.success); } options.success = function(data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg var context = options.context || options; // jQuery 1.4+ supports scope context for (var i=0, max=callbacks.length; i < max; i++) { callbacks[i].apply(context, [data, status, xhr || $form, $form]); } }; // are there files to upload? var fileInputs = $('input:file', this).length > 0; var mp = 'multipart/form-data'; var multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp); // options.iframe allows user to force iframe mode // 06-NOV-09: now defaulting to iframe mode if file input is detected if (options.iframe !== false && (fileInputs || options.iframe || multipart)) { // hack to fix Safari hang (thanks to Tim Molendijk for this) // see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d if (options.closeKeepAlive) { $.get(options.closeKeepAlive, fileUpload); } else { fileUpload(); } } else { $.ajax(options); } // fire 'notify' event this.trigger('form-submit-notify', [this, options]); return this; // private function for handling file uploads (hat tip to YAHOO!) function fileUpload() { var form = $form[0]; if ($(':input[name=submit],:input[id=submit]', form).length) { // if there is an input with a name or id of 'submit' then we won't be // able to invoke the submit fn on the form (at least not x-browser) alert('Error: Form elements must not have name or id of "submit".'); return; } var s = $.extend(true, {}, $.ajaxSettings, options); s.context = s.context || s; var id = 'jqFormIO' + (new Date().getTime()), fn = '_'+id; var $io = $('<iframe id="' + id + '" name="' + id + '" src="'+ s.iframeSrc +'" />'); var io = $io[0]; $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' }); var xhr = { // mock object aborted: 0, responseText: null, responseXML: null, status: 0, statusText: 'n/a', getAllResponseHeaders: function() {}, getResponseHeader: function() {}, setRequestHeader: function() {}, abort: function(status) { var e = (status === 'timeout' ? 'timeout' : 'aborted'); log('aborting upload... ' + e); this.aborted = 1; $io.attr('src', s.iframeSrc); // abort op in progress xhr.error = e; s.error && s.error.call(s.context, xhr, e, e); g && $.event.trigger("ajaxError", [xhr, s, e]); s.complete && s.complete.call(s.context, xhr, e); } }; var g = s.global; // trigger ajax global events so that activity/block indicators work like normal if (g && ! $.active++) { $.event.trigger("ajaxStart"); } if (g) { $.event.trigger("ajaxSend", [xhr, s]); } if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) { if (s.global) { $.active--; } return; } if (xhr.aborted) { return; } var timedOut = 0, timeoutHandle; // add submitting element to data if we know it var sub = form.clk; if (sub) { var n = sub.name; if (n && !sub.disabled) { s.extraData = s.extraData || {}; s.extraData[n] = sub.value; if (sub.type == "image") { s.extraData[n+'.x'] = form.clk_x; s.extraData[n+'.y'] = form.clk_y; } } } // take a breath so that pending repaints get some cpu time before the upload starts function doSubmit() { // make sure form attrs are set var t = $form.attr('target'), a = $form.attr('action'); // update form attrs in IE friendly way form.setAttribute('target',id); if (form.getAttribute('method') != 'POST') { form.setAttribute('method', 'POST'); } if (form.getAttribute('action') != s.url) { form.setAttribute('action', s.url); } // ie borks in some cases when setting encoding if (! s.skipEncodingOverride) { $form.attr({ encoding: 'multipart/form-data', enctype: 'multipart/form-data' }); } // support timout if (s.timeout) { timeoutHandle = setTimeout(function() { timedOut = true; cb(true); }, s.timeout); } // add "extra" data to form if provided in options var extraInputs = []; try { if (s.extraData) { for (var n in s.extraData) { extraInputs.push( $('<input type="hidden" name="'+n+'" value="'+s.extraData[n]+'" />') .appendTo(form)[0]); } } // add iframe to doc and submit the form $io.appendTo('body'); io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false); form.submit(); } finally { // reset attrs and remove "extra" input elements form.setAttribute('action',a); if(t) { form.setAttribute('target', t); } else { $form.removeAttr('target'); } $(extraInputs).remove(); } } if (s.forceSync) { doSubmit(); } else { setTimeout(doSubmit, 10); // this lets dom updates render } var data, doc, domCheckCount = 50, callbackProcessed; function cb(e) { if (xhr.aborted || callbackProcessed) { return; } if (e === true && xhr) { xhr.abort('timeout'); return; } var doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document; if (!doc || doc.location.href == s.iframeSrc) { // response not received yet if (!timedOut) return; } io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false); var ok = true; try { if (timedOut) { throw 'timeout'; } var isXml = s.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc); log('isXml='+isXml); if (!isXml && window.opera && (doc.body == null || doc.body.innerHTML == '')) { if (--domCheckCount) { // in some browsers (Opera) the iframe DOM is not always traversable when // the onload callback fires, so we loop a bit to accommodate log('requeing onLoad callback, DOM not available'); setTimeout(cb, 250); return; } // let this fall through because server response could be an empty document //log('Could not access iframe DOM after mutiple tries.'); //throw 'DOMException: not available'; } //log('response detected'); xhr.responseText = doc.body ? doc.body.innerHTML : doc.documentElement ? doc.documentElement.innerHTML : null; xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc; if (isXml) s.dataType = 'xml'; xhr.getResponseHeader = function(header){ var headers = {'content-type': s.dataType}; return headers[header]; }; var scr = /(json|script|text)/.test(s.dataType); if (scr || s.textarea) { // see if user embedded response in textarea var ta = doc.getElementsByTagName('textarea')[0]; if (ta) { xhr.responseText = ta.value; } else if (scr) { // account for browsers injecting pre around json response var pre = doc.getElementsByTagName('pre')[0]; var b = doc.getElementsByTagName('body')[0]; if (pre) { xhr.responseText = pre.textContent; } else if (b) { xhr.responseText = b.innerHTML; } } } else if (s.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) { xhr.responseXML = toXml(xhr.responseText); } data = httpData(xhr, s.dataType, s); } catch(e){ log('error caught:',e); ok = false; xhr.error = e; s.error && s.error.call(s.context, xhr, 'error', e); g && $.event.trigger("ajaxError", [xhr, s, e]); } if (xhr.aborted) { log('upload aborted'); ok = false; } // ordering of these callbacks/triggers is odd, but that's how $.ajax does it if (ok) { s.success && s.success.call(s.context, data, 'success', xhr); g && $.event.trigger("ajaxSuccess", [xhr, s]); } g && $.event.trigger("ajaxComplete", [xhr, s]); if (g && ! --$.active) { $.event.trigger("ajaxStop"); } s.complete && s.complete.call(s.context, xhr, ok ? 'success' : 'error'); callbackProcessed = true; if (s.timeout) clearTimeout(timeoutHandle); // clean up setTimeout(function() { $io.removeData('form-plugin-onload'); $io.remove(); xhr.responseXML = null; }, 100); } var toXml = $.parseXML || function(s, doc) { // use parseXML if available (jQuery 1.5+) if (window.ActiveXObject) { doc = new ActiveXObject('Microsoft.XMLDOM'); doc.async = 'false'; doc.loadXML(s); } else { doc = (new DOMParser()).parseFromString(s, 'text/xml'); } return (doc && doc.documentElement && doc.documentElement.nodeName != 'parsererror') ? doc : null; }; var parseJSON = $.parseJSON || function(s) { return window['eval']('(' + s + ')'); }; var httpData = function( xhr, type, s ) { // mostly lifted from jq1.4.4 var ct = xhr.getResponseHeader('content-type') || '', xml = type === 'xml' || !type && ct.indexOf('xml') >= 0, data = xml ? xhr.responseXML : xhr.responseText; if (xml && data.documentElement.nodeName === 'parsererror') { $.error && $.error('parsererror'); } if (s && s.dataFilter) { data = s.dataFilter(data, type); } if (typeof data === 'string') { if (type === 'json' || !type && ct.indexOf('json') >= 0) { data = parseJSON(data); } else if (type === "script" || !type && ct.indexOf("javascript") >= 0) { $.globalEval(data); } } return data; }; } }; /** * ajaxForm() provides a mechanism for fully automating form submission. * * The advantages of using this method instead of ajaxSubmit() are: * * 1: This method will include coordinates for <input type="image" /> elements (if the element * is used to submit the form). * 2. This method will include the submit element's name/value data (for the element that was * used to submit the form). * 3. This method binds the submit() method to the form for you. * * The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely * passes the options argument along after properly binding events for submit elements and * the form itself. */ $.fn.ajaxForm = function(options) { // in jQuery 1.3+ we can fix mistakes with the ready state if (this.length === 0) { var o = { s: this.selector, c: this.context }; if (!$.isReady && o.s) { log('DOM not ready, queuing ajaxForm'); $(function() { $(o.s,o.c).ajaxForm(options); }); return this; } // is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready() log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)')); return this; } return this.ajaxFormUnbind().bind('submit.form-plugin', function(e) { if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed e.preventDefault(); $(this).ajaxSubmit(options); } }).bind('click.form-plugin', function(e) { var target = e.target; var $el = $(target); if (!($el.is(":submit,input:image"))) { // is this a child element of the submit el? (ex: a span within a button) var t = $el.closest(':submit'); if (t.length == 0) { return; } target = t[0]; } var form = this; form.clk = target; if (target.type == 'image') { if (e.offsetX != undefined) { form.clk_x = e.offsetX; form.clk_y = e.offsetY; } else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin var offset = $el.offset(); form.clk_x = e.pageX - offset.left; form.clk_y = e.pageY - offset.top; } else { form.clk_x = e.pageX - target.offsetLeft; form.clk_y = e.pageY - target.offsetTop; } } // clear form vars setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100); }); }; // ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm $.fn.ajaxFormUnbind = function() { return this.unbind('submit.form-plugin click.form-plugin'); }; /** * formToArray() gathers form element data into an array of objects that can * be passed to any of the following ajax functions: $.get, $.post, or load. * Each object in the array has both a 'name' and 'value' property. An example of * an array for a simple login form might be: * * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ] * * It is this array that is passed to pre-submit callback functions provided to the * ajaxSubmit() and ajaxForm() methods. */ $.fn.formToArray = function(semantic) { var a = []; if (this.length === 0) { return a; } var form = this[0]; var els = semantic ? form.getElementsByTagName('*') : form.elements; if (!els) { return a; } var i,j,n,v,el,max,jmax; for(i=0, max=els.length; i < max; i++) { el = els[i]; n = el.name; if (!n) { continue; } if (semantic && form.clk && el.type == "image") { // handle image inputs on the fly when semantic == true if(!el.disabled && form.clk == el) { a.push({name: n, value: $(el).val()}); a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y}); } continue; } v = $.fieldValue(el, true); if (v && v.constructor == Array) { for(j=0, jmax=v.length; j < jmax; j++) { a.push({name: n, value: v[j]}); } } else if (v !== null && typeof v != 'undefined') { a.push({name: n, value: v}); } } if (!semantic && form.clk) { // input type=='image' are not found in elements array! handle it here var $input = $(form.clk), input = $input[0]; n = input.name; if (n && !input.disabled && input.type == 'image') { a.push({name: n, value: $input.val()}); a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y}); } } return a; }; /** * Serializes form data into a 'submittable' string. This method will return a string * in the format: name1=value1&amp;name2=value2 */ $.fn.formSerialize = function(semantic) { //hand off to jQuery.param for proper encoding return $.param(this.formToArray(semantic)); }; /** * Serializes all field elements in the jQuery object into a query string. * This method will return a string in the format: name1=value1&amp;name2=value2 */ $.fn.fieldSerialize = function(successful) { var a = []; this.each(function() { var n = this.name; if (!n) { return; } var v = $.fieldValue(this, successful); if (v && v.constructor == Array) { for (var i=0,max=v.length; i < max; i++) { a.push({name: n, value: v[i]}); } } else if (v !== null && typeof v != 'undefined') { a.push({name: this.name, value: v}); } }); //hand off to jQuery.param for proper encoding return $.param(a); }; /** * Returns the value(s) of the element in the matched set. For example, consider the following form: * * <form><fieldset> * <input name="A" type="text" /> * <input name="A" type="text" /> * <input name="B" type="checkbox" value="B1" /> * <input name="B" type="checkbox" value="B2"/> * <input name="C" type="radio" value="C1" /> * <input name="C" type="radio" value="C2" /> * </fieldset></form> * * var v = $(':text').fieldValue(); * // if no values are entered into the text inputs * v == ['',''] * // if values entered into the text inputs are 'foo' and 'bar' * v == ['foo','bar'] * * var v = $(':checkbox').fieldValue(); * // if neither checkbox is checked * v === undefined * // if both checkboxes are checked * v == ['B1', 'B2'] * * var v = $(':radio').fieldValue(); * // if neither radio is checked * v === undefined * // if first radio is checked * v == ['C1'] * * The successful argument controls whether or not the field element must be 'successful' * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls). * The default value of the successful argument is true. If this value is false the value(s) * for each element is returned. * * Note: This method *always* returns an array. If no valid value can be determined the * array will be empty, otherwise it will contain one or more values. */ $.fn.fieldValue = function(successful) { for (var val=[], i=0, max=this.length; i < max; i++) { var el = this[i]; var v = $.fieldValue(el, successful); if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) { continue; } v.constructor == Array ? $.merge(val, v) : val.push(v); } return val; }; /** * Returns the value of the field element. */ $.fieldValue = function(el, successful) { var n = el.name, t = el.type, tag = el.tagName.toLowerCase(); if (successful === undefined) { successful = true; } if (successful && (!n || el.disabled || t == 'reset' || t == 'button' || (t == 'checkbox' || t == 'radio') && !el.checked || (t == 'submit' || t == 'image') && el.form && el.form.clk != el || tag == 'select' && el.selectedIndex == -1)) { return null; } if (tag == 'select') { var index = el.selectedIndex; if (index < 0) { return null; } var a = [], ops = el.options; var one = (t == 'select-one'); var max = (one ? index+1 : ops.length); for(var i=(one ? index : 0); i < max; i++) { var op = ops[i]; if (op.selected) { var v = op.value; if (!v) { // extra pain for IE... v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value; } if (one) { return v; } a.push(v); } } return a; } return $(el).val(); }; /** * Clears the form data. Takes the following actions on the form's input fields: * - input text fields will have their 'value' property set to the empty string * - select elements will have their 'selectedIndex' property set to -1 * - checkbox and radio inputs will have their 'checked' property set to false * - inputs of type submit, button, reset, and hidden will *not* be effected * - button elements will *not* be effected */ $.fn.clearForm = function() { return this.each(function() { $('input,select,textarea', this).clearFields(); }); }; /** * Clears the selected form elements. */ $.fn.clearFields = $.fn.clearInputs = function() { return this.each(function() { var t = this.type, tag = this.tagName.toLowerCase(); if (t == 'text' || t == 'password' || tag == 'textarea') { this.value = ''; } else if (t == 'checkbox' || t == 'radio') { this.checked = false; } else if (tag == 'select') { this.selectedIndex = -1; } }); }; /** * Resets the form data. Causes all form elements to be reset to their original value. */ $.fn.resetForm = function() { return this.each(function() { // guard against an input with the name of 'reset' // note that IE reports the reset function as an 'object' if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) { this.reset(); } }); }; /** * Enables or disables any matching elements. */ $.fn.enable = function(b) { if (b === undefined) { b = true; } return this.each(function() { this.disabled = !b; }); }; /** * Checks/unchecks any matching checkboxes or radio buttons and * selects/deselects and matching option elements. */ $.fn.selected = function(select) { if (select === undefined) { select = true; } return this.each(function() { var t = this.type; if (t == 'checkbox' || t == 'radio') { this.checked = select; } else if (this.tagName.toLowerCase() == 'option') { var $sel = $(this).parent('select'); if (select && $sel[0] && $sel[0].type == 'select-one') { // deselect all other options $sel.find('option').selected(false); } this.selected = select; } }); }; // helper fn for console logging // set $.fn.ajaxSubmit.debug to true to enable debug logging function log() { if ($.fn.ajaxSubmit.debug) { var msg = '[jquery.form] ' + Array.prototype.join.call(arguments,''); if (window.console && window.console.log) { window.console.log(msg); } else if (window.opera && window.opera.postError) { window.opera.postError(msg); } } }; })(jQuery);
JavaScript
/****************************************************************************************************************************** * @ Original idea by by Binny V A, Original version: 2.00.A * @ http://www.openjs.com/scripts/events/keyboard_shortcuts/ * @ Original License : BSD * @ jQuery Plugin by Tzury Bar Yochay mail: tzury.by@gmail.com blog: evalinux.wordpress.com face: facebook.com/profile.php?id=513676303 (c) Copyrights 2007 * @ jQuery Plugin version Beta (0.0.2) * @ License: jQuery-License. TODO: add queue support (as in gmail) e.g. 'x' then 'y', etc. add mouse + mouse wheel events. USAGE: $.hotkeys.add('Ctrl+c', function(){ alert('copy anyone?');}); $.hotkeys.add('Ctrl+c', {target:'div#editor', type:'keyup', propagate: true},function(){ alert('copy anyone?');});> $.hotkeys.remove('Ctrl+c'); $.hotkeys.remove('Ctrl+c', {target:'div#editor', type:'keypress'}); ******************************************************************************************************************************/ (function (jQuery){ this.version = '(beta)(0.0.3)'; this.all = {}; this.special_keys = { 27: 'esc', 9: 'tab', 32:'space', 13: 'return', 8:'backspace', 145: 'scroll', 20: 'capslock', 144: 'numlock', 19:'pause', 45:'insert', 36:'home', 46:'del',35:'end', 33: 'pageup', 34:'pagedown', 37:'left', 38:'up', 39:'right',40:'down', 112:'f1',113:'f2', 114:'f3', 115:'f4', 116:'f5', 117:'f6', 118:'f7', 119:'f8', 120:'f9', 121:'f10', 122:'f11', 123:'f12'}; this.shift_nums = { "`":"~", "1":"!", "2":"@", "3":"#", "4":"$", "5":"%", "6":"^", "7":"&", "8":"*", "9":"(", "0":")", "-":"_", "=":"+", ";":":", "'":"\"", ",":"<", ".":">", "/":"?", "\\":"|" }; this.add = function(combi, options, callback) { if (jQuery.isFunction(options)){ callback = options; options = {}; } var opt = {}, defaults = {type: 'keydown', propagate: false, disableInInput: false, target: jQuery('html')[0]}, that = this; opt = jQuery.extend( opt , defaults, options || {} ); combi = combi.toLowerCase(); // inspect if keystroke matches var inspector = function(event) { event = jQuery.event.fix(event); // jQuery event normalization. var element = event.target; // @ TextNode -> nodeType == 3 element = (element.nodeType==3) ? element.parentNode : element; if(opt['disableInInput']) { // Disable shortcut keys in Input, Textarea fields var target = jQuery(element); if( target.is("input") || target.is("textarea")){ return; } } var code = event.which, type = event.type, character = String.fromCharCode(code).toLowerCase(), special = that.special_keys[code], shift = event.shiftKey, ctrl = event.ctrlKey, alt= event.altKey, meta = event.metaKey, propagate = true, // default behaivour mapPoint = null; // in opera + safari, the event.target is unpredictable. // for example: 'keydown' might be associated with HtmlBodyElement // or the element where you last clicked with your mouse. if (jQuery.browser.opera || jQuery.browser.safari){ while (!that.all[element] && element.parentNode){ element = element.parentNode; } } var cbMap = that.all[element].events[type].callbackMap; if(!shift && !ctrl && !alt && !meta) { // No Modifiers mapPoint = cbMap[special] || cbMap[character] } // deals with combinaitons (alt|ctrl|shift+anything) else{ var modif = ''; if(alt) modif +='alt+'; if(ctrl) modif+= 'ctrl+'; if(shift) modif += 'shift+'; if(meta) modif += 'meta+'; // modifiers + special keys or modifiers + characters or modifiers + shift characters mapPoint = cbMap[modif+special] || cbMap[modif+character] || cbMap[modif+that.shift_nums[character]] } if (mapPoint){ mapPoint.cb(event); if(!mapPoint.propagate) { event.stopPropagation(); event.preventDefault(); return false; } } }; // first hook for this element if (!this.all[opt.target]){ this.all[opt.target] = {events:{}}; } if (!this.all[opt.target].events[opt.type]){ this.all[opt.target].events[opt.type] = {callbackMap: {}} jQuery.event.add(opt.target, opt.type, inspector); } this.all[opt.target].events[opt.type].callbackMap[combi] = {cb: callback, propagate:opt.propagate}; return jQuery; }; this.remove = function(exp, opt) { opt = opt || {}; target = opt.target || jQuery('html')[0]; type = opt.type || 'keydown'; exp = exp.toLowerCase(); delete this.all[target].events[type].callbackMap[exp] return jQuery; }; jQuery.hotkeys = this; return jQuery; })(jQuery);
JavaScript
(function($){$.scheduler=function(){this.bucket={};return;};$.scheduler.prototype={schedule:function(){var ctx={"id":null,"time":1000,"repeat":false,"protect":false,"obj":null,"func":function(){},"args":[]};function _isfn(fn){return(!!fn&&typeof fn!="string"&&typeof fn[0]=="undefined"&&RegExp("function","i").test(fn+""));};var i=0;var override=false;if(typeof arguments[i]=="object"&&arguments.length>1){override=true;i++;} if(typeof arguments[i]=="object"){for(var option in arguments[i]) if(typeof ctx[option]!="undefined") ctx[option]=arguments[i][option];i++;} if(typeof arguments[i]=="number"||(typeof arguments[i]=="string"&&arguments[i].match(RegExp("^[0-9]+[smhdw]$")))) ctx["time"]=arguments[i++];if(typeof arguments[i]=="boolean") ctx["repeat"]=arguments[i++];if(typeof arguments[i]=="boolean") ctx["protect"]=arguments[i++];if(typeof arguments[i]=="object"&&typeof arguments[i+1]=="string"&&_isfn(arguments[i][arguments[i+1]])){ctx["obj"]=arguments[i++];ctx["func"]=arguments[i++];} else if(typeof arguments[i]!="undefined"&&(_isfn(arguments[i])||typeof arguments[i]=="string")) ctx["func"]=arguments[i++];while(typeof arguments[i]!="undefined") ctx["args"].push(arguments[i++]);if(override){if(typeof arguments[1]=="object"){for(var option in arguments[0]) if(typeof ctx[option]!="undefined"&&typeof arguments[1][option]=="undefined") ctx[option]=arguments[0][option];} else{for(var option in arguments[0]) if(typeof ctx[option]!="undefined") ctx[option]=arguments[0][option];} i++;} ctx["_scheduler"]=this;ctx["_handle"]=null;var match=String(ctx["time"]).match(RegExp("^([0-9]+)([smhdw])$"));if(match&&match[0]!="undefined"&&match[1]!="undefined") ctx["time"]=String(parseInt(match[1])*{s:1000,m:1000*60,h:1000*60*60,d:1000*60*60*24,w:1000*60*60*24*7}[match[2]]);if(ctx["id"]==null) ctx["id"]=(String(ctx["repeat"])+":" +String(ctx["protect"])+":" +String(ctx["time"])+":" +String(ctx["obj"])+":" +String(ctx["func"])+":" +String(ctx["args"]));if(ctx["protect"]) if(typeof this.bucket[ctx["id"]]!="undefined") return this.bucket[ctx["id"]];if(!_isfn(ctx["func"])){if(ctx["obj"]!=null&&typeof ctx["obj"]=="object"&&typeof ctx["func"]=="string"&&_isfn(ctx["obj"][ctx["func"]])) ctx["func"]=ctx["obj"][ctx["func"]];else ctx["func"]=eval("function () { "+ctx["func"]+" }");} ctx["_handle"]=this._schedule(ctx);this.bucket[ctx["id"]]=ctx;return ctx;},reschedule:function(ctx){if(typeof ctx=="string") ctx=this.bucket[ctx];ctx["_handle"]=this._schedule(ctx);return ctx;},_schedule:function(ctx){var trampoline=function(){var obj=(ctx["obj"]!=null?ctx["obj"]:ctx);(ctx["func"]).apply(obj,ctx["args"]);if(typeof(ctx["_scheduler"]).bucket[ctx["id"]]!="undefined"&&ctx["repeat"]) (ctx["_scheduler"])._schedule(ctx);else delete(ctx["_scheduler"]).bucket[ctx["id"]];};return setTimeout(trampoline,ctx["time"]);},cancel:function(ctx){if(typeof ctx=="string") ctx=this.bucket[ctx];if(typeof ctx=="object"){clearTimeout(ctx["_handle"]);delete this.bucket[ctx["id"]];}}};$.extend({scheduler$:new $.scheduler(),schedule:function(){return $.scheduler$.schedule.apply($.scheduler$,arguments)},reschedule:function(){return $.scheduler$.reschedule.apply($.scheduler$,arguments)},cancel:function(){return $.scheduler$.cancel.apply($.scheduler$,arguments)}});$.fn.extend({schedule:function(){var a=[{}];for(var i=0;i<arguments.length;i++) a.push(arguments[i]);return this.each(function(){a[0]={"id":this,"obj":this};return $.schedule.apply($,a);});}});})(jQuery);
JavaScript
/* * jQuery Color Animations * Copyright 2007 John Resig * Released under the MIT and GPL licenses. */ (function(jQuery){ // We override the animation for all of these color styles jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){ jQuery.fx.step[attr] = function(fx){ if ( fx.state == 0 ) { fx.start = getColor( fx.elem, attr ); fx.end = getRGB( fx.end ); } fx.elem.style[attr] = "rgb(" + [ Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0), Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0), Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0) ].join(",") + ")"; } }); // Color Conversion functions from highlightFade // By Blair Mitchelmore // http://jquery.offput.ca/highlightFade/ // Parse strings looking for color tuples [255,255,255] function getRGB(color) { var result; // Check if we're already dealing with an array of colors if ( color && color.constructor == Array && color.length == 3 ) return color; // Look for rgb(num,num,num) if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color)) return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])]; // Look for rgb(num%,num%,num%) if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color)) return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55]; // Look for #a0b1c2 if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color)) return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)]; // Look for #fff if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color)) return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)]; // Look for rgba(0, 0, 0, 0) == transparent in Safari 3 if (result = /rgba\(0, 0, 0, 0\)/.exec(color)) return colors['transparent'] // Otherwise, we're most likely dealing with a named color return colors[jQuery.trim(color).toLowerCase()]; } function getColor(elem, attr) { var color; do { color = jQuery.curCSS(elem, attr); // Keep going until we find an element that has color, or we hit the body if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") ) break; attr = "backgroundColor"; } while ( elem = elem.parentNode ); return getRGB(color); }; // Some named colors to work with // From Interface by Stefan Petre // http://interface.eyecon.ro/ var colors = { 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], transparent: [255,255,255] }; })(jQuery);
JavaScript
/* * jquery.suggest 1.1b - 2007-08-06 * Patched by Mark Jaquith with Alexander Dick's "multiple items" patch to allow for auto-suggesting of more than one tag before submitting * See: http://www.vulgarisoip.com/2007/06/29/jquerysuggest-an-alternative-jquery-based-autocomplete-library/#comment-7228 * * Uses code and techniques from following libraries: * 1. http://www.dyve.net/jquery/?autocomplete * 2. http://dev.jquery.com/browser/trunk/plugins/interface/iautocompleter.js * * All the new stuff written by Peter Vulgaris (www.vulgarisoip.com) * Feel free to do whatever you want with this file * */ (function($) { $.suggest = function(input, options) { var $input, $results, timeout, prevLength, cache, cacheSize; $input = $(input).attr("autocomplete", "off"); $results = $(document.createElement("ul")); timeout = false; // hold timeout ID for suggestion results to appear prevLength = 0; // last recorded length of $input.val() cache = []; // cache MRU list cacheSize = 0; // size of cache in chars (bytes?) $results.addClass(options.resultsClass).appendTo('body'); resetPosition(); $(window) .load(resetPosition) // just in case user is changing size of page while loading .resize(resetPosition); $input.blur(function() { setTimeout(function() { $results.hide() }, 200); }); // help IE users if possible if ( $.browser.msie ) { try { $results.bgiframe(); } catch(e) { } } // I really hate browser detection, but I don't see any other way if ($.browser.mozilla) $input.keypress(processKey); // onkeypress repeats arrow keys in Mozilla/Opera else $input.keydown(processKey); // onkeydown repeats arrow keys in IE/Safari function resetPosition() { // requires jquery.dimension plugin var offset = $input.offset(); $results.css({ top: (offset.top + input.offsetHeight) + 'px', left: offset.left + 'px' }); } function processKey(e) { // handling up/down/escape requires results to be visible // handling enter/tab requires that AND a result to be selected if ((/27$|38$|40$/.test(e.keyCode) && $results.is(':visible')) || (/^13$|^9$/.test(e.keyCode) && getCurrentResult())) { if (e.preventDefault) e.preventDefault(); if (e.stopPropagation) e.stopPropagation(); e.cancelBubble = true; e.returnValue = false; switch(e.keyCode) { case 38: // up prevResult(); break; case 40: // down nextResult(); break; case 9: // tab case 13: // return selectCurrentResult(); break; case 27: // escape $results.hide(); break; } } else if ($input.val().length != prevLength) { if (timeout) clearTimeout(timeout); timeout = setTimeout(suggest, options.delay); prevLength = $input.val().length; } } function suggest() { var q = $.trim($input.val()), multipleSepPos, items; if ( options.multiple ) { multipleSepPos = q.lastIndexOf(options.multipleSep); if ( multipleSepPos != -1 ) { q = $.trim(q.substr(multipleSepPos + options.multipleSep.length)); } } if (q.length >= options.minchars) { cached = checkCache(q); if (cached) { displayItems(cached['items']); } else { $.get(options.source, {q: q}, function(txt) { $results.hide(); items = parseTxt(txt, q); displayItems(items); addToCache(q, items, txt.length); }); } } else { $results.hide(); } } function checkCache(q) { var i; for (i = 0; i < cache.length; i++) if (cache[i]['q'] == q) { cache.unshift(cache.splice(i, 1)[0]); return cache[0]; } return false; } function addToCache(q, items, size) { var cached; while (cache.length && (cacheSize + size > options.maxCacheSize)) { cached = cache.pop(); cacheSize -= cached['size']; } cache.push({ q: q, size: size, items: items }); cacheSize += size; } function displayItems(items) { var html = '', i; if (!items) return; if (!items.length) { $results.hide(); return; } resetPosition(); // when the form moves after the page has loaded for (i = 0; i < items.length; i++) html += '<li>' + items[i] + '</li>'; $results.html(html).show(); $results .children('li') .mouseover(function() { $results.children('li').removeClass(options.selectClass); $(this).addClass(options.selectClass); }) .click(function(e) { e.preventDefault(); e.stopPropagation(); selectCurrentResult(); }); } function parseTxt(txt, q) { var items = [], tokens = txt.split(options.delimiter), i, token; // parse returned data for non-empty items for (i = 0; i < tokens.length; i++) { token = $.trim(tokens[i]); if (token) { token = token.replace( new RegExp(q, 'ig'), function(q) { return '<span class="' + options.matchClass + '">' + q + '</span>' } ); items[items.length] = token; } } return items; } function getCurrentResult() { var $currentResult; if (!$results.is(':visible')) return false; $currentResult = $results.children('li.' + options.selectClass); if (!$currentResult.length) $currentResult = false; return $currentResult; } function selectCurrentResult() { $currentResult = getCurrentResult(); if ($currentResult) { if ( options.multiple ) { if ( $input.val().indexOf(options.multipleSep) != -1 ) { $currentVal = $input.val().substr( 0, ( $input.val().lastIndexOf(options.multipleSep) + options.multipleSep.length ) ); } else { $currentVal = ""; } $input.val( $currentVal + $currentResult.text() + options.multipleSep); $input.focus(); } else { $input.val($currentResult.text()); } $results.hide(); if (options.onSelect) options.onSelect.apply($input[0]); } } function nextResult() { $currentResult = getCurrentResult(); if ($currentResult) $currentResult .removeClass(options.selectClass) .next() .addClass(options.selectClass); else $results.children('li:first-child').addClass(options.selectClass); } function prevResult() { var $currentResult = getCurrentResult(); if ($currentResult) $currentResult .removeClass(options.selectClass) .prev() .addClass(options.selectClass); else $results.children('li:last-child').addClass(options.selectClass); } } $.fn.suggest = function(source, options) { if (!source) return; options = options || {}; options.multiple = options.multiple || false; options.multipleSep = options.multipleSep || ", "; options.source = source; options.delay = options.delay || 100; options.resultsClass = options.resultsClass || 'ac_results'; options.selectClass = options.selectClass || 'ac_over'; options.matchClass = options.matchClass || 'ac_match'; options.minchars = options.minchars || 2; options.delimiter = options.delimiter || '\n'; options.onSelect = options.onSelect || false; options.maxCacheSize = options.maxCacheSize || 65536; this.each(function() { new $.suggest(this, options); }); return this; }; })(jQuery);
JavaScript
(function($){ $.fn.filter_visible = function(depth) { depth = depth || 3; var is_visible = function() { var p = $(this), i; for(i=0; i<depth-1; ++i) { if (!p.is(':visible')) return false; p = p.parent(); } return true; } return this.filter(is_visible); }; $.table_hotkeys = function(table, keys, opts) { opts = $.extend($.table_hotkeys.defaults, opts); var selected_class, destructive_class, set_current_row, adjacent_row_callback, get_adjacent_row, adjacent_row, prev_row, next_row, check, get_first_row, get_last_row, make_key_callback, first_row; selected_class = opts.class_prefix + opts.selected_suffix; destructive_class = opts.class_prefix + opts.destructive_suffix set_current_row = function (tr) { if ($.table_hotkeys.current_row) $.table_hotkeys.current_row.removeClass(selected_class); tr.addClass(selected_class); tr[0].scrollIntoView(false); $.table_hotkeys.current_row = tr; }; adjacent_row_callback = function(which) { if (!adjacent_row(which) && $.isFunction(opts[which+'_page_link_cb'])) { opts[which+'_page_link_cb'](); } }; get_adjacent_row = function(which) { var first_row, method; if (!$.table_hotkeys.current_row) { first_row = get_first_row(); $.table_hotkeys.current_row = first_row; return first_row[0]; } method = 'prev' == which? $.fn.prevAll : $.fn.nextAll; return method.call($.table_hotkeys.current_row, opts.cycle_expr).filter_visible()[0]; }; adjacent_row = function(which) { var adj = get_adjacent_row(which); if (!adj) return false; set_current_row($(adj)); return true; }; prev_row = function() { return adjacent_row('prev'); }; next_row = function() { return adjacent_row('next'); }; check = function() { $(opts.checkbox_expr, $.table_hotkeys.current_row).each(function() { this.checked = !this.checked; }); }; get_first_row = function() { return $(opts.cycle_expr, table).filter_visible().eq(opts.start_row_index); }; get_last_row = function() { var rows = $(opts.cycle_expr, table).filter_visible(); return rows.eq(rows.length-1); }; make_key_callback = function(expr) { return function() { if ( null == $.table_hotkeys.current_row ) return false; var clickable = $(expr, $.table_hotkeys.current_row); if (!clickable.length) return false; if (clickable.is('.'+destructive_class)) next_row() || prev_row(); clickable.click(); } }; first_row = get_first_row(); if (!first_row.length) return; if (opts.highlight_first) set_current_row(first_row); else if (opts.highlight_last) set_current_row(get_last_row()); $.hotkeys.add(opts.prev_key, opts.hotkeys_opts, function() {return adjacent_row_callback('prev')}); $.hotkeys.add(opts.next_key, opts.hotkeys_opts, function() {return adjacent_row_callback('next')}); $.hotkeys.add(opts.mark_key, opts.hotkeys_opts, check); $.each(keys, function() { var callback, key; if ($.isFunction(this[1])) { callback = this[1]; key = this[0]; $.hotkeys.add(key, opts.hotkeys_opts, function(event) { return callback(event, $.table_hotkeys.current_row); }); } else { key = this; $.hotkeys.add(key, opts.hotkeys_opts, make_key_callback('.'+opts.class_prefix+key)); } }); }; $.table_hotkeys.current_row = null; $.table_hotkeys.defaults = {cycle_expr: 'tr', class_prefix: 'vim-', selected_suffix: 'current', destructive_suffix: 'destructive', hotkeys_opts: {disableInInput: true, type: 'keypress'}, checkbox_expr: ':checkbox', next_key: 'j', prev_key: 'k', mark_key: 'x', start_row_index: 2, highlight_first: false, highlight_last: false, next_page_link_cb: false, prev_page_link_cb: false}; })(jQuery);
JavaScript
/*! * jQuery serializeObject - v0.2 - 1/20/2010 * http://benalman.com/projects/jquery-misc-plugins/ * * Copyright (c) 2010 "Cowboy" Ben Alman * Dual licensed under the MIT and GPL licenses. * http://benalman.com/about/license/ */ // Whereas .serializeArray() serializes a form into an array, .serializeObject() // serializes a form into an (arguably more useful) object. (function($,undefined){ '$:nomunge'; // Used by YUI compressor. $.fn.serializeObject = function(){ var obj = {}; $.each( this.serializeArray(), function(i,o){ var n = o.name, v = o.value; obj[n] = obj[n] === undefined ? v : $.isArray( obj[n] ) ? obj[n].concat( v ) : [ obj[n], v ]; }); return obj; }; })(jQuery);
JavaScript
var wpAjax = jQuery.extend( { unserialize: function( s ) { var r = {}, q, pp, i, p; if ( !s ) { return r; } q = s.split('?'); if ( q[1] ) { s = q[1]; } pp = s.split('&'); for ( i in pp ) { if ( jQuery.isFunction(pp.hasOwnProperty) && !pp.hasOwnProperty(i) ) { continue; } p = pp[i].split('='); r[p[0]] = p[1]; } return r; }, parseAjaxResponse: function( x, r, e ) { // 1 = good, 0 = strange (bad data?), -1 = you lack permission var parsed = {}, re = jQuery('#' + r).html(''), err = ''; if ( x && typeof x == 'object' && x.getElementsByTagName('wp_ajax') ) { parsed.responses = []; parsed.errors = false; jQuery('response', x).each( function() { var th = jQuery(this), child = jQuery(this.firstChild), response; response = { action: th.attr('action'), what: child.get(0).nodeName, id: child.attr('id'), oldId: child.attr('old_id'), position: child.attr('position') }; response.data = jQuery( 'response_data', child ).text(); response.supplemental = {}; if ( !jQuery( 'supplemental', child ).children().each( function() { response.supplemental[this.nodeName] = jQuery(this).text(); } ).size() ) { response.supplemental = false } response.errors = []; if ( !jQuery('wp_error', child).each( function() { var code = jQuery(this).attr('code'), anError, errorData, formField; anError = { code: code, message: this.firstChild.nodeValue, data: false }; errorData = jQuery('wp_error_data[code="' + code + '"]', x); if ( errorData ) { anError.data = errorData.get(); } formField = jQuery( 'form-field', errorData ).text(); if ( formField ) { code = formField; } if ( e ) { wpAjax.invalidateForm( jQuery('#' + e + ' :input[name="' + code + '"]' ).parents('.form-field:first') ); } err += '<p>' + anError.message + '</p>'; response.errors.push( anError ); parsed.errors = true; } ).size() ) { response.errors = false; } parsed.responses.push( response ); } ); if ( err.length ) { re.html( '<div class="error">' + err + '</div>' ); } return parsed; } if ( isNaN(x) ) { return !re.html('<div class="error"><p>' + x + '</p></div>'); } x = parseInt(x,10); if ( -1 == x ) { return !re.html('<div class="error"><p>' + wpAjax.noPerm + '</p></div>'); } else if ( 0 === x ) { return !re.html('<div class="error"><p>' + wpAjax.broken + '</p></div>'); } return true; }, invalidateForm: function ( selector ) { return jQuery( selector ).addClass( 'form-invalid' ).find('input:visible').change( function() { jQuery(this).closest('.form-invalid').removeClass( 'form-invalid' ); } ); }, validateForm: function( selector ) { selector = jQuery( selector ); return !wpAjax.invalidateForm( selector.find('.form-required').filter( function() { return jQuery('input:visible', this).val() == ''; } ) ).size(); } }, wpAjax || { noPerm: 'You do not have permission to do that.', broken: 'An unidentified error has occurred.' } ); // Basic form validation jQuery(document).ready( function($){ $('form.validate').submit( function() { return wpAjax.validateForm( $(this) ); } ); });
JavaScript
(function(w) { var init = function() { var pr = document.getElementById('post-revisions'), inputs = pr ? pr.getElementsByTagName('input') : []; pr.onclick = function() { var i, checkCount = 0, side; for ( i = 0; i < inputs.length; i++ ) { checkCount += inputs[i].checked ? 1 : 0; side = inputs[i].getAttribute('name'); if ( ! inputs[i].checked && ( 'left' == side && 1 > checkCount || 'right' == side && 1 < checkCount && ( ! inputs[i-1] || ! inputs[i-1].checked ) ) && ! ( inputs[i+1] && inputs[i+1].checked && 'right' == inputs[i+1].getAttribute('name') ) ) inputs[i].style.visibility = 'hidden'; else if ( 'left' == side || 'right' == side ) inputs[i].style.visibility = 'visible'; } } pr.onclick(); } if ( w && w.addEventListener ) w.addEventListener('load', init, false); else if ( w && w.attachEvent ) w.attachEvent('onload', init); })(window);
JavaScript
/* * imgAreaSelect jQuery plugin * version 0.9.6 * * 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($) { var abs = Math.abs, max = Math.max, min = Math.min, round = Math.round; function div() { return $('<div/>'); } $.imgAreaSelect = function (img, options) { var $img = $(img), imgLoaded, $box = div(), $area = div(), $border = div().add(div()).add(div()).add(div()), $outer = div().add(div()).add(div()).add(div()), $handles = $([]), $areaOpera, left, top, imgOfs = { left: 0, top: 0 }, imgWidth, imgHeight, $parent, parOfs = { left: 0, top: 0 }, zIndex = 0, position = 'absolute', startX, startY, scaleX, scaleY, resizeMargin = 10, resize, minWidth, minHeight, maxWidth, maxHeight, aspectRatio, shown, x1, y1, x2, y2, selection = { x1: 0, y1: 0, x2: 0, y2: 0, width: 0, height: 0 }, docElem = document.documentElement, $p, d, i, o, w, h, adjusted; function viewX(x) { return x + imgOfs.left - parOfs.left; } function viewY(y) { return y + imgOfs.top - parOfs.top; } function selX(x) { return x - imgOfs.left + parOfs.left; } function selY(y) { return y - imgOfs.top + parOfs.top; } function evX(event) { return event.pageX - parOfs.left; } function evY(event) { return event.pageY - parOfs.top; } 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) }; } 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; } function adjust() { if (!$img.width()) return; imgOfs = { left: round($img.offset().left), top: round($img.offset().top) }; imgWidth = $img.innerWidth(); imgHeight = $img.innerHeight(); imgOfs.top += ($img.outerHeight() - imgHeight) >> 1; imgOfs.left += ($img.outerWidth() - imgWidth) >> 1; minWidth = options.minWidth || 0; minHeight = options.minHeight || 0; maxWidth = min(options.maxWidth || 1<<24, imgWidth); maxHeight = min(options.maxHeight || 1<<24, imgHeight); 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); } parOfs = $.inArray($parent.css('position'), ['absolute', 'relative']) + 1 ? { 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); if (selection.x2 > imgWidth || selection.y2 > imgHeight) doResize(); } function update(resetKeyPress) { if (!shown) return; $box.css({ left: viewX(selection.x1), top: viewY(selection.y1) }) .add($area).width(w = selection.width).height(h = selection.height); $area.add($border).add($handles).css({ left: 0, top: 0 }); $border .width(max(w - $border.outerWidth() + $border.innerWidth(), 0)) .height(max(h - $border.outerHeight() + $border.innerHeight(), 0)); $($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(); 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) { if ($.imgAreaSelect.keyPress != docKeyPress) $(document).unbind($.imgAreaSelect.keyPress, $.imgAreaSelect.onKeyPress); if (options.keys) $(document)[$.imgAreaSelect.keyPress]( $.imgAreaSelect.onKeyPress = docKeyPress); } if ($.browser.msie && $border.outerWidth() - $border.innerWidth() == 2) { $border.css('margin', 0); setTimeout(function () { $border.css('margin', 'auto'); }, 0); } } function doUpdate(resetKeyPress) { adjust(); update(resetKeyPress); x1 = viewX(selection.x1); y1 = viewY(selection.y1); x2 = viewX(selection.x2); y2 = viewY(selection.y2); } function hide($elem, fn) { options.fadeSpeed ? $elem.fadeOut(options.fadeSpeed, fn) : $elem.hide(); } 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; }); } resize = ''; if (options.resizable) { 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(); } function docMouseUp(event) { $('body').css('cursor', ''); 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()); } function areaMouseDown(event) { if (event.which != 1) return false; adjust(); if (resize) { $('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; } 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); } } function doResize() { x1 = min(x1, left + imgWidth); y1 = min(y1, top + imgHeight); if (abs(x2 - x1) < 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) { 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) { x2 = x1 - maxWidth * (x2 < x1 || -1); fixAspectRatio(); } if (abs(y2 - y1) > 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()); } function selectingMouseMove(event) { x2 = resize == '' || /w|e/.test(resize) || aspectRatio ? evX(event) : viewX(selection.x2); y2 = resize == '' || /n|s/.test(resize) || aspectRatio ? evY(event) : viewY(selection.y2); doResize(); return false; } 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()); } 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; } function startSelection() { $(document).unbind('mousemove', startSelection); adjust(); x2 = x1; y2 = y1; doResize(); resize = ''; if ($outer.is(':not(:visible)')) $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()); } function cancelSelection() { $(document).unbind('mousemove', startSelection) .unbind('mouseup', cancelSelection); hide($box.add($outer)); setSelection(selX(x1), selY(y1), selX(x1), selY(y1)); options.onSelectChange(img, getSelection()); options.onSelectEnd(img, getSelection()); } function imgMouseDown(event) { if (event.which != 1 || $outer.is(':animated')) return false; adjust(); startX = x1 = evX(event); startY = y1 = evY(event); $(document).mousemove(startSelection).mouseup(cancelSelection); return false; } function windowResize() { doUpdate(false); } function imgLoad() { imgLoaded = true; 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); } setTimeout(function () { options.onInit(img, getSelection()); }, 0); } 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))) { switch (key) { case 37: d = -d; case 39: t = max(x1, x2); x1 = min(x1, x2); x2 = max(t + d, x1); fixAspectRatio(); break; case 38: d = -d; case 40: t = max(y1, y2); y1 = min(y1, y2); y2 = max(t + d, y1); fixAspectRatio(true); break; default: return; } doResize(); } else { x1 = min(x1, x2); y1 = min(y1, y2); switch (key) { case 37: doMove(max(x1 - d, left), y1); break; case 38: doMove(x1, max(y1 - d, top)); break; case 39: doMove(x1 + min(d, imgWidth - selX(x2)), y1); break; case 40: doMove(x1, y1 + min(d, imgHeight - selY(y2))); break; default: return; } } return false; }; function styleOptions($elem, props) { for (option in props) if (options[option] !== undefined) $elem.css(props[option], options[option]); } function setOptions(newOptions) { if (newOptions.parent) ($parent = $(newOptions.parent)).append($box.add($outer)); $.extend(options, newOptions); adjust(); if (newOptions.handles != null) { $handles.remove(); $handles = $([]); i = newOptions.handles ? newOptions.handles == 'corners' ? 4 : 8 : 0; while (i--) $handles = $handles.add(div()); $handles.addClass(options.classPrefix + '-handle').css({ position: 'absolute', fontSize: 0, zIndex: zIndex + 1 || 1 }); if (!parseInt($handles.css('width')) >= 0) $handles.width(5).height(5); if (o = options.borderWidth) $handles.css({ borderWidth: o, borderStyle: 'solid' }); styleOptions($handles, { borderColor1: 'border-color', borderColor2: 'background-color', borderOpacity: 'opacity' }); } scaleX = options.imageWidth / imgWidth || 1; scaleY = options.imageHeight / imgHeight || 1; if (newOptions.x1 != null) { setSelection(newOptions.x1, newOptions.y1, newOptions.x2, newOptions.y2); newOptions.show = !newOptions.hide; } if (newOptions.keys) options.keys = $.extend({ shift: 1, ctrl: 'resize' }, newOptions.keys); $outer.addClass(options.classPrefix + '-outer'); $area.addClass(options.classPrefix + '-selection'); for (i = 0; i++ < 4;) $($border[i-1]).addClass(options.classPrefix + '-border' + i); 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 }); $box.append($area.add($border).add($areaOpera).add($handles)); if ($.browser.msie) { if (o = $outer.css('filter').match(/opacity=([0-9]+)/)) $outer.css('opacity', o[1]/100); if (o = $border.css('filter').match(/opacity=([0-9]+)/)) $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(); } aspectRatio = (d = (options.aspectRatio || '').split(/:/))[0] / d[1]; $img.add($outer).unbind('mousedown', imgMouseDown); if (options.disable || options.enable === false) { $box.unbind('mousemove', areaMouseMove).unbind('mousedown', areaMouseDown); $(window).unbind('resize', windowResize); } else { if (options.enable || options.disable === false) { 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; } this.remove = function () { setOptions({ disable: true }); $box.add($outer).remove(); }; this.getOptions = function () { return options; }; this.setOptions = setOptions; this.getSelection = getSelection; this.setSelection = setSelection; this.update = doUpdate; $p = $img; while ($p.length) { zIndex = max(zIndex, !isNaN($p.css('z-index')) ? $p.css('z-index') : zIndex); if ($p.css('position') == 'fixed') position = 'fixed'; $p = $p.parent(':not(body)'); } zIndex = options.zIndex || zIndex; if ($.browser.msie) $img.attr('unselectable', 'on'); $.imgAreaSelect.keyPress = $.browser.msie || $.browser.safari ? 'keydown' : 'keypress'; if ($.browser.opera) $areaOpera = div().css({ width: '100%', height: '100%', position: 'absolute', zIndex: zIndex + 2 || 2 }); $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 }); img.complete || img.readyState == 'complete' || !$img.is('img') ? imgLoad() : $img.one('load', imgLoad); if ($.browser.msie && $.browser.version >= 9) img.src = img.src; }; $.fn.imgAreaSelect = function (options) { options = options || {}; this.each(function () { if ($(this).data('imgAreaSelect')) { if (options.remove) { $(this).data('imgAreaSelect').remove(); $(this).removeData('imgAreaSelect'); } else $(this).data('imgAreaSelect').setOptions(options); } else if (!options.remove) { if (options.enable === undefined && options.disable === undefined) options.enable = true; $(this).data('imgAreaSelect', new $.imgAreaSelect(this, options)); } }); if (options.instance) return $(this).data('imgAreaSelect'); return this; }; })(jQuery);
JavaScript
(function() { tinymce.create('tinymce.plugins.wpGallery', { init : function(ed, url) { var t = this; t.url = url; t._createButtons(); // Register the command so that it can be invoked by using tinyMCE.activeEditor.execCommand('...'); ed.addCommand('WP_Gallery', function() { var el = ed.selection.getNode(), post_id, vp = tinymce.DOM.getViewPort(), H = vp.h - 80, W = ( 640 < vp.w ) ? 640 : vp.w; if ( el.nodeName != 'IMG' ) return; if ( ed.dom.getAttrib(el, 'class').indexOf('wpGallery') == -1 ) return; post_id = tinymce.DOM.get('post_ID').value; tb_show('', tinymce.documentBaseURL + '/media-upload.php?post_id='+post_id+'&tab=gallery&TB_iframe=true&width='+W+'&height='+H); tinymce.DOM.setStyle( ['TB_overlay','TB_window','TB_load'], 'z-index', '999999' ); }); ed.onMouseDown.add(function(ed, e) { if ( e.target.nodeName == 'IMG' && ed.dom.hasClass(e.target, 'wpGallery') ) 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="wpGallery 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('wpGallery') != -1 ) return '<p>['+tinymce.trim(getAttr(im, 'title'))+']</p>'; return a; }); }, _createButtons : function() { var t = this, ed = tinyMCE.activeEditor, DOM = tinymce.DOM, editButton, dellButton; DOM.remove('wp_gallerybtns'); DOM.add(document.body, 'div', { id : 'wp_gallerybtns', style : 'display:none;' }); editButton = DOM.add('wp_gallerybtns', 'img', { src : 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.windowManager.bookmark = ed.selection.getBookmark('simple'); ed.execCommand("WP_Gallery"); }); dellButton = DOM.add('wp_gallerybtns', 'img', { src : 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, 'wpGallery') ) { ed.dom.remove(el); ed.execCommand('mceRepaint'); return false; } }); }, getInfo : function() { return { longname : 'Gallery Settings', author : 'WordPress', authorurl : 'http://wordpress.org', infourl : '', version : "1.0" }; } }); tinymce.PluginManager.add('wpgallery', tinymce.plugins.wpGallery); })();
JavaScript
(function($){ $.ui.dialog.prototype.options.closeOnEscape = false; $.widget("wp.wpdialog", $.ui.dialog, { options: { closeOnEscape: false }, open: function() { var ed; // Initialize tinyMCEPopup if it exists and is 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. $.ui.dialog.prototype.open.apply( this, arguments ); // 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. * * 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 retrive. * @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 retrive. * @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 * looses it's 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 * looses it's 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 a 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. * * 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
/** * 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
(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 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) { if (typeof(value) != 'undefined') { var elm = get(id); if (elm.nodeName == "SELECT") selectByValue(document.forms[0], id, value); else if (elm.type == "checkbox") { if (typeof(value) == 'string') elm.checked = value.toLowerCase() === 'true' ? true : false; else elm.checked = !!value; } else elm.value = value; } } window.Media = { init : function() { var html, editor; this.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('filebrowser_altsource1','video_altsource1','media','media'); get('video_altsource2_filebrowser').innerHTML = getBrowserHTML('filebrowser_altsource2','video_altsource2','media','media'); get('video_poster_filebrowser').innerHTML = getBrowserHTML('filebrowser_poster','video_poster','media','image'); html = this.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('filebrowser_altsource1')) get('video_altsource1').style.width = '220px'; if (isVisible('filebrowser_altsource2')) get('video_altsource2').style.width = '220px'; if (isVisible('filebrowser_poster')) get('video_poster').style.width = '220px'; this.data = tinyMCEPopup.getWindowArg('data'); this.dataToForm(); this.preview(); }, 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, data = this.data, 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') { 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]); } else { delete list[name]; value = getVal(formItemName); if (type == 'video' && 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") { 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('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'; 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,preload,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 { // 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 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); } 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 data.params.src = src; // Set default size setVal('width', data.width || 320); setVal('height', data.height || 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 = this.editor.plugins.media.htmlToData(getVal('source')); this.dataToForm(); this.panel = ''; } this.moveStates(false, field); this.preview(); } }, beforeResize : function() { this.width = parseInt(getVal('width') || "320", 10); this.height = parseInt(getVal('height') || "240", 10); }, changeSize : function(type) { var width, height, scale, size; if (get('constrain').checked) { width = parseInt(getVal('width') || "320", 10); height = parseInt(getVal('height') || "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 ""; } }; tinyMCEPopup.requireLangPack(); tinyMCEPopup.onInit.add(function() { Media.init(); }); })();
JavaScript
var tinymce = null, tinyMCEPopup, tinyMCE, wpImage; tinyMCEPopup = { init: function() { var t = this, w, li, q, i, it; 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 w = t.getWin(); tinymce = w.tinymce; tinyMCE = w.tinyMCE; t.editor = tinymce.EditorManager.activeEditor; t.params = t.editor.windowManager.params; // Setup local DOM t.dom = t.editor.windowManager.createInstance('tinymce.dom.DOMUtils', document); t.editor.windowManager.onOpen.dispatch(t.editor.windowManager, window); }, getWin : function() { return window.dialogArguments || opener || parent || top; }, getParam : function(n, dv) { return this.editor.getParam(n, dv); }, close : function() { var t = this, win = t.getWin(); // To avoid domain relaxing issue in Opera function close() { win.tb_remove(); tinymce = tinyMCE = t.editor = t.dom = t.dom.doc = null; // Cleanup }; if (tinymce.isOpera) win.setTimeout(close, 0); else close(); }, execCommand : function(cmd, ui, val, a) { a = a || {}; a.skip_focus = 1; this.restoreSelection(); return this.editor.execCommand(cmd, ui, val, a); }, storeSelection : function() { this.editor.windowManager.bookmark = tinyMCEPopup.editor.selection.getBookmark('simple'); }, restoreSelection : function() { var t = tinyMCEPopup; if (tinymce.isIE) t.editor.selection.moveToBookmark(t.editor.windowManager.bookmark); } } tinyMCEPopup.init(); wpImage = { preInit : function() { // import colors stylesheet from parent var win = tinyMCEPopup.getWin(), styles = win.document.styleSheets, url, i; for ( i = 0; i < styles.length; i++ ) { url = styles.item(i).href; if ( url && url.indexOf('colors') != -1 ) document.write( '<link rel="stylesheet" href="'+url+'" type="text/css" media="all" />' ); } }, I : function(e) { return document.getElementById(e); }, current : '', link : '', link_rel : '', target_value : '', current_size_sel : 's100', width : '', height : '', align : '', img_alt : '', setTabs : function(tab) { var t = this; if ( 'current' == tab.className ) return false; t.I('div_advanced').style.display = ( 'tab_advanced' == tab.id ) ? 'block' : 'none'; t.I('div_basic').style.display = ( 'tab_basic' == tab.id ) ? 'block' : 'none'; t.I('tab_basic').className = t.I('tab_advanced').className = ''; tab.className = 'current'; return false; }, img_seturl : function(u) { var t = this, rel = t.I('link_rel').value; if ( 'current' == u ) { t.I('link_href').value = t.current; t.I('link_rel').value = t.link_rel; } else { t.I('link_href').value = t.link; if ( rel ) { rel = rel.replace( /attachment|wp-att-[0-9]+/gi, '' ); t.I('link_rel').value = tinymce.trim(rel); } } }, imgAlignCls : function(v) { var t = this, cls = t.I('img_classes').value; t.I('img_demo').className = t.align = v; cls = cls.replace( /align[^ "']+/gi, '' ); cls += (' ' + v); cls = cls.replace( /\s+/g, ' ' ).replace( /^\s/, '' ); if ( 'aligncenter' == v ) { t.I('hspace').value = ''; t.updateStyle('hspace'); } t.I('img_classes').value = cls; }, showSize : function(el) { var t = this, demo = t.I('img_demo'), w = t.width, h = t.height, id = el.id || 's100', size; size = parseInt(id.substring(1)) / 200; demo.width = Math.round(w * size); demo.height = Math.round(h * size); t.showSizeClear(); el.style.borderColor = '#A3A3A3'; el.style.backgroundColor = '#E5E5E5'; }, showSizeSet : function() { var t = this, s130, s120, s110; if ( (t.width * 1.3) > parseInt(t.preloadImg.width) ) { s130 = t.I('s130'), s120 = t.I('s120'), s110 = t.I('s110'); s130.onclick = s120.onclick = s110.onclick = null; s130.onmouseover = s120.onmouseover = s110.onmouseover = null; s130.style.color = s120.style.color = s110.style.color = '#aaa'; } }, showSizeRem : function() { var t = this, demo = t.I('img_demo'), f = document.forms[0]; demo.width = Math.round(f.width.value * 0.5); demo.height = Math.round(f.height.value * 0.5); t.showSizeClear(); t.I(t.current_size_sel).style.borderColor = '#A3A3A3'; t.I(t.current_size_sel).style.backgroundColor = '#E5E5E5'; return false; }, showSizeClear : function() { var divs = this.I('img_size').getElementsByTagName('div'), i; for ( i = 0; i < divs.length; i++ ) { divs[i].style.borderColor = '#f1f1f1'; divs[i].style.backgroundColor = '#f1f1f1'; } }, imgEditSize : function(el) { var t = this, f = document.forms[0], W, H, w, h, id; if ( ! t.preloadImg || ! t.preloadImg.width || ! t.preloadImg.height ) return; W = parseInt(t.preloadImg.width), H = parseInt(t.preloadImg.height), w = t.width || W, h = t.height || H, id = el.id || 's100'; size = parseInt(id.substring(1)) / 100; w = Math.round(w * size); h = Math.round(h * size); f.width.value = Math.min(W, w); f.height.value = Math.min(H, h); t.current_size_sel = id; t.demoSetSize(); }, demoSetSize : function(img) { var demo = this.I('img_demo'), f = document.forms[0]; demo.width = f.width.value ? Math.round(f.width.value * 0.5) : ''; demo.height = f.height.value ? Math.round(f.height.value * 0.5) : ''; }, demoSetStyle : function() { var f = document.forms[0], demo = this.I('img_demo'), dom = tinyMCEPopup.editor.dom; if (demo) { dom.setAttrib(demo, 'style', f.img_style.value); dom.setStyle(demo, 'width', ''); dom.setStyle(demo, 'height', ''); } }, origSize : function() { var t = this, f = document.forms[0], el = t.I('s100'); f.width.value = t.width = t.preloadImg.width; f.height.value = t.height = t.preloadImg.height; t.showSizeSet(); t.demoSetSize(); t.showSize(el); }, init : function() { var ed = tinyMCEPopup.editor, h; h = document.body.innerHTML; document.body.innerHTML = ed.translate(h); window.setTimeout( function(){wpImage.setup();}, 500 ); }, setup : function() { var t = this, c, el, link, fname, f = document.forms[0], ed = tinyMCEPopup.editor, d = t.I('img_demo'), dom = tinyMCEPopup.dom, DL, caption = '', dlc, pa; document.dir = tinyMCEPopup.editor.getParam('directionality',''); if ( tinyMCEPopup.editor.getParam('wpeditimage_disable_captions', false) ) t.I('cap_field').style.display = 'none'; tinyMCEPopup.restoreSelection(); el = ed.selection.getNode(); if (el.nodeName != 'IMG') return; f.img_src.value = d.src = link = ed.dom.getAttrib(el, 'src'); ed.dom.setStyle(el, 'float', ''); t.getImageData(); c = ed.dom.getAttrib(el, 'class'); if ( DL = dom.getParent(el, 'dl') ) { dlc = ed.dom.getAttrib(DL, 'class'); dlc = dlc.match(/align[^ "']+/i); if ( dlc && ! dom.hasClass(el, dlc) ) { c += ' '+dlc; tinymce.trim(c); } tinymce.each(DL.childNodes, function(e) { if ( e.nodeName == 'DD' && dom.hasClass(e, 'wp-caption-dd') ) { caption = e.innerHTML; return; } }); } f.img_cap.value = caption; f.img_title.value = ed.dom.getAttrib(el, 'title'); f.img_alt.value = ed.dom.getAttrib(el, 'alt'); f.border.value = ed.dom.getAttrib(el, 'border'); f.vspace.value = ed.dom.getAttrib(el, 'vspace'); f.hspace.value = ed.dom.getAttrib(el, 'hspace'); f.align.value = ed.dom.getAttrib(el, 'align'); f.width.value = t.width = ed.dom.getAttrib(el, 'width'); f.height.value = t.height = ed.dom.getAttrib(el, 'height'); f.img_classes.value = c; f.img_style.value = ed.dom.getAttrib(el, 'style'); // Move attribs to styles if ( dom.getAttrib(el, 'hspace') ) t.updateStyle('hspace'); if ( dom.getAttrib(el, 'border') ) t.updateStyle('border'); if ( dom.getAttrib(el, 'vspace') ) t.updateStyle('vspace'); if ( pa = ed.dom.getParent(el, 'A') ) { f.link_href.value = t.current = ed.dom.getAttrib(pa, 'href'); f.link_title.value = ed.dom.getAttrib(pa, 'title'); f.link_rel.value = t.link_rel = ed.dom.getAttrib(pa, 'rel'); f.link_style.value = ed.dom.getAttrib(pa, 'style'); t.target_value = ed.dom.getAttrib(pa, 'target'); f.link_classes.value = ed.dom.getAttrib(pa, 'class'); } f.link_target.checked = ( t.target_value && t.target_value == '_blank' ) ? 'checked' : ''; fname = link.substring( link.lastIndexOf('/') ); fname = fname.replace(/-[0-9]{2,4}x[0-9]{2,4}/, '' ); t.link = link.substring( 0, link.lastIndexOf('/') ) + fname; if ( c.indexOf('alignleft') != -1 ) { t.I('alignleft').checked = "checked"; d.className = t.align = "alignleft"; } else if ( c.indexOf('aligncenter') != -1 ) { t.I('aligncenter').checked = "checked"; d.className = t.align = "aligncenter"; } else if ( c.indexOf('alignright') != -1 ) { t.I('alignright').checked = "checked"; d.className = t.align = "alignright"; } else if ( c.indexOf('alignnone') != -1 ) { t.I('alignnone').checked = "checked"; d.className = t.align = "alignnone"; } if ( t.width && t.preloadImg.width ) t.showSizeSet(); document.body.style.display = ''; }, remove : function() { var ed = tinyMCEPopup.editor, p, el; tinyMCEPopup.restoreSelection(); el = ed.selection.getNode(); if (el.nodeName != 'IMG') return; if ( (p = ed.dom.getParent(el, 'div')) && ed.dom.hasClass(p, 'mceTemp') ) ed.dom.remove(p); else if ( (p = ed.dom.getParent(el, 'A')) && p.childNodes.length == 1 ) ed.dom.remove(p); else ed.dom.remove(el); ed.execCommand('mceRepaint'); tinyMCEPopup.close(); return; }, update : function() { var t = this, f = document.forms[0], ed = tinyMCEPopup.editor, el, b, fixSafari = null, DL, P, A, DIV, do_caption = null, img_class = f.img_classes.value, html, id, cap_id = '', cap, DT, DD, cap_width, div_cls, lnk = '', pa, aa; tinyMCEPopup.restoreSelection(); el = ed.selection.getNode(); if (el.nodeName != 'IMG') return; if (f.img_src.value === '') { t.remove(); return; } if ( f.img_cap.value != '' && f.width.value != '' ) { do_caption = 1; img_class = img_class.replace( /align[^ "']+\s?/gi, '' ); } A = ed.dom.getParent(el, 'a'); P = ed.dom.getParent(el, 'p'); DL = ed.dom.getParent(el, 'dl'); DIV = ed.dom.getParent(el, 'div'); tinyMCEPopup.execCommand("mceBeginUndoLevel"); ed.dom.setAttribs(el, { src : f.img_src.value, title : f.img_title.value, alt : f.img_alt.value, width : f.width.value, height : f.height.value, style : f.img_style.value, 'class' : img_class }); if ( f.link_href.value ) { // Create new anchor elements if ( A == null ) { if ( ! f.link_href.value.match(/https?:\/\//i) ) f.link_href.value = tinyMCEPopup.editor.documentBaseURI.toAbsolute(f.link_href.value); if ( tinymce.isWebKit && ed.dom.hasClass(el, 'aligncenter') ) { ed.dom.removeClass(el, 'aligncenter'); fixSafari = 1; } tinyMCEPopup.execCommand("CreateLink", false, "#mce_temp_url#", {skip_undo : 1}); if ( fixSafari ) ed.dom.addClass(el, 'aligncenter'); tinymce.each(ed.dom.select("a"), function(n) { if (ed.dom.getAttrib(n, 'href') == '#mce_temp_url#') { ed.dom.setAttribs(n, { href : f.link_href.value, title : f.link_title.value, rel : f.link_rel.value, target : (f.link_target.checked == true) ? '_blank' : '', 'class' : f.link_classes.value, style : f.link_style.value }); } }); } else { ed.dom.setAttribs(A, { href : f.link_href.value, title : f.link_title.value, rel : f.link_rel.value, target : (f.link_target.checked == true) ? '_blank' : '', 'class' : f.link_classes.value, style : f.link_style.value }); } } if ( do_caption ) { cap_width = 10 + parseInt(f.width.value); div_cls = (t.align == 'aligncenter') ? 'mceTemp mceIEcenter' : 'mceTemp'; if ( DL ) { ed.dom.setAttribs(DL, { 'class' : 'wp-caption '+t.align, style : 'width: '+cap_width+'px;' }); if ( DIV ) ed.dom.setAttrib(DIV, 'class', div_cls); if ( (DT = ed.dom.getParent(el, 'dt')) && (DD = DT.nextSibling) && ed.dom.hasClass(DD, 'wp-caption-dd') ) ed.dom.setHTML(DD, f.img_cap.value); } else { if ( (id = f.img_classes.value.match( /wp-image-([0-9]{1,6})/ )) && id[1] ) cap_id = 'attachment_'+id[1]; if ( f.link_href.value && (lnk = ed.dom.getParent(el, 'a')) ) { if ( lnk.childNodes.length == 1 ) html = ed.dom.getOuterHTML(lnk); else { html = ed.dom.getOuterHTML(lnk); html = html.match(/<a[^>]+>/i); html = html+ed.dom.getOuterHTML(el)+'</a>'; } } else html = ed.dom.getOuterHTML(el); html = '<dl id="'+cap_id+'" class="wp-caption '+t.align+'" style="width: '+cap_width+ 'px"><dt class="wp-caption-dt">'+html+'</dt><dd class="wp-caption-dd">'+f.img_cap.value+'</dd></dl>'; cap = ed.dom.create('div', {'class': div_cls}, html); if ( P ) { P.parentNode.insertBefore(cap, P); if ( P.childNodes.length == 1 ) ed.dom.remove(P); else if ( lnk && lnk.childNodes.length == 1 ) ed.dom.remove(lnk); else ed.dom.remove(el); } else if ( pa = ed.dom.getParent(el, 'TD,TH,LI') ) { pa.appendChild(cap); if ( lnk && lnk.childNodes.length == 1 ) ed.dom.remove(lnk); else ed.dom.remove(el); } } } else { if ( DL && DIV ) { if ( f.link_href.value && (aa = ed.dom.getParent(el, 'a')) ) html = ed.dom.getOuterHTML(aa); else html = ed.dom.getOuterHTML(el); P = ed.dom.create('p', {}, html); DIV.parentNode.insertBefore(P, DIV); ed.dom.remove(DIV); } } if ( f.img_classes.value.indexOf('aligncenter') != -1 ) { if ( P && ( ! P.style || P.style.textAlign != 'center' ) ) ed.dom.setStyle(P, 'textAlign', 'center'); } else { if ( P && P.style && P.style.textAlign == 'center' ) ed.dom.setStyle(P, 'textAlign', ''); } if ( ! f.link_href.value && A ) { b = ed.selection.getBookmark(); ed.dom.remove(A, 1); ed.selection.moveToBookmark(b); } tinyMCEPopup.execCommand("mceEndUndoLevel"); ed.execCommand('mceRepaint'); tinyMCEPopup.close(); }, updateStyle : function(ty) { var dom = tinyMCEPopup.dom, v, f = document.forms[0], img = dom.create('img', {style : f.img_style.value}); if (tinyMCEPopup.editor.settings.inline_styles) { // Handle align if (ty == 'align') { dom.setStyle(img, 'float', ''); dom.setStyle(img, 'vertical-align', ''); v = f.align.value; if (v) { if (v == 'left' || v == 'right') dom.setStyle(img, 'float', v); else img.style.verticalAlign = v; } } // Handle border if (ty == 'border') { dom.setStyle(img, 'border', ''); v = f.border.value; if (v || v == '0') { if (v == '0') img.style.border = '0'; else img.style.border = v + 'px solid black'; } } // Handle hspace if (ty == 'hspace') { dom.setStyle(img, 'marginLeft', ''); dom.setStyle(img, 'marginRight', ''); v = f.hspace.value; if (v) { img.style.marginLeft = v + 'px'; img.style.marginRight = v + 'px'; } } // Handle vspace if (ty == 'vspace') { dom.setStyle(img, 'marginTop', ''); dom.setStyle(img, 'marginBottom', ''); v = f.vspace.value; if (v) { img.style.marginTop = v + 'px'; img.style.marginBottom = v + 'px'; } } // Merge f.img_style.value = dom.serializeStyle(dom.parseStyle(img.style.cssText)); this.demoSetStyle(); } }, checkVal : function(f) { if ( f.value == '' ) { // if ( f.id == 'width' ) f.value = this.width || this.preloadImg.width; // if ( f.id == 'height' ) f.value = this.height || this.preloadImg.height; if ( f.id == 'img_src' ) f.value = this.I('img_demo').src || this.preloadImg.src; } }, resetImageData : function() { var f = document.forms[0]; f.width.value = f.height.value = ''; }, updateImageData : function() { var f = document.forms[0], t = wpImage, w = f.width.value, h = f.height.value; if ( !w && h ) w = f.width.value = t.width = Math.round( t.preloadImg.width / (t.preloadImg.height / h) ); else if ( w && !h ) h = f.height.value = t.height = Math.round( t.preloadImg.height / (t.preloadImg.width / w) ); if ( !w ) f.width.value = t.width = t.preloadImg.width; if ( !h ) f.height.value = t.height = t.preloadImg.height; t.showSizeSet(); t.demoSetSize(); if ( f.img_style.value ) t.demoSetStyle(); }, getImageData : function() { var t = wpImage, f = document.forms[0]; t.preloadImg = new Image(); t.preloadImg.onload = t.updateImageData; t.preloadImg.onerror = t.resetImageData; t.preloadImg.src = tinyMCEPopup.editor.documentBaseURI.toAbsolute(f.img_src.value); } }; window.onload = function(){wpImage.init();} wpImage.preInit();
JavaScript
(function() { tinymce.create('tinymce.plugins.wpEditImage', { init : function(ed, url) { var t = this; t.url = url; t._createButtons(); // Register the command so that it can be invoked by using tinyMCE.activeEditor.execCommand('...'); ed.addCommand('WP_EditImage', function() { var el = ed.selection.getNode(), vp = tinymce.DOM.getViewPort(), H = vp.h, W = ( 720 < vp.w ) ? 720 : vp.w, cls = ed.dom.getAttrib(el, 'class'); if ( cls.indexOf('mceItem') != -1 || cls.indexOf('wpGallery') != -1 || el.nodeName != 'IMG' ) return; tb_show('', url + '/editimage.html?ver=321&TB_iframe=true'); tinymce.DOM.setStyles('TB_window', { 'width':( W - 50 )+'px', 'height':( H - 45 )+'px', 'margin-left':'-'+parseInt((( W - 50 ) / 2),10) + 'px' }); if ( ! tinymce.isIE6 ) { tinymce.DOM.setStyles('TB_window', { 'top':'20px', 'marginTop':'0' }); } tinymce.DOM.setStyles('TB_iframeContent', { 'width':( W - 50 )+'px', 'height':( H - 75 )+'px' }); tinymce.DOM.setStyle( ['TB_overlay','TB_window','TB_load'], 'z-index', '999999' ); }); ed.onInit.add(function(ed) { tinymce.dom.Event.add(ed.getBody(), 'dragstart', function(e) { if ( !tinymce.isGecko && e.target.nodeName == 'IMG' && ed.dom.getParent(e.target, 'dl.wp-caption') ) return tinymce.dom.Event.cancel(e); }); }); // resize the caption <dl> when the image is soft-resized by the user (only possible in Firefox and IE) ed.onMouseUp.add(function(ed, e) { if ( tinymce.isWebKit || tinymce.isOpera ) return; if ( ed.dom.getParent(e.target, 'div.mceTemp') || ed.dom.is(e.target, 'div.mceTemp') ) { window.setTimeout(function(){ var ed = tinyMCE.activeEditor, n = ed.selection.getNode(), DL, width; if ( 'IMG' == n.nodeName ) { DL = ed.dom.getParent(n, 'dl.wp-caption'); width = ed.dom.getAttrib(n, 'width') || n.width; width = parseInt(width, 10); if ( DL && width != ( parseInt(ed.dom.getStyle(DL, 'width'), 10) - 10 ) ) { ed.dom.setStyle(DL, 'width', 10 + width); ed.execCommand('mceRepaint'); } } }, 100); } }); // show editimage buttons ed.onMouseDown.add(function(ed, e) { var p; if ( e.target.nodeName == 'IMG' && ed.dom.getAttrib(e.target, 'class').indexOf('mceItem') == -1 ) { ed.plugins.wordpress._showButtons(e.target, 'wp_editbtns'); if ( tinymce.isGecko && (p = ed.dom.getParent(e.target, 'dl.wp-caption')) && ed.dom.hasClass(p.parentNode, 'mceTemp') ) ed.selection.select(p.parentNode); } }); // when pressing Return inside a caption move the cursor to a new parapraph under it ed.onKeyPress.add(function(ed, e) { var n, DL, DIV, P; if ( e.keyCode == 13 ) { n = ed.selection.getNode(); DL = ed.dom.getParent(n, 'dl.wp-caption'); DIV = ed.dom.getParent(DL, 'div.mceTemp'); if ( DL && DIV ) { P = ed.dom.create('p', {}, '&nbsp;'); ed.dom.insertAfter( P, DIV ); if ( P.firstChild ) ed.selection.select(P.firstChild); else ed.selection.select(P); tinymce.dom.Event.cancel(e); return false; } } }); ed.onBeforeSetContent.add(function(ed, o) { o.content = t._do_shcode(o.content); }); ed.onPostProcess.add(function(ed, o) { if (o.get) o.content = t._get_shcode(o.content); }); }, _do_shcode : function(co) { return co.replace(/(?:<p>)?\[(?:wp_)?caption([^\]]+)\]([\s\S]+?)\[\/(?:wp_)?caption\](?:<\/p>)?[\s\u00a0]*/g, function(a,b,c){ var id, cls, w, cap, div_cls; b = b.replace(/\\'|\\&#39;|\\&#039;/g, '&#39;').replace(/\\"|\\&quot;/g, '&quot;'); c = c.replace(/\\&#39;|\\&#039;/g, '&#39;').replace(/\\&quot;/g, '&quot;'); id = b.match(/id=['"]([^'"]+)/i); cls = b.match(/align=['"]([^'"]+)/i); w = b.match(/width=['"]([0-9]+)/); cap = b.match(/caption=['"]([^'"]+)/i); id = ( id && id[1] ) ? id[1] : ''; cls = ( cls && cls[1] ) ? cls[1] : 'alignnone'; w = ( w && w[1] ) ? w[1] : ''; cap = ( cap && cap[1] ) ? cap[1] : ''; if ( ! w || ! cap ) return c; div_cls = (cls == 'aligncenter') ? 'mceTemp mceIEcenter' : 'mceTemp'; return '<div class="'+div_cls+'" draggable><dl id="'+id+'" class="wp-caption '+cls+'" style="width: '+(10+parseInt(w))+ 'px"><dt class="wp-caption-dt">'+c+'</dt><dd class="wp-caption-dd">'+cap+'</dd></dl></div>'; }); }, _get_shcode : function(co) { return co.replace(/<div class="mceTemp[^"]*">\s*<dl([^>]+)>\s*<dt[^>]+>([\s\S]+?)<\/dt>\s*<dd[^>]+>(.+?)<\/dd>\s*<\/dl>\s*<\/div>\s*/gi, function(a,b,c,cap){ var id, cls, w; id = b.match(/id=['"]([^'"]+)/i); cls = b.match(/class=['"]([^'"]+)/i); w = c.match(/width=['"]([0-9]+)/); id = ( id && id[1] ) ? id[1] : ''; cls = ( cls && cls[1] ) ? cls[1] : 'alignnone'; w = ( w && w[1] ) ? w[1] : ''; if ( ! w || ! cap ) return c; cls = cls.match(/align[^ '"]+/) || 'alignnone'; cap = cap.replace(/<\S[^<>]*>/gi, '').replace(/'/g, '&#39;').replace(/"/g, '&quot;'); return '[caption id="'+id+'" align="'+cls+'" width="'+w+'" caption="'+cap+'"]'+c+'[/caption]'; }); }, _createButtons : function() { var t = this, ed = tinyMCE.activeEditor, DOM = tinymce.DOM, editButton, dellButton; DOM.remove('wp_editbtns'); DOM.add(document.body, 'div', { id : 'wp_editbtns', style : 'display:none;' }); editButton = DOM.add('wp_editbtns', 'img', { src : t.url+'/img/image.png', id : 'wp_editimgbtn', width : '24', height : '24', title : ed.getLang('wpeditimage.edit_img') }); tinymce.dom.Event.add(editButton, 'mousedown', function(e) { var ed = tinyMCE.activeEditor; ed.windowManager.bookmark = ed.selection.getBookmark('simple'); ed.execCommand("WP_EditImage"); }); dellButton = DOM.add('wp_editbtns', 'img', { src : t.url+'/img/delete.png', id : 'wp_delimgbtn', width : '24', height : '24', title : ed.getLang('wpeditimage.del_img') }); tinymce.dom.Event.add(dellButton, 'mousedown', function(e) { var ed = tinyMCE.activeEditor, el = ed.selection.getNode(), p; if ( el.nodeName == 'IMG' && ed.dom.getAttrib(el, 'class').indexOf('mceItem') == -1 ) { if ( (p = ed.dom.getParent(el, 'div')) && ed.dom.hasClass(p, 'mceTemp') ) ed.dom.remove(p); else if ( (p = ed.dom.getParent(el, 'A')) && p.childNodes.length == 1 ) ed.dom.remove(p); else ed.dom.remove(el); ed.execCommand('mceRepaint'); return false; } }); }, getInfo : function() { return { longname : 'Edit Image', author : 'WordPress', authorurl : 'http://wordpress.org', infourl : '', version : "1.0" }; } }); tinymce.PluginManager.add('wpeditimage', tinymce.plugins.wpEditImage); })();
JavaScript
tinyMCEPopup.requireLangPack(); var PasteWordDialog = { init : function() { var ed = tinyMCEPopup.editor, el = document.getElementById('iframecontainer'), ifr, doc, css, cssHTML = ''; // Create iframe el.innerHTML = '<iframe id="iframe" src="javascript:\'\';" frameBorder="0" style="border: 1px solid gray"></iframe>'; ifr = document.getElementById('iframe'); doc = ifr.contentWindow.document; // Force absolute CSS urls css = [ed.baseURI.toAbsolute("themes/" + ed.settings.theme + "/skins/" + ed.settings.skin + "/content.css")]; css = css.concat(tinymce.explode(ed.settings.content_css) || []); tinymce.each(css, function(u) { cssHTML += '<link href="' + ed.documentBaseURI.toAbsolute('' + u) + '" rel="stylesheet" type="text/css" />'; }); // Write content into iframe doc.open(); doc.write('<html><head>' + cssHTML + '</head><body class="mceContentBody" spellcheck="false"></body></html>'); doc.close(); doc.designMode = 'on'; this.resize(); window.setTimeout(function() { ifr.contentWindow.focus(); }, 10); }, insert : function() { var h = document.getElementById('iframe').contentWindow.document.body.innerHTML; tinyMCEPopup.editor.execCommand('mceInsertClipboardContent', false, {content : h, wordContent : true}); tinyMCEPopup.close(); }, resize : function() { var vp = tinyMCEPopup.dom.getViewPort(window), el; el = document.getElementById('iframe'); if (el) { el.style.width = (vp.w - 20) + 'px'; el.style.height = (vp.h - 90) + 'px'; } } }; tinyMCEPopup.onInit.add(PasteWordDialog.init, PasteWordDialog);
JavaScript
tinyMCEPopup.requireLangPack(); var PasteTextDialog = { init : function() { this.resize(); }, insert : function() { var h = tinyMCEPopup.dom.encode(document.getElementById('content').value), lines; // Convert linebreaks into paragraphs if (document.getElementById('linebreaks').checked) { lines = h.split(/\r?\n/); if (lines.length > 1) { h = ''; tinymce.each(lines, function(row) { h += '<p>' + row + '</p>'; }); } } tinyMCEPopup.editor.execCommand('mceInsertClipboardContent', false, {content : h}); tinyMCEPopup.close(); }, resize : function() { var vp = tinyMCEPopup.dom.getViewPort(window), el; el = document.getElementById('content'); el.style.width = (vp.w - 20) + 'px'; el.style.height = (vp.h - 90) + 'px'; } }; tinyMCEPopup.onInit.add(PasteTextDialog.init, PasteTextDialog);
JavaScript
/** * WP Fullscreen TinyMCE plugin * * Contains code from Moxiecode Systems AB released under LGPL License http://tinymce.moxiecode.com/license */ (function() { tinymce.create('tinymce.plugins.wpFullscreenPlugin', { init : function(ed, url) { var t = this, oldHeight = 0, s = {}, DOM = tinymce.DOM, resized = false; // 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 = ed.getDoc(), b = d.body, fsed; // Only init the editor if necessary. if ( ed.id == 'wp_mce_fullscreen' ) return; 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 ); }); } }); // Register buttons if ( 'undefined' != fullscreen ) { ed.addButton('fullscreen', { title : 'fullscreen.desc', onclick : function(){ fullscreen.on(); } }); } // 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() { if ( resized ) return; var d = ed.getDoc(), DOM = tinymce.DOM, resizeHeight, myHeight; // Get height differently depending on the browser used if ( tinymce.isIE ) myHeight = d.body.scrollHeight; else myHeight = d.documentElement.offsetHeight; // Don't make it smaller than 300px resizeHeight = (myHeight > 300) ? myHeight : 300; // Resize content element if ( oldHeight != resizeHeight ) { oldHeight = resizeHeight; resized = true; setTimeout(function(){ resized = false; }, 100); DOM.setStyle(DOM.get(ed.id + '_ifr'), 'height', resizeHeight + 'px'); } }; // 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
var wpLink; (function($){ var inputs = {}, rivers = {}, ed, River, Query; wpLink = { timeToTriggerRiver: 150, minRiverAJAXDuration: 200, riverBottomThreshold: 5, keySensitivity: 100, lastSearch: '', textarea: function() { return edCanvas; }, init : function() { inputs.dialog = $('#wp-link'); inputs.submit = $('#wp-link-submit'); // URL inputs.url = $('#url-field'); // 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){ wpLink.update(); e.preventDefault(); }); $('#wp-link-cancel').click( 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() { // Initialize the dialog if necessary (html mode). if ( ! inputs.dialog.data('wpdialog') ) { inputs.dialog.wpdialog({ title: wpLinkL10n.title, width: 480, height: 'auto', modal: true, dialogClass: 'wp-dialog', zIndex: 300000 }); } inputs.dialog.wpdialog('open'); }, isMCE : function() { return tinyMCEPopup && ( ed = tinyMCEPopup.editor ) && ! ed.isHidden(); }, refresh : function() { // Refresh rivers (clear links, check visibility) rivers.search.refresh(); rivers.recent.refresh(); if ( wpLink.isMCE() ) wpLink.mceRefresh(); else wpLink.setDefaultValues(); // Focus the URL field and highlight its contents. // If this is moved above the selection changes, // IE will show a flashing cursor over the dialog. inputs.url.focus()[0].select(); // Load the most recent results if this is the first time opening the panel. if ( ! rivers.recent.ul.children().length ) rivers.recent.ajax(); }, mceRefresh : function() { var e; ed = tinyMCEPopup.editor; tinyMCEPopup.restoreSelection(); // If link exists, select proper values. if ( e = ed.dom.getParent(ed.selection.getNode(), 'A') ) { // Set URL and description. inputs.url.val( e.href ); inputs.title.val( ed.dom.getAttrib(e, 'title') ); // Set open in new tab. if ( "_blank" == ed.dom.getAttrib(e, 'target') ) inputs.openInNewTab.prop('checked', true); // Update save prompt. inputs.submit.val( wpLinkL10n.update ); // If there's no link, set the default values. } else { wpLink.setDefaultValues(); } tinyMCEPopup.storeSelection(); }, close : function() { if ( wpLink.isMCE() ) tinyMCEPopup.close(); else inputs.dialog.wpdialog('close'); }, onClose: function() { if ( ! wpLink.isMCE() ) { wpLink.textarea().focus(); if ( wpLink.range ) { wpLink.range.moveToBookmark( wpLink.range.getBookmark() ); wpLink.range.select(); } } }, getAttrs : function() { return { href : inputs.url.val(), title : inputs.title.val(), target : inputs.openInNewTab.prop('checked') ? '_blank' : '' }; }, update : function() { if ( wpLink.isMCE() ) wpLink.mceUpdate(); else wpLink.htmlUpdate(); }, htmlUpdate : function() { var attrs, html, start, 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 // W3C if ( typeof textarea.selectionStart !== 'undefined' ) { start = textarea.selectionStart; end = textarea.selectionEnd; selection = textarea.value.substring( start, end ); html = html + selection + '</a>'; cursor = start + html.length; // If no next is selected, place the cursor inside the closing tag. if ( start == end ) cursor -= '</a>'.length; textarea.value = textarea.value.substring( 0, start ) + html + textarea.value.substring( end, textarea.value.length ); // Update cursor position textarea.selectionStart = textarea.selectionEnd = cursor; // IE // Note: If no text is selected, IE will not place the cursor // inside the closing tag. } else if ( document.selection && wpLink.range ) { textarea.focus(); wpLink.range.text = html + wpLink.range.text + '</a>'; wpLink.range.moveToBookmark( wpLink.range.getBookmark() ); wpLink.range.select(); wpLink.range = null; } 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("CreateLink", 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.siblings('img.waiting').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' : $('#_ajax_linking_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
(function() { tinymce.create('tinymce.plugins.wpLink', { /** * Initializes the plugin, this will be executed after the plugin has been created. * This call is done before the editor instance has finished it's initialization so use the onInit event * of the editor instance to intercept that event. * * @param {tinymce.Editor} ed Editor instance that the plugin is initialized in. * @param {string} url Absolute URL to where the plugin is located. */ init : function(ed, url) { var disabled = true; // Register the command so that it can be invoked by using tinyMCE.activeEditor.execCommand('mceExample'); ed.addCommand('WP_Link', function() { if ( disabled ) return; ed.windowManager.open({ id : 'wp-link', width : 480, height : "auto", wpDialog : true, title : ed.getLang('advlink.link_desc') }, { plugin_url : url // Plugin absolute URL }); }); // Register example button ed.addButton('link', { title : ed.getLang('advanced.link_desc'), cmd : 'WP_Link' }); ed.addShortcut('alt+shift+a', ed.getLang('advanced.link_desc'), 'WP_Link'); ed.onNodeChange.add(function(ed, cm, n, co) { disabled = co && n.nodeName != 'A'; }); }, /** * Returns information about the plugin as a name/value array. * The current keys are longname, author, authorurl, infourl and version. * * @return {Object} Name/value array containing information about the plugin. */ getInfo : function() { return { longname : 'WordPress Link Dialog', author : 'WordPress', authorurl : 'http://wordpress.org', infourl : '', version : "1.0" }; } }); // Register plugin tinymce.PluginManager.add('wplink', tinymce.plugins.wpLink); })();
JavaScript
/** * WordPress plugin. */ (function() { var DOM = tinymce.DOM; tinymce.create('tinymce.plugins.WordPress', { mceTout : 0, init : function(ed, url) { var t = this, tbId = ed.getParam('wordpress_adv_toolbar', 'toolbar2'), last = 0, moreHTML, nextpageHTML; moreHTML = '<img src="' + url + '/img/trans.gif" class="mceWPmore mceItemNoResize" title="'+ed.getLang('wordpress.wp_more_alt')+'" />'; nextpageHTML = '<img src="' + url + '/img/trans.gif" class="mceWPnextpage mceItemNoResize" title="'+ed.getLang('wordpress.wp_page_alt')+'" />'; if ( getUserSetting('hidetb', '0') == '1' ) ed.settings.wordpress_adv_hidden = 0; // Hides the specified toolbar and resizes the iframe ed.onPostRender.add(function() { var adv_toolbar = ed.controlManager.get(tbId); if ( ed.getParam('wordpress_adv_hidden', 1) && adv_toolbar ) { DOM.hide(adv_toolbar.id); t._resizeIframe(ed, tbId, 28); } }); // Register commands ed.addCommand('WP_More', function() { ed.execCommand('mceInsertContent', 0, moreHTML); }); ed.addCommand('WP_Page', function() { ed.execCommand('mceInsertContent', 0, nextpageHTML); }); ed.addCommand('WP_Help', function() { ed.windowManager.open({ url : tinymce.baseURL + '/wp-mce-help.php', width : 450, height : 420, inline : 1 }); }); ed.addCommand('WP_Adv', function() { var cm = ed.controlManager, id = cm.get(tbId).id; if ( 'undefined' == id ) return; if ( DOM.isHidden(id) ) { cm.setActive('wp_adv', 1); DOM.show(id); t._resizeIframe(ed, tbId, -28); ed.settings.wordpress_adv_hidden = 0; setUserSetting('hidetb', '1'); } else { cm.setActive('wp_adv', 0); DOM.hide(id); t._resizeIframe(ed, tbId, 28); ed.settings.wordpress_adv_hidden = 1; setUserSetting('hidetb', '0'); } }); // Register buttons ed.addButton('wp_more', { title : 'wordpress.wp_more_desc', cmd : 'WP_More' }); ed.addButton('wp_page', { title : 'wordpress.wp_page_desc', image : url + '/img/page.gif', cmd : 'WP_Page' }); ed.addButton('wp_help', { title : 'wordpress.wp_help_desc', cmd : 'WP_Help' }); ed.addButton('wp_adv', { title : 'wordpress.wp_adv_desc', cmd : 'WP_Adv' }); // Add Media buttons ed.addButton('add_media', { title : 'wordpress.add_media', image : url + '/img/media.gif', onclick : function() { tb_show('', tinymce.DOM.get('add_media').href); tinymce.DOM.setStyle( ['TB_overlay','TB_window','TB_load'], 'z-index', '999999' ); } }); ed.addButton('add_image', { title : 'wordpress.add_image', image : url + '/img/image.gif', onclick : function() { tb_show('', tinymce.DOM.get('add_image').href); tinymce.DOM.setStyle( ['TB_overlay','TB_window','TB_load'], 'z-index', '999999' ); } }); ed.addButton('add_video', { title : 'wordpress.add_video', image : url + '/img/video.gif', onclick : function() { tb_show('', tinymce.DOM.get('add_video').href); tinymce.DOM.setStyle( ['TB_overlay','TB_window','TB_load'], 'z-index', '999999' ); } }); ed.addButton('add_audio', { title : 'wordpress.add_audio', image : url + '/img/audio.gif', onclick : function() { tb_show('', tinymce.DOM.get('add_audio').href); tinymce.DOM.setStyle( ['TB_overlay','TB_window','TB_load'], 'z-index', '999999' ); } }); // Add Media buttons to fullscreen and handle align buttons for image captions ed.onBeforeExecCommand.add(function(ed, cmd, ui, val, o) { var DOM = tinymce.DOM, n, DL, DIV, cls, a, align; if ( 'mceFullScreen' == cmd ) { if ( 'mce_fullscreen' != ed.id && DOM.get('add_audio') && DOM.get('add_video') && DOM.get('add_image') && DOM.get('add_media') ) ed.settings.theme_advanced_buttons1 += ',|,add_image,add_video,add_audio,add_media'; } if ( 'JustifyLeft' == cmd || 'JustifyRight' == cmd || 'JustifyCenter' == cmd ) { n = ed.selection.getNode(); if ( n.nodeName == 'IMG' ) { align = cmd.substr(7).toLowerCase(); a = 'align' + align; DL = ed.dom.getParent(n, 'dl.wp-caption'); DIV = ed.dom.getParent(n, 'div.mceTemp'); if ( DL && DIV ) { cls = ed.dom.hasClass(DL, a) ? 'alignnone' : a; DL.className = DL.className.replace(/align[^ '"]+\s?/g, ''); ed.dom.addClass(DL, cls); if (cls == 'aligncenter') ed.dom.addClass(DIV, 'mceIEcenter'); else ed.dom.removeClass(DIV, 'mceIEcenter'); o.terminate = true; ed.execCommand('mceRepaint'); } else { if ( ed.dom.hasClass(n, a) ) ed.dom.addClass(n, 'alignnone'); else ed.dom.removeClass(n, 'alignnone'); } } } }); ed.onInit.add(function(ed) { // make sure these run last ed.onNodeChange.add( function(ed, cm, e) { var DL; if ( e.nodeName == 'IMG' ) { DL = ed.dom.getParent(e, 'dl.wp-caption'); } else if ( e.nodeName == 'DIV' && ed.dom.hasClass(e, 'mceTemp') ) { DL = e.firstChild; if ( ! ed.dom.hasClass(DL, 'wp-caption') ) DL = false; } if ( DL ) { if ( ed.dom.hasClass(DL, 'alignleft') ) cm.setActive('justifyleft', 1); else if ( ed.dom.hasClass(DL, 'alignright') ) cm.setActive('justifyright', 1); else if ( ed.dom.hasClass(DL, 'aligncenter') ) cm.setActive('justifycenter', 1); } }); if ( ed.id != 'wp_mce_fullscreen' ) ed.dom.addClass(ed.getBody(), 'wp-editor'); // remove invalid parent paragraphs when pasting HTML and/or switching to the HTML editor and back ed.onBeforeSetContent.add(function(ed, o) { if ( o.content ) { o.content = o.content.replace(/<p>\s*<(p|div|ul|ol|dl|table|blockquote|h[1-6]|fieldset|pre|address)( [^>]*)?>/gi, '<$1$2>'); o.content = o.content.replace(/<\/(p|div|ul|ol|dl|table|blockquote|h[1-6]|fieldset|pre|address)>\s*<\/p>/gi, '</$1>'); } }); }); // Word count if ( 'undefined' != typeof(jQuery) ) { ed.onKeyUp.add(function(ed, e) { var k = e.keyCode || e.charCode; if ( k == last ) return; if ( 13 == k || 8 == last || 46 == last ) jQuery(document).triggerHandler('wpcountwords', [ ed.getContent({format : 'raw'}) ]); last = k; }); }; // keep empty paragraphs :( ed.onSaveContent.addToTop(function(ed, o) { o.content = o.content.replace(/<p>(<br ?\/?>|\u00a0|\uFEFF)?<\/p>/g, '<p>&nbsp;</p>'); }); ed.onSaveContent.add(function(ed, o) { if ( typeof(switchEditors) == 'object' ) { if ( ed.isHidden() ) o.content = o.element.value; else o.content = switchEditors.pre_wpautop(o.content); } }); /* disable for now ed.onBeforeSetContent.add(function(ed, o) { o.content = t._setEmbed(o.content); }); ed.onPostProcess.add(function(ed, o) { if ( o.get ) o.content = t._getEmbed(o.content); }); */ // Add listeners to handle more break t._handleMoreBreak(ed, url); // Add custom shortcuts ed.addShortcut('alt+shift+c', ed.getLang('justifycenter_desc'), 'JustifyCenter'); ed.addShortcut('alt+shift+r', ed.getLang('justifyright_desc'), 'JustifyRight'); ed.addShortcut('alt+shift+l', ed.getLang('justifyleft_desc'), 'JustifyLeft'); ed.addShortcut('alt+shift+j', ed.getLang('justifyfull_desc'), 'JustifyFull'); ed.addShortcut('alt+shift+q', ed.getLang('blockquote_desc'), 'mceBlockQuote'); ed.addShortcut('alt+shift+u', ed.getLang('bullist_desc'), 'InsertUnorderedList'); ed.addShortcut('alt+shift+o', ed.getLang('numlist_desc'), 'InsertOrderedList'); ed.addShortcut('alt+shift+d', ed.getLang('striketrough_desc'), 'Strikethrough'); ed.addShortcut('alt+shift+n', ed.getLang('spellchecker.desc'), 'mceSpellCheck'); ed.addShortcut('alt+shift+a', ed.getLang('link_desc'), 'mceLink'); ed.addShortcut('alt+shift+s', ed.getLang('unlink_desc'), 'unlink'); ed.addShortcut('alt+shift+m', ed.getLang('image_desc'), 'mceImage'); ed.addShortcut('alt+shift+g', ed.getLang('fullscreen.desc'), 'mceFullScreen'); ed.addShortcut('alt+shift+z', ed.getLang('wp_adv_desc'), 'WP_Adv'); ed.addShortcut('alt+shift+h', ed.getLang('help_desc'), 'WP_Help'); ed.addShortcut('alt+shift+t', ed.getLang('wp_more_desc'), 'WP_More'); ed.addShortcut('alt+shift+p', ed.getLang('wp_page_desc'), 'WP_Page'); ed.addShortcut('ctrl+s', ed.getLang('save_desc'), function(){if('function'==typeof autosave)autosave();}); if ( tinymce.isWebKit ) { ed.addShortcut('alt+shift+b', ed.getLang('bold_desc'), 'Bold'); ed.addShortcut('alt+shift+i', ed.getLang('italic_desc'), 'Italic'); } ed.onInit.add(function(ed) { tinymce.dom.Event.add(ed.getWin(), 'scroll', function(e) { ed.plugins.wordpress._hideButtons(); }); tinymce.dom.Event.add(ed.getBody(), 'dragstart', function(e) { ed.plugins.wordpress._hideButtons(); }); }); ed.onBeforeExecCommand.add(function(ed, cmd, ui, val) { ed.plugins.wordpress._hideButtons(); }); ed.onSaveContent.add(function(ed, o) { ed.plugins.wordpress._hideButtons(); }); ed.onMouseDown.add(function(ed, e) { if ( e.target.nodeName != 'IMG' ) ed.plugins.wordpress._hideButtons(); }); }, getInfo : function() { return { longname : 'WordPress Plugin', author : 'WordPress', // add Moxiecode? authorurl : 'http://wordpress.org', infourl : 'http://wordpress.org', version : '3.0' }; }, // Internal functions _setEmbed : function(c) { return c.replace(/\[embed\]([\s\S]+?)\[\/embed\][\s\u00a0]*/g, function(a,b){ return '<img width="300" height="200" src="' + tinymce.baseURL + '/plugins/wordpress/img/trans.gif" class="wp-oembed mceItemNoResize" alt="'+b+'" title="'+b+'" />'; }); }, _getEmbed : function(c) { return c.replace(/<img[^>]+>/g, function(a) { if ( a.indexOf('class="wp-oembed') != -1 ) { var u = a.match(/alt="([^\"]+)"/); if ( u[1] ) a = '[embed]' + u[1] + '[/embed]'; } return a; }); }, _showButtons : function(n, id) { var ed = tinyMCE.activeEditor, p1, p2, vp, DOM = tinymce.DOM, X, Y; vp = ed.dom.getViewPort(ed.getWin()); p1 = DOM.getPos(ed.getContentAreaContainer()); p2 = ed.dom.getPos(n); X = Math.max(p2.x - vp.x, 0) + p1.x; Y = Math.max(p2.y - vp.y, 0) + p1.y; DOM.setStyles(id, { 'top' : Y+5+'px', 'left' : X+5+'px', 'display' : 'block' }); if ( this.mceTout ) clearTimeout(this.mceTout); this.mceTout = setTimeout( function(){ed.plugins.wordpress._hideButtons();}, 5000 ); }, _hideButtons : function() { if ( !this.mceTout ) return; if ( document.getElementById('wp_editbtns') ) tinymce.DOM.hide('wp_editbtns'); if ( document.getElementById('wp_gallerybtns') ) tinymce.DOM.hide('wp_gallerybtns'); clearTimeout(this.mceTout); this.mceTout = 0; }, // Resizes the iframe by a relative height value _resizeIframe : function(ed, tb_id, dy) { var ifr = ed.getContentAreaContainer().firstChild; DOM.setStyle(ifr, 'height', ifr.clientHeight + dy); // Resize iframe ed.theme.deltaHeight += dy; // For resize cookie }, _handleMoreBreak : function(ed, url) { var moreHTML, nextpageHTML; moreHTML = '<img src="' + url + '/img/trans.gif" alt="$1" class="mceWPmore mceItemNoResize" title="'+ed.getLang('wordpress.wp_more_alt')+'" />'; nextpageHTML = '<img src="' + url + '/img/trans.gif" class="mceWPnextpage mceItemNoResize" title="'+ed.getLang('wordpress.wp_page_alt')+'" />'; // Load plugin specific CSS into editor ed.onInit.add(function() { ed.dom.loadCSS(url + '/css/content.css'); }); // Display morebreak instead if img in element path ed.onPostRender.add(function() { if (ed.theme.onResolveName) { ed.theme.onResolveName.add(function(th, o) { if (o.node.nodeName == 'IMG') { if ( ed.dom.hasClass(o.node, 'mceWPmore') ) o.name = 'wpmore'; if ( ed.dom.hasClass(o.node, 'mceWPnextpage') ) o.name = 'wppage'; } }); } }); // Replace morebreak with images ed.onBeforeSetContent.add(function(ed, o) { if ( o.content ) { o.content = o.content.replace(/<!--more(.*?)-->/g, moreHTML); o.content = o.content.replace(/<!--nextpage-->/g, nextpageHTML); } }); // Replace images with morebreak ed.onPostProcess.add(function(ed, o) { if (o.get) o.content = o.content.replace(/<img[^>]+>/g, function(im) { if (im.indexOf('class="mceWPmore') !== -1) { var m, moretext = (m = im.match(/alt="(.*?)"/)) ? m[1] : ''; im = '<!--more'+moretext+'-->'; } if (im.indexOf('class="mceWPnextpage') !== -1) im = '<!--nextpage-->'; return im; }); }); // Set active buttons if user selected pagebreak or more break ed.onNodeChange.add(function(ed, cm, n) { cm.setActive('wp_page', n.nodeName === 'IMG' && ed.dom.hasClass(n, 'mceWPnextpage')); cm.setActive('wp_more', n.nodeName === 'IMG' && ed.dom.hasClass(n, 'mceWPmore')); }); } }); // Register plugin tinymce.PluginManager.add('wordpress', tinymce.plugins.WordPress); })();
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:"Horizontale 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 / Alt+Shift + B)", italic_desc:"Italic (Ctrl / Alt+Shift + 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", 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" }); 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:"Alternate Text" });
JavaScript
tinyMCEPopup.requireLangPack(); tinyMCEPopup.onInit.add(onLoadInit); function saveContent() { tinyMCEPopup.editor.setContent(document.getElementById('htmlSource').value, {source_view : true}); tinyMCEPopup.close(); } function onLoadInit() { tinyMCEPopup.resizeToInnerSize(); // Remove Gecko spellchecking if (tinymce.isGecko) document.body.spellcheck = tinyMCEPopup.editor.getParam("gecko_spellcheck"); document.getElementById('htmlSource').value = tinyMCEPopup.editor.getContent({source_view : true}); if (tinyMCEPopup.editor.getParam("theme_advanced_source_editor_wrap", true)) { setWrap('soft'); document.getElementById('wraped').checked = true; } resizeInputs(); } function setWrap(val) { var v, n, s = document.getElementById('htmlSource'); s.wrap = val; if (!tinymce.isIE) { v = s.value; n = s.cloneNode(false); n.setAttribute("wrap", val); s.parentNode.replaceChild(n, s); n.value = v; } } function toggleWordWrap(elm) { if (elm.checked) setWrap('soft'); else setWrap('off'); } function resizeInputs() { var vp = tinyMCEPopup.dom.getViewPort(window), el; el = document.getElementById('htmlSource'); if (el) { el.style.width = (vp.w - 20) + 'px'; el.style.height = (vp.h - 65) + 'px'; } }
JavaScript
/** * charmap.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ tinyMCEPopup.requireLangPack(); var charmap = [ ['&nbsp;', '&#160;', true, 'no-break space'], ['&amp;', '&#38;', true, 'ampersand'], ['&quot;', '&#34;', true, 'quotation mark'], // finance ['&cent;', '&#162;', true, 'cent sign'], ['&euro;', '&#8364;', true, 'euro sign'], ['&pound;', '&#163;', true, 'pound sign'], ['&yen;', '&#165;', true, 'yen sign'], // signs ['&copy;', '&#169;', true, 'copyright sign'], ['&reg;', '&#174;', true, 'registered sign'], ['&trade;', '&#8482;', true, 'trade mark sign'], ['&permil;', '&#8240;', true, 'per mille sign'], ['&micro;', '&#181;', true, 'micro sign'], ['&middot;', '&#183;', true, 'middle dot'], ['&bull;', '&#8226;', true, 'bullet'], ['&hellip;', '&#8230;', true, 'three dot leader'], ['&prime;', '&#8242;', true, 'minutes / feet'], ['&Prime;', '&#8243;', true, 'seconds / inches'], ['&sect;', '&#167;', true, 'section sign'], ['&para;', '&#182;', true, 'paragraph sign'], ['&szlig;', '&#223;', true, 'sharp s / ess-zed'], // quotations ['&lsaquo;', '&#8249;', true, 'single left-pointing angle quotation mark'], ['&rsaquo;', '&#8250;', true, 'single right-pointing angle quotation mark'], ['&laquo;', '&#171;', true, 'left pointing guillemet'], ['&raquo;', '&#187;', true, 'right pointing guillemet'], ['&lsquo;', '&#8216;', true, 'left single quotation mark'], ['&rsquo;', '&#8217;', true, 'right single quotation mark'], ['&ldquo;', '&#8220;', true, 'left double quotation mark'], ['&rdquo;', '&#8221;', true, 'right double quotation mark'], ['&sbquo;', '&#8218;', true, 'single low-9 quotation mark'], ['&bdquo;', '&#8222;', true, 'double low-9 quotation mark'], ['&lt;', '&#60;', true, 'less-than sign'], ['&gt;', '&#62;', true, 'greater-than sign'], ['&le;', '&#8804;', true, 'less-than or equal to'], ['&ge;', '&#8805;', true, 'greater-than or equal to'], ['&ndash;', '&#8211;', true, 'en dash'], ['&mdash;', '&#8212;', true, 'em dash'], ['&macr;', '&#175;', true, 'macron'], ['&oline;', '&#8254;', true, 'overline'], ['&curren;', '&#164;', true, 'currency sign'], ['&brvbar;', '&#166;', true, 'broken bar'], ['&uml;', '&#168;', true, 'diaeresis'], ['&iexcl;', '&#161;', true, 'inverted exclamation mark'], ['&iquest;', '&#191;', true, 'turned question mark'], ['&circ;', '&#710;', true, 'circumflex accent'], ['&tilde;', '&#732;', true, 'small tilde'], ['&deg;', '&#176;', true, 'degree sign'], ['&minus;', '&#8722;', true, 'minus sign'], ['&plusmn;', '&#177;', true, 'plus-minus sign'], ['&divide;', '&#247;', true, 'division sign'], ['&frasl;', '&#8260;', true, 'fraction slash'], ['&times;', '&#215;', true, 'multiplication sign'], ['&sup1;', '&#185;', true, 'superscript one'], ['&sup2;', '&#178;', true, 'superscript two'], ['&sup3;', '&#179;', true, 'superscript three'], ['&frac14;', '&#188;', true, 'fraction one quarter'], ['&frac12;', '&#189;', true, 'fraction one half'], ['&frac34;', '&#190;', true, 'fraction three quarters'], // math / logical ['&fnof;', '&#402;', true, 'function / florin'], ['&int;', '&#8747;', true, 'integral'], ['&sum;', '&#8721;', true, 'n-ary sumation'], ['&infin;', '&#8734;', true, 'infinity'], ['&radic;', '&#8730;', true, 'square root'], ['&sim;', '&#8764;', false,'similar to'], ['&cong;', '&#8773;', false,'approximately equal to'], ['&asymp;', '&#8776;', true, 'almost equal to'], ['&ne;', '&#8800;', true, 'not equal to'], ['&equiv;', '&#8801;', true, 'identical to'], ['&isin;', '&#8712;', false,'element of'], ['&notin;', '&#8713;', false,'not an element of'], ['&ni;', '&#8715;', false,'contains as member'], ['&prod;', '&#8719;', true, 'n-ary product'], ['&and;', '&#8743;', false,'logical and'], ['&or;', '&#8744;', false,'logical or'], ['&not;', '&#172;', true, 'not sign'], ['&cap;', '&#8745;', true, 'intersection'], ['&cup;', '&#8746;', false,'union'], ['&part;', '&#8706;', true, 'partial differential'], ['&forall;', '&#8704;', false,'for all'], ['&exist;', '&#8707;', false,'there exists'], ['&empty;', '&#8709;', false,'diameter'], ['&nabla;', '&#8711;', false,'backward difference'], ['&lowast;', '&#8727;', false,'asterisk operator'], ['&prop;', '&#8733;', false,'proportional to'], ['&ang;', '&#8736;', false,'angle'], // undefined ['&acute;', '&#180;', true, 'acute accent'], ['&cedil;', '&#184;', true, 'cedilla'], ['&ordf;', '&#170;', true, 'feminine ordinal indicator'], ['&ordm;', '&#186;', true, 'masculine ordinal indicator'], ['&dagger;', '&#8224;', true, 'dagger'], ['&Dagger;', '&#8225;', true, 'double dagger'], // alphabetical special chars ['&Agrave;', '&#192;', true, 'A - grave'], ['&Aacute;', '&#193;', true, 'A - acute'], ['&Acirc;', '&#194;', true, 'A - circumflex'], ['&Atilde;', '&#195;', true, 'A - tilde'], ['&Auml;', '&#196;', true, 'A - diaeresis'], ['&Aring;', '&#197;', true, 'A - ring above'], ['&AElig;', '&#198;', true, 'ligature AE'], ['&Ccedil;', '&#199;', true, 'C - cedilla'], ['&Egrave;', '&#200;', true, 'E - grave'], ['&Eacute;', '&#201;', true, 'E - acute'], ['&Ecirc;', '&#202;', true, 'E - circumflex'], ['&Euml;', '&#203;', true, 'E - diaeresis'], ['&Igrave;', '&#204;', true, 'I - grave'], ['&Iacute;', '&#205;', true, 'I - acute'], ['&Icirc;', '&#206;', true, 'I - circumflex'], ['&Iuml;', '&#207;', true, 'I - diaeresis'], ['&ETH;', '&#208;', true, 'ETH'], ['&Ntilde;', '&#209;', true, 'N - tilde'], ['&Ograve;', '&#210;', true, 'O - grave'], ['&Oacute;', '&#211;', true, 'O - acute'], ['&Ocirc;', '&#212;', true, 'O - circumflex'], ['&Otilde;', '&#213;', true, 'O - tilde'], ['&Ouml;', '&#214;', true, 'O - diaeresis'], ['&Oslash;', '&#216;', true, 'O - slash'], ['&OElig;', '&#338;', true, 'ligature OE'], ['&Scaron;', '&#352;', true, 'S - caron'], ['&Ugrave;', '&#217;', true, 'U - grave'], ['&Uacute;', '&#218;', true, 'U - acute'], ['&Ucirc;', '&#219;', true, 'U - circumflex'], ['&Uuml;', '&#220;', true, 'U - diaeresis'], ['&Yacute;', '&#221;', true, 'Y - acute'], ['&Yuml;', '&#376;', true, 'Y - diaeresis'], ['&THORN;', '&#222;', true, 'THORN'], ['&agrave;', '&#224;', true, 'a - grave'], ['&aacute;', '&#225;', true, 'a - acute'], ['&acirc;', '&#226;', true, 'a - circumflex'], ['&atilde;', '&#227;', true, 'a - tilde'], ['&auml;', '&#228;', true, 'a - diaeresis'], ['&aring;', '&#229;', true, 'a - ring above'], ['&aelig;', '&#230;', true, 'ligature ae'], ['&ccedil;', '&#231;', true, 'c - cedilla'], ['&egrave;', '&#232;', true, 'e - grave'], ['&eacute;', '&#233;', true, 'e - acute'], ['&ecirc;', '&#234;', true, 'e - circumflex'], ['&euml;', '&#235;', true, 'e - diaeresis'], ['&igrave;', '&#236;', true, 'i - grave'], ['&iacute;', '&#237;', true, 'i - acute'], ['&icirc;', '&#238;', true, 'i - circumflex'], ['&iuml;', '&#239;', true, 'i - diaeresis'], ['&eth;', '&#240;', true, 'eth'], ['&ntilde;', '&#241;', true, 'n - tilde'], ['&ograve;', '&#242;', true, 'o - grave'], ['&oacute;', '&#243;', true, 'o - acute'], ['&ocirc;', '&#244;', true, 'o - circumflex'], ['&otilde;', '&#245;', true, 'o - tilde'], ['&ouml;', '&#246;', true, 'o - diaeresis'], ['&oslash;', '&#248;', true, 'o slash'], ['&oelig;', '&#339;', true, 'ligature oe'], ['&scaron;', '&#353;', true, 's - caron'], ['&ugrave;', '&#249;', true, 'u - grave'], ['&uacute;', '&#250;', true, 'u - acute'], ['&ucirc;', '&#251;', true, 'u - circumflex'], ['&uuml;', '&#252;', true, 'u - diaeresis'], ['&yacute;', '&#253;', true, 'y - acute'], ['&thorn;', '&#254;', true, 'thorn'], ['&yuml;', '&#255;', true, 'y - diaeresis'], ['&Alpha;', '&#913;', true, 'Alpha'], ['&Beta;', '&#914;', true, 'Beta'], ['&Gamma;', '&#915;', true, 'Gamma'], ['&Delta;', '&#916;', true, 'Delta'], ['&Epsilon;', '&#917;', true, 'Epsilon'], ['&Zeta;', '&#918;', true, 'Zeta'], ['&Eta;', '&#919;', true, 'Eta'], ['&Theta;', '&#920;', true, 'Theta'], ['&Iota;', '&#921;', true, 'Iota'], ['&Kappa;', '&#922;', true, 'Kappa'], ['&Lambda;', '&#923;', true, 'Lambda'], ['&Mu;', '&#924;', true, 'Mu'], ['&Nu;', '&#925;', true, 'Nu'], ['&Xi;', '&#926;', true, 'Xi'], ['&Omicron;', '&#927;', true, 'Omicron'], ['&Pi;', '&#928;', true, 'Pi'], ['&Rho;', '&#929;', true, 'Rho'], ['&Sigma;', '&#931;', true, 'Sigma'], ['&Tau;', '&#932;', true, 'Tau'], ['&Upsilon;', '&#933;', true, 'Upsilon'], ['&Phi;', '&#934;', true, 'Phi'], ['&Chi;', '&#935;', true, 'Chi'], ['&Psi;', '&#936;', true, 'Psi'], ['&Omega;', '&#937;', true, 'Omega'], ['&alpha;', '&#945;', true, 'alpha'], ['&beta;', '&#946;', true, 'beta'], ['&gamma;', '&#947;', true, 'gamma'], ['&delta;', '&#948;', true, 'delta'], ['&epsilon;', '&#949;', true, 'epsilon'], ['&zeta;', '&#950;', true, 'zeta'], ['&eta;', '&#951;', true, 'eta'], ['&theta;', '&#952;', true, 'theta'], ['&iota;', '&#953;', true, 'iota'], ['&kappa;', '&#954;', true, 'kappa'], ['&lambda;', '&#955;', true, 'lambda'], ['&mu;', '&#956;', true, 'mu'], ['&nu;', '&#957;', true, 'nu'], ['&xi;', '&#958;', true, 'xi'], ['&omicron;', '&#959;', true, 'omicron'], ['&pi;', '&#960;', true, 'pi'], ['&rho;', '&#961;', true, 'rho'], ['&sigmaf;', '&#962;', true, 'final sigma'], ['&sigma;', '&#963;', true, 'sigma'], ['&tau;', '&#964;', true, 'tau'], ['&upsilon;', '&#965;', true, 'upsilon'], ['&phi;', '&#966;', true, 'phi'], ['&chi;', '&#967;', true, 'chi'], ['&psi;', '&#968;', true, 'psi'], ['&omega;', '&#969;', true, 'omega'], // symbols ['&alefsym;', '&#8501;', false,'alef symbol'], ['&piv;', '&#982;', false,'pi symbol'], ['&real;', '&#8476;', false,'real part symbol'], ['&thetasym;','&#977;', false,'theta symbol'], ['&upsih;', '&#978;', false,'upsilon - hook symbol'], ['&weierp;', '&#8472;', false,'Weierstrass p'], ['&image;', '&#8465;', false,'imaginary part'], // arrows ['&larr;', '&#8592;', true, 'leftwards arrow'], ['&uarr;', '&#8593;', true, 'upwards arrow'], ['&rarr;', '&#8594;', true, 'rightwards arrow'], ['&darr;', '&#8595;', true, 'downwards arrow'], ['&harr;', '&#8596;', true, 'left right arrow'], ['&crarr;', '&#8629;', false,'carriage return'], ['&lArr;', '&#8656;', false,'leftwards double arrow'], ['&uArr;', '&#8657;', false,'upwards double arrow'], ['&rArr;', '&#8658;', false,'rightwards double arrow'], ['&dArr;', '&#8659;', false,'downwards double arrow'], ['&hArr;', '&#8660;', false,'left right double arrow'], ['&there4;', '&#8756;', false,'therefore'], ['&sub;', '&#8834;', false,'subset of'], ['&sup;', '&#8835;', false,'superset of'], ['&nsub;', '&#8836;', false,'not a subset of'], ['&sube;', '&#8838;', false,'subset of or equal to'], ['&supe;', '&#8839;', false,'superset of or equal to'], ['&oplus;', '&#8853;', false,'circled plus'], ['&otimes;', '&#8855;', false,'circled times'], ['&perp;', '&#8869;', false,'perpendicular'], ['&sdot;', '&#8901;', false,'dot operator'], ['&lceil;', '&#8968;', false,'left ceiling'], ['&rceil;', '&#8969;', false,'right ceiling'], ['&lfloor;', '&#8970;', false,'left floor'], ['&rfloor;', '&#8971;', false,'right floor'], ['&lang;', '&#9001;', false,'left-pointing angle bracket'], ['&rang;', '&#9002;', false,'right-pointing angle bracket'], ['&loz;', '&#9674;', true, 'lozenge'], ['&spades;', '&#9824;', true, 'black spade suit'], ['&clubs;', '&#9827;', true, 'black club suit'], ['&hearts;', '&#9829;', true, 'black heart suit'], ['&diams;', '&#9830;', true, 'black diamond suit'], ['&ensp;', '&#8194;', false,'en space'], ['&emsp;', '&#8195;', false,'em space'], ['&thinsp;', '&#8201;', false,'thin space'], ['&zwnj;', '&#8204;', false,'zero width non-joiner'], ['&zwj;', '&#8205;', false,'zero width joiner'], ['&lrm;', '&#8206;', false,'left-to-right mark'], ['&rlm;', '&#8207;', false,'right-to-left mark'], ['&shy;', '&#173;', false,'soft hyphen'] ]; tinyMCEPopup.onInit.add(function() { tinyMCEPopup.dom.setHTML('charmapView', renderCharMapHTML()); addKeyboardNavigation(); }); function addKeyboardNavigation(){ var tableElm, cells, settings; cells = tinyMCEPopup.dom.select(".charmaplink", "charmapgroup"); settings ={ root: "charmapgroup", items: cells }; tinyMCEPopup.editor.windowManager.createInstance('tinymce.ui.KeyboardNavigation', settings, tinyMCEPopup.dom); } function renderCharMapHTML() { var charsPerRow = 20, tdWidth=20, tdHeight=20, i; var html = '<div id="charmapgroup" aria-labelledby="charmap_label" tabindex="0" role="listbox">'+ '<table role="presentation" border="0" cellspacing="1" cellpadding="0" width="' + (tdWidth*charsPerRow) + '"><tr height="' + tdHeight + '">'; var cols=-1; for (i=0; i<charmap.length; i++) { var previewCharFn; if (charmap[i][2]==true) { cols++; previewCharFn = 'previewChar(\'' + charmap[i][1].substring(1,charmap[i][1].length) + '\',\'' + charmap[i][0].substring(1,charmap[i][0].length) + '\',\'' + charmap[i][3] + '\');'; html += '' + '<td class="charmap">' + '<a class="charmaplink" role="button" onmouseover="'+previewCharFn+'" onfocus="'+previewCharFn+'" href="javascript:void(0)" onclick="insertChar(\'' + charmap[i][1].substring(2,charmap[i][1].length-1) + '\');" onclick="return false;" onmousedown="return false;" title="' + charmap[i][3] + '">' + charmap[i][1] + '</a></td>'; if ((cols+1) % charsPerRow == 0) html += '</tr><tr height="' + tdHeight + '">'; } } if (cols % charsPerRow > 0) { var padd = charsPerRow - (cols % charsPerRow); for (var i=0; i<padd-1; i++) html += '<td width="' + tdWidth + '" height="' + tdHeight + '" class="charmap">&nbsp;</td>'; } html += '</tr></table></div>'; html = html.replace(/<tr height="20"><\/tr>/g, ''); return html; } function insertChar(chr) { tinyMCEPopup.execCommand('mceInsertContent', false, '&#' + chr + ';'); // Refocus in window if (tinyMCEPopup.isWindow) window.focus(); tinyMCEPopup.editor.focus(); tinyMCEPopup.close(); } function previewChar(codeA, codeB, codeN) { var elmA = document.getElementById('codeA'); var elmB = document.getElementById('codeB'); var elmV = document.getElementById('codeV'); var elmN = document.getElementById('codeN'); if (codeA=='#160;') { elmV.innerHTML = '__'; } else { elmV.innerHTML = '&' + codeA; } elmB.innerHTML = '&amp;' + codeA; elmA.innerHTML = '&amp;' + codeB; elmN.innerHTML = codeN; }
JavaScript
tinyMCEPopup.requireLangPack(); var AnchorDialog = { init : function(ed) { var action, elm, f = document.forms[0]; this.editor = ed; elm = ed.dom.getParent(ed.selection.getNode(), 'A'); v = ed.dom.getAttrib(elm, 'name'); if (v) { this.action = 'update'; f.anchorName.value = v; } f.insert.value = ed.getLang(elm ? 'update' : 'insert'); }, update : function() { var ed = this.editor, elm, name = document.forms[0].anchorName.value; if (!name || !/^[a-z][a-z0-9\-\_:\.]*$/i.test(name)) { tinyMCEPopup.alert('advanced_dlg.anchor_invalid'); return; } tinyMCEPopup.restoreSelection(); if (this.action != 'update') ed.selection.collapse(1); elm = ed.dom.getParent(ed.selection.getNode(), 'A'); if (elm) elm.name = name; else ed.execCommand('mceInsertContent', 0, ed.dom.createHTML('a', {name : name, 'class' : 'mceItemAnchor'}, '')); tinyMCEPopup.close(); } }; tinyMCEPopup.onInit.add(AnchorDialog.init, AnchorDialog);
JavaScript
var ImageDialog = { preInit : function() { var url; tinyMCEPopup.requireLangPack(); if (url = tinyMCEPopup.getParam("external_image_list_url")) document.write('<script language="javascript" type="text/javascript" src="' + tinyMCEPopup.editor.documentBaseURI.toAbsolute(url) + '"></script>'); }, init : function() { var f = document.forms[0], ed = tinyMCEPopup.editor; // Setup browse button document.getElementById('srcbrowsercontainer').innerHTML = getBrowserHTML('srcbrowser','src','image','theme_advanced_image'); if (isVisible('srcbrowser')) document.getElementById('src').style.width = '180px'; e = ed.selection.getNode(); this.fillFileList('image_list', 'tinyMCEImageList'); if (e.nodeName == 'IMG') { f.src.value = ed.dom.getAttrib(e, 'src'); f.alt.value = ed.dom.getAttrib(e, 'alt'); f.border.value = this.getAttrib(e, 'border'); f.vspace.value = this.getAttrib(e, 'vspace'); f.hspace.value = this.getAttrib(e, 'hspace'); f.width.value = ed.dom.getAttrib(e, 'width'); f.height.value = ed.dom.getAttrib(e, 'height'); f.insert.value = ed.getLang('update'); this.styleVal = ed.dom.getAttrib(e, 'style'); selectByValue(f, 'image_list', f.src.value); selectByValue(f, 'align', this.getAttrib(e, 'align')); this.updateStyle(); } }, fillFileList : function(id, l) { var dom = tinyMCEPopup.dom, lst = dom.get(id), v, cl; l = window[l]; if (l && l.length > 0) { lst.options[lst.options.length] = new Option('', ''); tinymce.each(l, function(o) { lst.options[lst.options.length] = new Option(o[0], o[1]); }); } else dom.remove(dom.getParent(id, 'tr')); }, update : function() { var f = document.forms[0], nl = f.elements, ed = tinyMCEPopup.editor, args = {}, el; tinyMCEPopup.restoreSelection(); if (f.src.value === '') { if (ed.selection.getNode().nodeName == 'IMG') { ed.dom.remove(ed.selection.getNode()); ed.execCommand('mceRepaint'); } tinyMCEPopup.close(); return; } if (!ed.settings.inline_styles) { args = tinymce.extend(args, { vspace : nl.vspace.value, hspace : nl.hspace.value, border : nl.border.value, align : getSelectValue(f, 'align') }); } else args.style = this.styleVal; tinymce.extend(args, { src : f.src.value.replace(/ /g, '%20'), alt : f.alt.value, width : f.width.value, height : f.height.value, 'class' : f.class_name.value }); el = ed.selection.getNode(); if (el && el.nodeName == 'IMG') { ed.dom.setAttribs(el, args); tinyMCEPopup.editor.execCommand('mceRepaint'); tinyMCEPopup.editor.focus(); } else { ed.execCommand('mceInsertContent', false, '<img id="__mce_tmp" />', {skip_undo : 1}); ed.dom.setAttribs('__mce_tmp', args); ed.dom.setAttrib('__mce_tmp', 'id', ''); ed.undoManager.add(); } tinyMCEPopup.close(); }, updateStyle : function() { var dom = tinyMCEPopup.dom, st, v, cls, oldcls, rep, f = document.forms[0]; if (tinyMCEPopup.editor.settings.inline_styles) { st = tinyMCEPopup.dom.parseStyle(this.styleVal); // Handle align v = getSelectValue(f, 'align'); cls = f.class_name.value || ''; cls = cls ? cls.replace(/alignright\s*|alignleft\s*|aligncenter\s*/g, '') : ''; cls = cls ? cls.replace(/^\s*(.+?)\s*$/, '$1') : ''; if (v) { if (v == 'left' || v == 'right') { st['float'] = v; delete st['vertical-align']; oldcls = cls ? ' '+cls : ''; f.class_name.value = 'align' + v + oldcls; } else { st['vertical-align'] = v; delete st['float']; f.class_name.value = cls; } } else { delete st['float']; delete st['vertical-align']; f.class_name.value = cls; } // Handle border v = f.border.value; if (v || v == '0') { if (v == '0') st['border'] = '0'; else st['border'] = v + 'px solid black'; } else delete st['border']; // Handle hspace v = f.hspace.value; if (v) { delete st['margin']; st['margin-left'] = v + 'px'; st['margin-right'] = v + 'px'; } else { delete st['margin-left']; delete st['margin-right']; } // Handle vspace v = f.vspace.value; if (v) { delete st['margin']; st['margin-top'] = v + 'px'; st['margin-bottom'] = v + 'px'; } else { delete st['margin-top']; delete st['margin-bottom']; } // Merge st = tinyMCEPopup.dom.parseStyle(dom.serializeStyle(st), 'img'); this.styleVal = dom.serializeStyle(st, 'img'); } }, getAttrib : function(e, at) { var ed = tinyMCEPopup.editor, dom = ed.dom, v, v2; if (ed.settings.inline_styles) { switch (at) { case 'align': if (v = dom.getStyle(e, 'float')) return v; if (v = dom.getStyle(e, 'vertical-align')) return v; break; case 'hspace': v = dom.getStyle(e, 'margin-left') v2 = dom.getStyle(e, 'margin-right'); if (v && v == v2) return parseInt(v.replace(/[^0-9]/g, '')); break; case 'vspace': v = dom.getStyle(e, 'margin-top') v2 = dom.getStyle(e, 'margin-bottom'); if (v && v == v2) return parseInt(v.replace(/[^0-9]/g, '')); break; case 'border': v = 0; tinymce.each(['top', 'right', 'bottom', 'left'], function(sv) { sv = dom.getStyle(e, 'border-' + sv + '-width'); // False or not the same as prev if (!sv || (sv != v && v !== 0)) { v = 0; return false; } if (sv) v = sv; }); if (v) return parseInt(v.replace(/[^0-9]/g, '')); break; } } if (v = dom.getAttrib(e, at)) return v; return ''; }, resetImageData : function() { var f = document.forms[0]; f.width.value = f.height.value = ""; }, updateImageData : function() { var f = document.forms[0], t = ImageDialog; if (f.width.value == "") f.width.value = t.preloadImg.width; if (f.height.value == "") f.height.value = t.preloadImg.height; }, getImageData : function() { var f = document.forms[0]; this.preloadImg = new Image(); this.preloadImg.onload = this.updateImageData; this.preloadImg.onerror = this.resetImageData; this.preloadImg.src = tinyMCEPopup.editor.documentBaseURI.toAbsolute(f.src.value); } }; ImageDialog.preInit(); tinyMCEPopup.onInit.add(ImageDialog.init, ImageDialog);
JavaScript
tinyMCEPopup.requireLangPack(); var LinkDialog = { preInit : function() { var url; if (url = tinyMCEPopup.getParam("external_link_list_url")) document.write('<script language="javascript" type="text/javascript" src="' + tinyMCEPopup.editor.documentBaseURI.toAbsolute(url) + '"></script>'); }, init : function() { var f = document.forms[0], ed = tinyMCEPopup.editor; // Setup browse button document.getElementById('hrefbrowsercontainer').innerHTML = getBrowserHTML('hrefbrowser', 'href', 'file', 'theme_advanced_link'); if (isVisible('hrefbrowser')) document.getElementById('href').style.width = '180px'; this.fillClassList('class_list'); this.fillFileList('link_list', 'tinyMCELinkList'); this.fillTargetList('target_list'); if (e = ed.dom.getParent(ed.selection.getNode(), 'A')) { f.href.value = ed.dom.getAttrib(e, 'href'); f.linktitle.value = ed.dom.getAttrib(e, 'title'); f.insert.value = ed.getLang('update'); selectByValue(f, 'link_list', f.href.value); selectByValue(f, 'target_list', ed.dom.getAttrib(e, 'target')); selectByValue(f, 'class_list', ed.dom.getAttrib(e, 'class')); } }, update : function() { var f = document.forms[0], ed = tinyMCEPopup.editor, e, b, href = f.href.value.replace(/ /g, '%20'); tinyMCEPopup.restoreSelection(); e = ed.dom.getParent(ed.selection.getNode(), 'A'); // Remove element if there is no href if (!f.href.value) { if (e) { b = ed.selection.getBookmark(); ed.dom.remove(e, 1); ed.selection.moveToBookmark(b); tinyMCEPopup.execCommand("mceEndUndoLevel"); tinyMCEPopup.close(); return; } } // Create new anchor elements 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, { href : href, title : f.linktitle.value, target : f.target_list ? getSelectValue(f, "target_list") : null, 'class' : f.class_list ? getSelectValue(f, "class_list") : null }); } }); } else { ed.dom.setAttribs(e, { href : href, title : f.linktitle.value, target : f.target_list ? getSelectValue(f, "target_list") : null, 'class' : f.class_list ? getSelectValue(f, "class_list") : null }); } // Don't move caret if selection was image if (e.childNodes.length != 1 || e.firstChild.nodeName != 'IMG') { ed.focus(); ed.selection.select(e); ed.selection.collapse(0); tinyMCEPopup.storeSelection(); } tinyMCEPopup.execCommand("mceEndUndoLevel"); tinyMCEPopup.close(); }, checkPrefix : function(n) { if (n.value && Validator.isEmail(n) && !/^\s*mailto:/i.test(n.value) && confirm(tinyMCEPopup.getLang('advanced_dlg.link_is_email'))) n.value = 'mailto:' + n.value; if (/^\s*www\./i.test(n.value) && confirm(tinyMCEPopup.getLang('advanced_dlg.link_is_external'))) n.value = 'http://' + n.value; }, fillFileList : function(id, l) { var dom = tinyMCEPopup.dom, lst = dom.get(id), v, cl; l = window[l]; if (l && l.length > 0) { lst.options[lst.options.length] = new Option('', ''); tinymce.each(l, function(o) { lst.options[lst.options.length] = new Option(o[0], o[1]); }); } else dom.remove(dom.getParent(id, 'tr')); }, fillClassList : function(id) { var dom = tinyMCEPopup.dom, lst = dom.get(id), v, cl; if (v = tinyMCEPopup.getParam('theme_advanced_styles')) { cl = []; tinymce.each(v.split(';'), function(v) { var p = v.split('='); cl.push({'title' : p[0], 'class' : p[1]}); }); } else cl = tinyMCEPopup.editor.dom.getClasses(); if (cl.length > 0) { lst.options[lst.options.length] = new Option(tinyMCEPopup.getLang('not_set'), ''); tinymce.each(cl, function(o) { lst.options[lst.options.length] = new Option(o.title || o['class'], o['class']); }); } else dom.remove(dom.getParent(id, 'tr')); }, fillTargetList : function(id) { var dom = tinyMCEPopup.dom, lst = dom.get(id), v; lst.options[lst.options.length] = new Option(tinyMCEPopup.getLang('not_set'), ''); lst.options[lst.options.length] = new Option(tinyMCEPopup.getLang('advanced_dlg.link_target_same'), '_self'); lst.options[lst.options.length] = new Option(tinyMCEPopup.getLang('advanced_dlg.link_target_blank'), '_blank'); if (v = tinyMCEPopup.getParam('theme_advanced_link_targets')) { tinymce.each(v.split(','), function(v) { v = v.split('='); lst.options[lst.options.length] = new Option(v[0], v[1]); }); } } }; LinkDialog.preInit(); tinyMCEPopup.onInit.add(LinkDialog.init, LinkDialog);
JavaScript
tinyMCEPopup.requireLangPack(); function init() { var ed, tcont; tinyMCEPopup.resizeToInnerSize(); ed = tinyMCEPopup.editor; // Give FF some time window.setTimeout(insertHelpIFrame, 10); tcont = document.getElementById('plugintablecontainer'); document.getElementById('plugins_tab').style.display = 'none'; var html = ""; html += '<table id="plugintable">'; html += '<thead>'; html += '<tr>'; html += '<td>' + ed.getLang('advanced_dlg.about_plugin') + '</td>'; html += '<td>' + ed.getLang('advanced_dlg.about_author') + '</td>'; html += '<td>' + ed.getLang('advanced_dlg.about_version') + '</td>'; html += '</tr>'; html += '</thead>'; html += '<tbody>'; tinymce.each(ed.plugins, function(p, n) { var info; if (!p.getInfo) return; html += '<tr>'; info = p.getInfo(); if (info.infourl != null && info.infourl != '') html += '<td width="50%" title="' + n + '"><a href="' + info.infourl + '" target="_blank">' + info.longname + '</a></td>'; else html += '<td width="50%" title="' + n + '">' + info.longname + '</td>'; if (info.authorurl != null && info.authorurl != '') html += '<td width="35%"><a href="' + info.authorurl + '" target="_blank">' + info.author + '</a></td>'; else html += '<td width="35%">' + info.author + '</td>'; html += '<td width="15%">' + info.version + '</td>'; html += '</tr>'; document.getElementById('plugins_tab').style.display = ''; }); html += '</tbody>'; html += '</table>'; tcont.innerHTML = html; tinyMCEPopup.dom.get('version').innerHTML = tinymce.majorVersion + "." + tinymce.minorVersion; tinyMCEPopup.dom.get('date').innerHTML = tinymce.releaseDate; } function insertHelpIFrame() { var html; if (tinyMCEPopup.getParam('docs_url')) { html = '<iframe width="100%" height="300" src="' + tinyMCEPopup.editor.baseURI.toAbsolute(tinyMCEPopup.getParam('docs_url')) + '"></iframe>'; document.getElementById('iframecontainer').innerHTML = html; document.getElementById('help_tab').style.display = 'block'; document.getElementById('help_tab').setAttribute("aria-hidden", "false"); } } tinyMCEPopup.onInit.add(init);
JavaScript
tinyMCEPopup.requireLangPack(); var detail = 50, strhex = "0123456789ABCDEF", i, isMouseDown = false, isMouseOver = false; var colors = [ "#000000","#000033","#000066","#000099","#0000cc","#0000ff","#330000","#330033", "#330066","#330099","#3300cc","#3300ff","#660000","#660033","#660066","#660099", "#6600cc","#6600ff","#990000","#990033","#990066","#990099","#9900cc","#9900ff", "#cc0000","#cc0033","#cc0066","#cc0099","#cc00cc","#cc00ff","#ff0000","#ff0033", "#ff0066","#ff0099","#ff00cc","#ff00ff","#003300","#003333","#003366","#003399", "#0033cc","#0033ff","#333300","#333333","#333366","#333399","#3333cc","#3333ff", "#663300","#663333","#663366","#663399","#6633cc","#6633ff","#993300","#993333", "#993366","#993399","#9933cc","#9933ff","#cc3300","#cc3333","#cc3366","#cc3399", "#cc33cc","#cc33ff","#ff3300","#ff3333","#ff3366","#ff3399","#ff33cc","#ff33ff", "#006600","#006633","#006666","#006699","#0066cc","#0066ff","#336600","#336633", "#336666","#336699","#3366cc","#3366ff","#666600","#666633","#666666","#666699", "#6666cc","#6666ff","#996600","#996633","#996666","#996699","#9966cc","#9966ff", "#cc6600","#cc6633","#cc6666","#cc6699","#cc66cc","#cc66ff","#ff6600","#ff6633", "#ff6666","#ff6699","#ff66cc","#ff66ff","#009900","#009933","#009966","#009999", "#0099cc","#0099ff","#339900","#339933","#339966","#339999","#3399cc","#3399ff", "#669900","#669933","#669966","#669999","#6699cc","#6699ff","#999900","#999933", "#999966","#999999","#9999cc","#9999ff","#cc9900","#cc9933","#cc9966","#cc9999", "#cc99cc","#cc99ff","#ff9900","#ff9933","#ff9966","#ff9999","#ff99cc","#ff99ff", "#00cc00","#00cc33","#00cc66","#00cc99","#00cccc","#00ccff","#33cc00","#33cc33", "#33cc66","#33cc99","#33cccc","#33ccff","#66cc00","#66cc33","#66cc66","#66cc99", "#66cccc","#66ccff","#99cc00","#99cc33","#99cc66","#99cc99","#99cccc","#99ccff", "#cccc00","#cccc33","#cccc66","#cccc99","#cccccc","#ccccff","#ffcc00","#ffcc33", "#ffcc66","#ffcc99","#ffcccc","#ffccff","#00ff00","#00ff33","#00ff66","#00ff99", "#00ffcc","#00ffff","#33ff00","#33ff33","#33ff66","#33ff99","#33ffcc","#33ffff", "#66ff00","#66ff33","#66ff66","#66ff99","#66ffcc","#66ffff","#99ff00","#99ff33", "#99ff66","#99ff99","#99ffcc","#99ffff","#ccff00","#ccff33","#ccff66","#ccff99", "#ccffcc","#ccffff","#ffff00","#ffff33","#ffff66","#ffff99","#ffffcc","#ffffff" ]; var named = { '#F0F8FF':'Alice Blue','#FAEBD7':'Antique White','#00FFFF':'Aqua','#7FFFD4':'Aquamarine','#F0FFFF':'Azure','#F5F5DC':'Beige', '#FFE4C4':'Bisque','#000000':'Black','#FFEBCD':'Blanched Almond','#0000FF':'Blue','#8A2BE2':'Blue Violet','#A52A2A':'Brown', '#DEB887':'Burly Wood','#5F9EA0':'Cadet Blue','#7FFF00':'Chartreuse','#D2691E':'Chocolate','#FF7F50':'Coral','#6495ED':'Cornflower Blue', '#FFF8DC':'Cornsilk','#DC143C':'Crimson','#00FFFF':'Cyan','#00008B':'Dark Blue','#008B8B':'Dark Cyan','#B8860B':'Dark Golden Rod', '#A9A9A9':'Dark Gray','#A9A9A9':'Dark Grey','#006400':'Dark Green','#BDB76B':'Dark Khaki','#8B008B':'Dark Magenta','#556B2F':'Dark Olive Green', '#FF8C00':'Darkorange','#9932CC':'Dark Orchid','#8B0000':'Dark Red','#E9967A':'Dark Salmon','#8FBC8F':'Dark Sea Green','#483D8B':'Dark Slate Blue', '#2F4F4F':'Dark Slate Gray','#2F4F4F':'Dark Slate Grey','#00CED1':'Dark Turquoise','#9400D3':'Dark Violet','#FF1493':'Deep Pink','#00BFFF':'Deep Sky Blue', '#696969':'Dim Gray','#696969':'Dim Grey','#1E90FF':'Dodger Blue','#B22222':'Fire Brick','#FFFAF0':'Floral White','#228B22':'Forest Green', '#FF00FF':'Fuchsia','#DCDCDC':'Gainsboro','#F8F8FF':'Ghost White','#FFD700':'Gold','#DAA520':'Golden Rod','#808080':'Gray','#808080':'Grey', '#008000':'Green','#ADFF2F':'Green Yellow','#F0FFF0':'Honey Dew','#FF69B4':'Hot Pink','#CD5C5C':'Indian Red','#4B0082':'Indigo','#FFFFF0':'Ivory', '#F0E68C':'Khaki','#E6E6FA':'Lavender','#FFF0F5':'Lavender Blush','#7CFC00':'Lawn Green','#FFFACD':'Lemon Chiffon','#ADD8E6':'Light Blue', '#F08080':'Light Coral','#E0FFFF':'Light Cyan','#FAFAD2':'Light Golden Rod Yellow','#D3D3D3':'Light Gray','#D3D3D3':'Light Grey','#90EE90':'Light Green', '#FFB6C1':'Light Pink','#FFA07A':'Light Salmon','#20B2AA':'Light Sea Green','#87CEFA':'Light Sky Blue','#778899':'Light Slate Gray','#778899':'Light Slate Grey', '#B0C4DE':'Light Steel Blue','#FFFFE0':'Light Yellow','#00FF00':'Lime','#32CD32':'Lime Green','#FAF0E6':'Linen','#FF00FF':'Magenta','#800000':'Maroon', '#66CDAA':'Medium Aqua Marine','#0000CD':'Medium Blue','#BA55D3':'Medium Orchid','#9370D8':'Medium Purple','#3CB371':'Medium Sea Green','#7B68EE':'Medium Slate Blue', '#00FA9A':'Medium Spring Green','#48D1CC':'Medium Turquoise','#C71585':'Medium Violet Red','#191970':'Midnight Blue','#F5FFFA':'Mint Cream','#FFE4E1':'Misty Rose','#FFE4B5':'Moccasin', '#FFDEAD':'Navajo White','#000080':'Navy','#FDF5E6':'Old Lace','#808000':'Olive','#6B8E23':'Olive Drab','#FFA500':'Orange','#FF4500':'Orange Red','#DA70D6':'Orchid', '#EEE8AA':'Pale Golden Rod','#98FB98':'Pale Green','#AFEEEE':'Pale Turquoise','#D87093':'Pale Violet Red','#FFEFD5':'Papaya Whip','#FFDAB9':'Peach Puff', '#CD853F':'Peru','#FFC0CB':'Pink','#DDA0DD':'Plum','#B0E0E6':'Powder Blue','#800080':'Purple','#FF0000':'Red','#BC8F8F':'Rosy Brown','#4169E1':'Royal Blue', '#8B4513':'Saddle Brown','#FA8072':'Salmon','#F4A460':'Sandy Brown','#2E8B57':'Sea Green','#FFF5EE':'Sea Shell','#A0522D':'Sienna','#C0C0C0':'Silver', '#87CEEB':'Sky Blue','#6A5ACD':'Slate Blue','#708090':'Slate Gray','#708090':'Slate Grey','#FFFAFA':'Snow','#00FF7F':'Spring Green', '#4682B4':'Steel Blue','#D2B48C':'Tan','#008080':'Teal','#D8BFD8':'Thistle','#FF6347':'Tomato','#40E0D0':'Turquoise','#EE82EE':'Violet', '#F5DEB3':'Wheat','#FFFFFF':'White','#F5F5F5':'White Smoke','#FFFF00':'Yellow','#9ACD32':'Yellow Green' }; var namedLookup = {}; function init() { var inputColor = convertRGBToHex(tinyMCEPopup.getWindowArg('input_color')), key, value; tinyMCEPopup.resizeToInnerSize(); generatePicker(); generateWebColors(); generateNamedColors(); if (inputColor) { changeFinalColor(inputColor); col = convertHexToRGB(inputColor); if (col) updateLight(col.r, col.g, col.b); } for (key in named) { value = named[key]; namedLookup[value.replace(/\s+/, '').toLowerCase()] = key.replace(/#/, '').toLowerCase(); } } function toHexColor(color) { var matches, red, green, blue, toInt = parseInt; function hex(value) { value = parseInt(value).toString(16); return value.length > 1 ? value : '0' + value; // Padd with leading zero }; color = color.replace(/[\s#]+/g, '').toLowerCase(); color = namedLookup[color] || color; matches = /^rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)|([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})|([a-f0-9])([a-f0-9])([a-f0-9])$/.exec(color); if (matches) { if (matches[1]) { red = toInt(matches[1]); green = toInt(matches[2]); blue = toInt(matches[3]); } else if (matches[4]) { red = toInt(matches[4], 16); green = toInt(matches[5], 16); blue = toInt(matches[6], 16); } else if (matches[7]) { red = toInt(matches[7] + matches[7], 16); green = toInt(matches[8] + matches[8], 16); blue = toInt(matches[9] + matches[9], 16); } return '#' + hex(red) + hex(green) + hex(blue); } return ''; } function insertAction() { var color = document.getElementById("color").value, f = tinyMCEPopup.getWindowArg('func'); tinyMCEPopup.restoreSelection(); if (f) f(toHexColor(color)); tinyMCEPopup.close(); } function showColor(color, name) { if (name) document.getElementById("colorname").innerHTML = name; document.getElementById("preview").style.backgroundColor = color; document.getElementById("color").value = color.toUpperCase(); } function convertRGBToHex(col) { var re = new RegExp("rgb\\s*\\(\\s*([0-9]+).*,\\s*([0-9]+).*,\\s*([0-9]+).*\\)", "gi"); if (!col) return col; 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 {r : r, g : g, b : b}; } return null; } function generatePicker() { var el = document.getElementById('light'), h = '', i; for (i = 0; i < detail; i++){ h += '<div id="gs'+i+'" style="background-color:#000000; width:15px; height:3px; border-style:none; border-width:0px;"' + ' onclick="changeFinalColor(this.style.backgroundColor)"' + ' onmousedown="isMouseDown = true; return false;"' + ' onmouseup="isMouseDown = false;"' + ' onmousemove="if (isMouseDown && isMouseOver) changeFinalColor(this.style.backgroundColor); return false;"' + ' onmouseover="isMouseOver = true;"' + ' onmouseout="isMouseOver = false;"' + '></div>'; } el.innerHTML = h; } function generateWebColors() { var el = document.getElementById('webcolors'), h = '', i; if (el.className == 'generated') return; // TODO: VoiceOver doesn't seem to support legend as a label referenced by labelledby. h += '<div role="listbox" aria-labelledby="webcolors_title" tabindex="0"><table role="presentation" border="0" cellspacing="1" cellpadding="0">' + '<tr>'; for (i=0; i<colors.length; i++) { h += '<td bgcolor="' + colors[i] + '" width="10" height="10">' + '<a href="javascript:insertAction();" role="option" tabindex="-1" aria-labelledby="web_colors_' + i + '" onfocus="showColor(\'' + colors[i] + '\');" onmouseover="showColor(\'' + colors[i] + '\');" style="display:block;width:10px;height:10px;overflow:hidden;">'; if (tinyMCEPopup.editor.forcedHighContrastMode) { h += '<canvas class="mceColorSwatch" height="10" width="10" data-color="' + colors[i] + '"></canvas>'; } h += '<span class="mceVoiceLabel" style="display:none;" id="web_colors_' + i + '">' + colors[i].toUpperCase() + '</span>'; h += '</a></td>'; if ((i+1) % 18 == 0) h += '</tr><tr>'; } h += '</table></div>'; el.innerHTML = h; el.className = 'generated'; paintCanvas(el); enableKeyboardNavigation(el.firstChild); } function paintCanvas(el) { tinyMCEPopup.getWin().tinymce.each(tinyMCEPopup.dom.select('canvas.mceColorSwatch', el), function(canvas) { var context; if (canvas.getContext && (context = canvas.getContext("2d"))) { context.fillStyle = canvas.getAttribute('data-color'); context.fillRect(0, 0, 10, 10); } }); } function generateNamedColors() { var el = document.getElementById('namedcolors'), h = '', n, v, i = 0; if (el.className == 'generated') return; for (n in named) { v = named[n]; h += '<a href="javascript:insertAction();" role="option" tabindex="-1" aria-labelledby="named_colors_' + i + '" onfocus="showColor(\'' + n + '\',\'' + v + '\');" onmouseover="showColor(\'' + n + '\',\'' + v + '\');" style="background-color: ' + n + '">'; if (tinyMCEPopup.editor.forcedHighContrastMode) { h += '<canvas class="mceColorSwatch" height="10" width="10" data-color="' + colors[i] + '"></canvas>'; } h += '<span class="mceVoiceLabel" style="display:none;" id="named_colors_' + i + '">' + v + '</span>'; h += '</a>'; i++; } el.innerHTML = h; el.className = 'generated'; paintCanvas(el); enableKeyboardNavigation(el); } function enableKeyboardNavigation(el) { tinyMCEPopup.editor.windowManager.createInstance('tinymce.ui.KeyboardNavigation', { root: el, items: tinyMCEPopup.dom.select('a', el) }, tinyMCEPopup.dom); } function dechex(n) { return strhex.charAt(Math.floor(n / 16)) + strhex.charAt(n % 16); } function computeColor(e) { var x, y, partWidth, partDetail, imHeight, r, g, b, coef, i, finalCoef, finalR, finalG, finalB; x = e.offsetX ? e.offsetX : (e.target ? e.clientX - e.target.x : 0); y = e.offsetY ? e.offsetY : (e.target ? e.clientY - e.target.y : 0); partWidth = document.getElementById('colors').width / 6; partDetail = detail / 2; imHeight = document.getElementById('colors').height; r = (x >= 0)*(x < partWidth)*255 + (x >= partWidth)*(x < 2*partWidth)*(2*255 - x * 255 / partWidth) + (x >= 4*partWidth)*(x < 5*partWidth)*(-4*255 + x * 255 / partWidth) + (x >= 5*partWidth)*(x < 6*partWidth)*255; g = (x >= 0)*(x < partWidth)*(x * 255 / partWidth) + (x >= partWidth)*(x < 3*partWidth)*255 + (x >= 3*partWidth)*(x < 4*partWidth)*(4*255 - x * 255 / partWidth); b = (x >= 2*partWidth)*(x < 3*partWidth)*(-2*255 + x * 255 / partWidth) + (x >= 3*partWidth)*(x < 5*partWidth)*255 + (x >= 5*partWidth)*(x < 6*partWidth)*(6*255 - x * 255 / partWidth); coef = (imHeight - y) / imHeight; r = 128 + (r - 128) * coef; g = 128 + (g - 128) * coef; b = 128 + (b - 128) * coef; changeFinalColor('#' + dechex(r) + dechex(g) + dechex(b)); updateLight(r, g, b); } function updateLight(r, g, b) { var i, partDetail = detail / 2, finalCoef, finalR, finalG, finalB, color; for (i=0; i<detail; i++) { if ((i>=0) && (i<partDetail)) { finalCoef = i / partDetail; finalR = dechex(255 - (255 - r) * finalCoef); finalG = dechex(255 - (255 - g) * finalCoef); finalB = dechex(255 - (255 - b) * finalCoef); } else { finalCoef = 2 - i / partDetail; finalR = dechex(r * finalCoef); finalG = dechex(g * finalCoef); finalB = dechex(b * finalCoef); } color = finalR + finalG + finalB; setCol('gs' + i, '#'+color); } } function changeFinalColor(color) { if (color.indexOf('#') == -1) color = convertRGBToHex(color); setCol('preview', color); document.getElementById('color').value = color; } function setCol(e, c) { try { document.getElementById(e).style.backgroundColor = c; } catch (ex) { // Ignore IE warning } } tinyMCEPopup.onInit.add(init);
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
/** * 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
/** * 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('(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
/** * 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
// =================================================================== // Author: Matt Kruse <matt@mattkruse.com> // WWW: http://www.mattkruse.com/ // // NOTICE: You may use this code for any purpose, commercial or // private, without any further permission from the author. You may // remove this notice from your final code if you wish, however it is // appreciated by the author if at least my web site address is kept. // // You may *NOT* re-distribute this code in any way except through its // use. That means, you can include it in your product, or your web // site, or any other form where the code is actually being used. You // may not put the plain javascript up on your site for download or // include it in your javascript libraries for download. // If you wish to share this code with others, please just point them // to the URL instead. // Please DO NOT link directly to my .js files from your site. Copy // the files to your server and use them there. Thank you. // =================================================================== /* SOURCE FILE: AnchorPosition.js */ /* AnchorPosition.js Author: Matt Kruse Last modified: 10/11/02 DESCRIPTION: These functions find the position of an <A> tag in a document, so other elements can be positioned relative to it. COMPATABILITY: Netscape 4.x,6.x,Mozilla, IE 5.x,6.x on Windows. Some small positioning errors - usually with Window positioning - occur on the Macintosh platform. FUNCTIONS: getAnchorPosition(anchorname) Returns an Object() having .x and .y properties of the pixel coordinates of the upper-left corner of the anchor. Position is relative to the PAGE. getAnchorWindowPosition(anchorname) Returns an Object() having .x and .y properties of the pixel coordinates of the upper-left corner of the anchor, relative to the WHOLE SCREEN. NOTES: 1) For popping up separate browser windows, use getAnchorWindowPosition. Otherwise, use getAnchorPosition 2) Your anchor tag MUST contain both NAME and ID attributes which are the same. For example: <A NAME="test" ID="test"> </A> 3) There must be at least a space between <A> </A> for IE5.5 to see the anchor tag correctly. Do not do <A></A> with no space. */ // getAnchorPosition(anchorname) // This function returns an object having .x and .y properties which are the coordinates // of the named anchor, relative to the page. function getAnchorPosition(anchorname) { // This function will return an Object with x and y properties var useWindow=false; var coordinates=new Object(); var x=0,y=0; // Browser capability sniffing var use_gebi=false, use_css=false, use_layers=false; if (document.getElementById) { use_gebi=true; } else if (document.all) { use_css=true; } else if (document.layers) { use_layers=true; } // Logic to find position if (use_gebi && document.all) { x=AnchorPosition_getPageOffsetLeft(document.all[anchorname]); y=AnchorPosition_getPageOffsetTop(document.all[anchorname]); } else if (use_gebi) { var o=document.getElementById(anchorname); x=AnchorPosition_getPageOffsetLeft(o); y=AnchorPosition_getPageOffsetTop(o); } else if (use_css) { x=AnchorPosition_getPageOffsetLeft(document.all[anchorname]); y=AnchorPosition_getPageOffsetTop(document.all[anchorname]); } else if (use_layers) { var found=0; for (var i=0; i<document.anchors.length; i++) { if (document.anchors[i].name==anchorname) { found=1; break; } } if (found==0) { coordinates.x=0; coordinates.y=0; return coordinates; } x=document.anchors[i].x; y=document.anchors[i].y; } else { coordinates.x=0; coordinates.y=0; return coordinates; } coordinates.x=x; coordinates.y=y; return coordinates; } // getAnchorWindowPosition(anchorname) // This function returns an object having .x and .y properties which are the coordinates // of the named anchor, relative to the window function getAnchorWindowPosition(anchorname) { var coordinates=getAnchorPosition(anchorname); var x=0; var y=0; if (document.getElementById) { if (isNaN(window.screenX)) { x=coordinates.x-document.body.scrollLeft+window.screenLeft; y=coordinates.y-document.body.scrollTop+window.screenTop; } else { x=coordinates.x+window.screenX+(window.outerWidth-window.innerWidth)-window.pageXOffset; y=coordinates.y+window.screenY+(window.outerHeight-24-window.innerHeight)-window.pageYOffset; } } else if (document.all) { x=coordinates.x-document.body.scrollLeft+window.screenLeft; y=coordinates.y-document.body.scrollTop+window.screenTop; } else if (document.layers) { x=coordinates.x+window.screenX+(window.outerWidth-window.innerWidth)-window.pageXOffset; y=coordinates.y+window.screenY+(window.outerHeight-24-window.innerHeight)-window.pageYOffset; } coordinates.x=x; coordinates.y=y; return coordinates; } // Functions for IE to get position of an object function AnchorPosition_getPageOffsetLeft (el) { var ol=el.offsetLeft; while ((el=el.offsetParent) != null) { ol += el.offsetLeft; } return ol; } function AnchorPosition_getWindowOffsetLeft (el) { return AnchorPosition_getPageOffsetLeft(el)-document.body.scrollLeft; } function AnchorPosition_getPageOffsetTop (el) { var ot=el.offsetTop; while((el=el.offsetParent) != null) { ot += el.offsetTop; } return ot; } function AnchorPosition_getWindowOffsetTop (el) { return AnchorPosition_getPageOffsetTop(el)-document.body.scrollTop; } /* SOURCE FILE: PopupWindow.js */ /* PopupWindow.js Author: Matt Kruse Last modified: 02/16/04 DESCRIPTION: This object allows you to easily and quickly popup a window in a certain place. The window can either be a DIV or a separate browser window. COMPATABILITY: Works with Netscape 4.x, 6.x, IE 5.x on Windows. Some small positioning errors - usually with Window positioning - occur on the Macintosh platform. Due to bugs in Netscape 4.x, populating the popup window with <STYLE> tags may cause errors. USAGE: // Create an object for a WINDOW popup var win = new PopupWindow(); // Create an object for a DIV window using the DIV named 'mydiv' var win = new PopupWindow('mydiv'); // Set the window to automatically hide itself when the user clicks // anywhere else on the page except the popup win.autoHide(); // Show the window relative to the anchor name passed in win.showPopup(anchorname); // Hide the popup win.hidePopup(); // Set the size of the popup window (only applies to WINDOW popups win.setSize(width,height); // Populate the contents of the popup window that will be shown. If you // change the contents while it is displayed, you will need to refresh() win.populate(string); // set the URL of the window, rather than populating its contents // manually win.setUrl("http://www.site.com/"); // Refresh the contents of the popup win.refresh(); // Specify how many pixels to the right of the anchor the popup will appear win.offsetX = 50; // Specify how many pixels below the anchor the popup will appear win.offsetY = 100; NOTES: 1) Requires the functions in AnchorPosition.js 2) Your anchor tag MUST contain both NAME and ID attributes which are the same. For example: <A NAME="test" ID="test"> </A> 3) There must be at least a space between <A> </A> for IE5.5 to see the anchor tag correctly. Do not do <A></A> with no space. 4) When a PopupWindow object is created, a handler for 'onmouseup' is attached to any event handler you may have already defined. Do NOT define an event handler for 'onmouseup' after you define a PopupWindow object or the autoHide() will not work correctly. */ // Set the position of the popup window based on the anchor function PopupWindow_getXYPosition(anchorname) { var coordinates; if (this.type == "WINDOW") { coordinates = getAnchorWindowPosition(anchorname); } else { coordinates = getAnchorPosition(anchorname); } this.x = coordinates.x; this.y = coordinates.y; } // Set width/height of DIV/popup window function PopupWindow_setSize(width,height) { this.width = width; this.height = height; } // Fill the window with contents function PopupWindow_populate(contents) { this.contents = contents; this.populated = false; } // Set the URL to go to function PopupWindow_setUrl(url) { this.url = url; } // Set the window popup properties function PopupWindow_setWindowProperties(props) { this.windowProperties = props; } // Refresh the displayed contents of the popup function PopupWindow_refresh() { if (this.divName != null) { // refresh the DIV object if (this.use_gebi) { document.getElementById(this.divName).innerHTML = this.contents; } else if (this.use_css) { document.all[this.divName].innerHTML = this.contents; } else if (this.use_layers) { var d = document.layers[this.divName]; d.document.open(); d.document.writeln(this.contents); d.document.close(); } } else { if (this.popupWindow != null && !this.popupWindow.closed) { if (this.url!="") { this.popupWindow.location.href=this.url; } else { this.popupWindow.document.open(); this.popupWindow.document.writeln(this.contents); this.popupWindow.document.close(); } this.popupWindow.focus(); } } } // Position and show the popup, relative to an anchor object function PopupWindow_showPopup(anchorname) { this.getXYPosition(anchorname); this.x += this.offsetX; this.y += this.offsetY; if (!this.populated && (this.contents != "")) { this.populated = true; this.refresh(); } if (this.divName != null) { // Show the DIV object if (this.use_gebi) { document.getElementById(this.divName).style.left = this.x + "px"; document.getElementById(this.divName).style.top = this.y; document.getElementById(this.divName).style.visibility = "visible"; } else if (this.use_css) { document.all[this.divName].style.left = this.x; document.all[this.divName].style.top = this.y; document.all[this.divName].style.visibility = "visible"; } else if (this.use_layers) { document.layers[this.divName].left = this.x; document.layers[this.divName].top = this.y; document.layers[this.divName].visibility = "visible"; } } else { if (this.popupWindow == null || this.popupWindow.closed) { // If the popup window will go off-screen, move it so it doesn't if (this.x<0) { this.x=0; } if (this.y<0) { this.y=0; } if (screen && screen.availHeight) { if ((this.y + this.height) > screen.availHeight) { this.y = screen.availHeight - this.height; } } if (screen && screen.availWidth) { if ((this.x + this.width) > screen.availWidth) { this.x = screen.availWidth - this.width; } } var avoidAboutBlank = window.opera || ( document.layers && !navigator.mimeTypes['*'] ) || navigator.vendor == 'KDE' || ( document.childNodes && !document.all && !navigator.taintEnabled ); this.popupWindow = window.open(avoidAboutBlank?"":"about:blank","window_"+anchorname,this.windowProperties+",width="+this.width+",height="+this.height+",screenX="+this.x+",left="+this.x+",screenY="+this.y+",top="+this.y+""); } this.refresh(); } } // Hide the popup function PopupWindow_hidePopup() { if (this.divName != null) { if (this.use_gebi) { document.getElementById(this.divName).style.visibility = "hidden"; } else if (this.use_css) { document.all[this.divName].style.visibility = "hidden"; } else if (this.use_layers) { document.layers[this.divName].visibility = "hidden"; } } else { if (this.popupWindow && !this.popupWindow.closed) { this.popupWindow.close(); this.popupWindow = null; } } } // Pass an event and return whether or not it was the popup DIV that was clicked function PopupWindow_isClicked(e) { if (this.divName != null) { if (this.use_layers) { var clickX = e.pageX; var clickY = e.pageY; var t = document.layers[this.divName]; if ((clickX > t.left) && (clickX < t.left+t.clip.width) && (clickY > t.top) && (clickY < t.top+t.clip.height)) { return true; } else { return false; } } else if (document.all) { // Need to hard-code this to trap IE for error-handling var t = window.event.srcElement; while (t.parentElement != null) { if (t.id==this.divName) { return true; } t = t.parentElement; } return false; } else if (this.use_gebi && e) { var t = e.originalTarget; while (t.parentNode != null) { if (t.id==this.divName) { return true; } t = t.parentNode; } return false; } return false; } return false; } // Check an onMouseDown event to see if we should hide function PopupWindow_hideIfNotClicked(e) { if (this.autoHideEnabled && !this.isClicked(e)) { this.hidePopup(); } } // Call this to make the DIV disable automatically when mouse is clicked outside it function PopupWindow_autoHide() { this.autoHideEnabled = true; } // This global function checks all PopupWindow objects onmouseup to see if they should be hidden function PopupWindow_hidePopupWindows(e) { for (var i=0; i<popupWindowObjects.length; i++) { if (popupWindowObjects[i] != null) { var p = popupWindowObjects[i]; p.hideIfNotClicked(e); } } } // Run this immediately to attach the event listener function PopupWindow_attachListener() { if (document.layers) { document.captureEvents(Event.MOUSEUP); } window.popupWindowOldEventListener = document.onmouseup; if (window.popupWindowOldEventListener != null) { document.onmouseup = new Function("window.popupWindowOldEventListener(); PopupWindow_hidePopupWindows();"); } else { document.onmouseup = PopupWindow_hidePopupWindows; } } // CONSTRUCTOR for the PopupWindow object // Pass it a DIV name to use a DHTML popup, otherwise will default to window popup function PopupWindow() { if (!window.popupWindowIndex) { window.popupWindowIndex = 0; } if (!window.popupWindowObjects) { window.popupWindowObjects = new Array(); } if (!window.listenerAttached) { window.listenerAttached = true; PopupWindow_attachListener(); } this.index = popupWindowIndex++; popupWindowObjects[this.index] = this; this.divName = null; this.popupWindow = null; this.width=0; this.height=0; this.populated = false; this.visible = false; this.autoHideEnabled = false; this.contents = ""; this.url=""; this.windowProperties="toolbar=no,location=no,status=no,menubar=no,scrollbars=auto,resizable,alwaysRaised,dependent,titlebar=no"; if (arguments.length>0) { this.type="DIV"; this.divName = arguments[0]; } else { this.type="WINDOW"; } this.use_gebi = false; this.use_css = false; this.use_layers = false; if (document.getElementById) { this.use_gebi = true; } else if (document.all) { this.use_css = true; } else if (document.layers) { this.use_layers = true; } else { this.type = "WINDOW"; } this.offsetX = 0; this.offsetY = 0; // Method mappings this.getXYPosition = PopupWindow_getXYPosition; this.populate = PopupWindow_populate; this.setUrl = PopupWindow_setUrl; this.setWindowProperties = PopupWindow_setWindowProperties; this.refresh = PopupWindow_refresh; this.showPopup = PopupWindow_showPopup; this.hidePopup = PopupWindow_hidePopup; this.setSize = PopupWindow_setSize; this.isClicked = PopupWindow_isClicked; this.autoHide = PopupWindow_autoHide; this.hideIfNotClicked = PopupWindow_hideIfNotClicked; } /* SOURCE FILE: ColorPicker2.js */ /* Last modified: 02/24/2003 DESCRIPTION: This widget is used to select a color, in hexadecimal #RRGGBB form. It uses a color "swatch" to display the standard 216-color web-safe palette. The user can then click on a color to select it. COMPATABILITY: See notes in AnchorPosition.js and PopupWindow.js. Only the latest DHTML-capable browsers will show the color and hex values at the bottom as your mouse goes over them. USAGE: // Create a new ColorPicker object using DHTML popup var cp = new ColorPicker(); // Create a new ColorPicker object using Window Popup var cp = new ColorPicker('window'); // Add a link in your page to trigger the popup. For example: <A HREF="#" onClick="cp.show('pick');return false;" NAME="pick" ID="pick">Pick</A> // Or use the built-in "select" function to do the dirty work for you: <A HREF="#" onClick="cp.select(document.forms[0].color,'pick');return false;" NAME="pick" ID="pick">Pick</A> // If using DHTML popup, write out the required DIV tag near the bottom // of your page. <SCRIPT LANGUAGE="JavaScript">cp.writeDiv()</SCRIPT> // Write the 'pickColor' function that will be called when the user clicks // a color and do something with the value. This is only required if you // want to do something other than simply populate a form field, which is // what the 'select' function will give you. function pickColor(color) { field.value = color; } NOTES: 1) Requires the functions in AnchorPosition.js and PopupWindow.js 2) Your anchor tag MUST contain both NAME and ID attributes which are the same. For example: <A NAME="test" ID="test"> </A> 3) There must be at least a space between <A> </A> for IE5.5 to see the anchor tag correctly. Do not do <A></A> with no space. 4) When a ColorPicker object is created, a handler for 'onmouseup' is attached to any event handler you may have already defined. Do NOT define an event handler for 'onmouseup' after you define a ColorPicker object or the color picker will not hide itself correctly. */ ColorPicker_targetInput = null; function ColorPicker_writeDiv() { document.writeln("<DIV ID=\"colorPickerDiv\" STYLE=\"position:absolute;visibility:hidden;\"> </DIV>"); } function ColorPicker_show(anchorname) { this.showPopup(anchorname); } function ColorPicker_pickColor(color,obj) { obj.hidePopup(); pickColor(color); } // A Default "pickColor" function to accept the color passed back from popup. // User can over-ride this with their own function. function pickColor(color) { if (ColorPicker_targetInput==null) { alert("Target Input is null, which means you either didn't use the 'select' function or you have no defined your own 'pickColor' function to handle the picked color!"); return; } ColorPicker_targetInput.value = color; } // This function is the easiest way to popup the window, select a color, and // have the value populate a form field, which is what most people want to do. function ColorPicker_select(inputobj,linkname) { if (inputobj.type!="text" && inputobj.type!="hidden" && inputobj.type!="textarea") { alert("colorpicker.select: Input object passed is not a valid form input object"); window.ColorPicker_targetInput=null; return; } window.ColorPicker_targetInput = inputobj; this.show(linkname); } // This function runs when you move your mouse over a color block, if you have a newer browser function ColorPicker_highlightColor(c) { var thedoc = (arguments.length>1)?arguments[1]:window.document; var d = thedoc.getElementById("colorPickerSelectedColor"); d.style.backgroundColor = c; d = thedoc.getElementById("colorPickerSelectedColorValue"); d.innerHTML = c; } function ColorPicker() { var windowMode = false; // Create a new PopupWindow object if (arguments.length==0) { var divname = "colorPickerDiv"; } else if (arguments[0] == "window") { var divname = ''; windowMode = true; } else { var divname = arguments[0]; } if (divname != "") { var cp = new PopupWindow(divname); } else { var cp = new PopupWindow(); cp.setSize(225,250); } // Object variables cp.currentValue = "#FFFFFF"; // Method Mappings cp.writeDiv = ColorPicker_writeDiv; cp.highlightColor = ColorPicker_highlightColor; cp.show = ColorPicker_show; cp.select = ColorPicker_select; // Code to populate color picker window var colors = new Array( "#4180B6","#69AEE7","#000000","#000033","#000066","#000099","#0000CC","#0000FF","#330000","#330033","#330066","#330099", "#3300CC","#3300FF","#660000","#660033","#660066","#660099","#6600CC","#6600FF","#990000","#990033","#990066","#990099", "#9900CC","#9900FF","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#FF0000","#FF0033","#FF0066","#FF0099", "#FF00CC","#FF00FF","#7FFFFF","#7FFFFF","#7FF7F7","#7FEFEF","#7FE7E7","#7FDFDF","#7FD7D7","#7FCFCF","#7FC7C7","#7FBFBF", "#7FB7B7","#7FAFAF","#7FA7A7","#7F9F9F","#7F9797","#7F8F8F","#7F8787","#7F7F7F","#7F7777","#7F6F6F","#7F6767","#7F5F5F", "#7F5757","#7F4F4F","#7F4747","#7F3F3F","#7F3737","#7F2F2F","#7F2727","#7F1F1F","#7F1717","#7F0F0F","#7F0707","#7F0000", "#4180B6","#69AEE7","#003300","#003333","#003366","#003399","#0033CC","#0033FF","#333300","#333333","#333366","#333399", "#3333CC","#3333FF","#663300","#663333","#663366","#663399","#6633CC","#6633FF","#993300","#993333","#993366","#993399", "#9933CC","#9933FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#FF3300","#FF3333","#FF3366","#FF3399", "#FF33CC","#FF33FF","#FF7FFF","#FF7FFF","#F77FF7","#EF7FEF","#E77FE7","#DF7FDF","#D77FD7","#CF7FCF","#C77FC7","#BF7FBF", "#B77FB7","#AF7FAF","#A77FA7","#9F7F9F","#977F97","#8F7F8F","#877F87","#7F7F7F","#777F77","#6F7F6F","#677F67","#5F7F5F", "#577F57","#4F7F4F","#477F47","#3F7F3F","#377F37","#2F7F2F","#277F27","#1F7F1F","#177F17","#0F7F0F","#077F07","#007F00", "#4180B6","#69AEE7","#006600","#006633","#006666","#006699","#0066CC","#0066FF","#336600","#336633","#336666","#336699", "#3366CC","#3366FF","#666600","#666633","#666666","#666699","#6666CC","#6666FF","#996600","#996633","#996666","#996699", "#9966CC","#9966FF","#CC6600","#CC6633","#CC6666","#CC6699","#CC66CC","#CC66FF","#FF6600","#FF6633","#FF6666","#FF6699", "#FF66CC","#FF66FF","#FFFF7F","#FFFF7F","#F7F77F","#EFEF7F","#E7E77F","#DFDF7F","#D7D77F","#CFCF7F","#C7C77F","#BFBF7F", "#B7B77F","#AFAF7F","#A7A77F","#9F9F7F","#97977F","#8F8F7F","#87877F","#7F7F7F","#77777F","#6F6F7F","#67677F","#5F5F7F", "#57577F","#4F4F7F","#47477F","#3F3F7F","#37377F","#2F2F7F","#27277F","#1F1F7F","#17177F","#0F0F7F","#07077F","#00007F", "#4180B6","#69AEE7","#009900","#009933","#009966","#009999","#0099CC","#0099FF","#339900","#339933","#339966","#339999", "#3399CC","#3399FF","#669900","#669933","#669966","#669999","#6699CC","#6699FF","#999900","#999933","#999966","#999999", "#9999CC","#9999FF","#CC9900","#CC9933","#CC9966","#CC9999","#CC99CC","#CC99FF","#FF9900","#FF9933","#FF9966","#FF9999", "#FF99CC","#FF99FF","#3FFFFF","#3FFFFF","#3FF7F7","#3FEFEF","#3FE7E7","#3FDFDF","#3FD7D7","#3FCFCF","#3FC7C7","#3FBFBF", "#3FB7B7","#3FAFAF","#3FA7A7","#3F9F9F","#3F9797","#3F8F8F","#3F8787","#3F7F7F","#3F7777","#3F6F6F","#3F6767","#3F5F5F", "#3F5757","#3F4F4F","#3F4747","#3F3F3F","#3F3737","#3F2F2F","#3F2727","#3F1F1F","#3F1717","#3F0F0F","#3F0707","#3F0000", "#4180B6","#69AEE7","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#33CC00","#33CC33","#33CC66","#33CC99", "#33CCCC","#33CCFF","#66CC00","#66CC33","#66CC66","#66CC99","#66CCCC","#66CCFF","#99CC00","#99CC33","#99CC66","#99CC99", "#99CCCC","#99CCFF","#CCCC00","#CCCC33","#CCCC66","#CCCC99","#CCCCCC","#CCCCFF","#FFCC00","#FFCC33","#FFCC66","#FFCC99", "#FFCCCC","#FFCCFF","#FF3FFF","#FF3FFF","#F73FF7","#EF3FEF","#E73FE7","#DF3FDF","#D73FD7","#CF3FCF","#C73FC7","#BF3FBF", "#B73FB7","#AF3FAF","#A73FA7","#9F3F9F","#973F97","#8F3F8F","#873F87","#7F3F7F","#773F77","#6F3F6F","#673F67","#5F3F5F", "#573F57","#4F3F4F","#473F47","#3F3F3F","#373F37","#2F3F2F","#273F27","#1F3F1F","#173F17","#0F3F0F","#073F07","#003F00", "#4180B6","#69AEE7","#00FF00","#00FF33","#00FF66","#00FF99","#00FFCC","#00FFFF","#33FF00","#33FF33","#33FF66","#33FF99", "#33FFCC","#33FFFF","#66FF00","#66FF33","#66FF66","#66FF99","#66FFCC","#66FFFF","#99FF00","#99FF33","#99FF66","#99FF99", "#99FFCC","#99FFFF","#CCFF00","#CCFF33","#CCFF66","#CCFF99","#CCFFCC","#CCFFFF","#FFFF00","#FFFF33","#FFFF66","#FFFF99", "#FFFFCC","#FFFFFF","#FFFF3F","#FFFF3F","#F7F73F","#EFEF3F","#E7E73F","#DFDF3F","#D7D73F","#CFCF3F","#C7C73F","#BFBF3F", "#B7B73F","#AFAF3F","#A7A73F","#9F9F3F","#97973F","#8F8F3F","#87873F","#7F7F3F","#77773F","#6F6F3F","#67673F","#5F5F3F", "#57573F","#4F4F3F","#47473F","#3F3F3F","#37373F","#2F2F3F","#27273F","#1F1F3F","#17173F","#0F0F3F","#07073F","#00003F", "#4180B6","#69AEE7","#FFFFFF","#FFEEEE","#FFDDDD","#FFCCCC","#FFBBBB","#FFAAAA","#FF9999","#FF8888","#FF7777","#FF6666", "#FF5555","#FF4444","#FF3333","#FF2222","#FF1111","#FF0000","#FF0000","#FF0000","#FF0000","#EE0000","#DD0000","#CC0000", "#BB0000","#AA0000","#990000","#880000","#770000","#660000","#550000","#440000","#330000","#220000","#110000","#000000", "#000000","#000000","#000000","#001111","#002222","#003333","#004444","#005555","#006666","#007777","#008888","#009999", "#00AAAA","#00BBBB","#00CCCC","#00DDDD","#00EEEE","#00FFFF","#00FFFF","#00FFFF","#00FFFF","#11FFFF","#22FFFF","#33FFFF", "#44FFFF","#55FFFF","#66FFFF","#77FFFF","#88FFFF","#99FFFF","#AAFFFF","#BBFFFF","#CCFFFF","#DDFFFF","#EEFFFF","#FFFFFF", "#4180B6","#69AEE7","#FFFFFF","#EEFFEE","#DDFFDD","#CCFFCC","#BBFFBB","#AAFFAA","#99FF99","#88FF88","#77FF77","#66FF66", "#55FF55","#44FF44","#33FF33","#22FF22","#11FF11","#00FF00","#00FF00","#00FF00","#00FF00","#00EE00","#00DD00","#00CC00", "#00BB00","#00AA00","#009900","#008800","#007700","#006600","#005500","#004400","#003300","#002200","#001100","#000000", "#000000","#000000","#000000","#110011","#220022","#330033","#440044","#550055","#660066","#770077","#880088","#990099", "#AA00AA","#BB00BB","#CC00CC","#DD00DD","#EE00EE","#FF00FF","#FF00FF","#FF00FF","#FF00FF","#FF11FF","#FF22FF","#FF33FF", "#FF44FF","#FF55FF","#FF66FF","#FF77FF","#FF88FF","#FF99FF","#FFAAFF","#FFBBFF","#FFCCFF","#FFDDFF","#FFEEFF","#FFFFFF", "#4180B6","#69AEE7","#FFFFFF","#EEEEFF","#DDDDFF","#CCCCFF","#BBBBFF","#AAAAFF","#9999FF","#8888FF","#7777FF","#6666FF", "#5555FF","#4444FF","#3333FF","#2222FF","#1111FF","#0000FF","#0000FF","#0000FF","#0000FF","#0000EE","#0000DD","#0000CC", "#0000BB","#0000AA","#000099","#000088","#000077","#000066","#000055","#000044","#000033","#000022","#000011","#000000", "#000000","#000000","#000000","#111100","#222200","#333300","#444400","#555500","#666600","#777700","#888800","#999900", "#AAAA00","#BBBB00","#CCCC00","#DDDD00","#EEEE00","#FFFF00","#FFFF00","#FFFF00","#FFFF00","#FFFF11","#FFFF22","#FFFF33", "#FFFF44","#FFFF55","#FFFF66","#FFFF77","#FFFF88","#FFFF99","#FFFFAA","#FFFFBB","#FFFFCC","#FFFFDD","#FFFFEE","#FFFFFF", "#4180B6","#69AEE7","#FFFFFF","#FFFFFF","#FBFBFB","#F7F7F7","#F3F3F3","#EFEFEF","#EBEBEB","#E7E7E7","#E3E3E3","#DFDFDF", "#DBDBDB","#D7D7D7","#D3D3D3","#CFCFCF","#CBCBCB","#C7C7C7","#C3C3C3","#BFBFBF","#BBBBBB","#B7B7B7","#B3B3B3","#AFAFAF", "#ABABAB","#A7A7A7","#A3A3A3","#9F9F9F","#9B9B9B","#979797","#939393","#8F8F8F","#8B8B8B","#878787","#838383","#7F7F7F", "#7B7B7B","#777777","#737373","#6F6F6F","#6B6B6B","#676767","#636363","#5F5F5F","#5B5B5B","#575757","#535353","#4F4F4F", "#4B4B4B","#474747","#434343","#3F3F3F","#3B3B3B","#373737","#333333","#2F2F2F","#2B2B2B","#272727","#232323","#1F1F1F", "#1B1B1B","#171717","#131313","#0F0F0F","#0B0B0B","#070707","#030303","#000000","#000000","#000000","#000000","#000000"); var total = colors.length; var width = 72; var cp_contents = ""; var windowRef = (windowMode)?"window.opener.":""; if (windowMode) { cp_contents += "<html><head><title>Select Color</title></head>"; cp_contents += "<body marginwidth=0 marginheight=0 leftmargin=0 topmargin=0><span style='text-align: center;'>"; } cp_contents += "<table style='border: none;' cellspacing=0 cellpadding=0>"; var use_highlight = (document.getElementById || document.all)?true:false; for (var i=0; i<total; i++) { if ((i % width) == 0) { cp_contents += "<tr>"; } if (use_highlight) { var mo = 'onMouseOver="'+windowRef+'ColorPicker_highlightColor(\''+colors[i]+'\',window.document)"'; } else { mo = ""; } cp_contents += '<td style="background-color: '+colors[i]+';"><a href="javascript:void()" onclick="'+windowRef+'ColorPicker_pickColor(\''+colors[i]+'\','+windowRef+'window.popupWindowObjects['+cp.index+']);return false;" '+mo+'>&nbsp;</a></td>'; if ( ((i+1)>=total) || (((i+1) % width) == 0)) { cp_contents += "</tr>"; } } // If the browser supports dynamically changing TD cells, add the fancy stuff if (document.getElementById) { var width1 = Math.floor(width/2); var width2 = width = width1; cp_contents += "<tr><td colspan='"+width1+"' style='background-color: #FFF;' ID='colorPickerSelectedColor'>&nbsp;</td><td colspan='"+width2+"' style='text-align: center;' id='colorPickerSelectedColorValue'>#FFFFFF</td></tr>"; } cp_contents += "</table>"; if (windowMode) { cp_contents += "</span></body></html>"; } // end populate code // Write the contents to the popup object cp.populate(cp_contents+"\n"); // Move the table down a bit so you can see it cp.offsetY = 25; cp.autoHide(); return cp; }
JavaScript
// new edit toolbar used with permission // by Alex King // http://www.alexking.org/ var edButtons = new Array(), edLinks = new Array(), edOpenTags = new Array(), now = new Date(), datetime; function edButton(id, display, tagStart, tagEnd, access, open) { this.id = id; // used to name the toolbar button this.display = display; // label on button this.tagStart = tagStart; // open tag this.tagEnd = tagEnd; // close tag this.access = access; // access key this.open = open; // set to -1 if tag does not need to be closed } function zeroise(number, threshold) { // FIXME: or we could use an implementation of printf in js here var str = number.toString(); if (number < 0) { str = str.substr(1, str.length) } while (str.length < threshold) { str = "0" + str } if (number < 0) { str = '-' + str } return str; } datetime = now.getUTCFullYear() + '-' + zeroise(now.getUTCMonth() + 1, 2) + '-' + zeroise(now.getUTCDate(), 2) + 'T' + zeroise(now.getUTCHours(), 2) + ':' + zeroise(now.getUTCMinutes(), 2) + ':' + zeroise(now.getUTCSeconds() ,2) + '+00:00'; edButtons[edButtons.length] = new edButton('ed_strong' ,'b' ,'<strong>' ,'</strong>' ,'b' ); edButtons[edButtons.length] = new edButton('ed_em' ,'i' ,'<em>' ,'</em>' ,'i' ); edButtons[edButtons.length] = new edButton('ed_link' ,'link' ,'' ,'</a>' ,'a' ); // special case edButtons[edButtons.length] = new edButton('ed_block' ,'b-quote' ,'\n\n<blockquote>' ,'</blockquote>\n\n' ,'q' ); edButtons[edButtons.length] = new edButton('ed_del' ,'del' ,'<del datetime="' + datetime + '">' ,'</del>' ,'d' ); edButtons[edButtons.length] = new edButton('ed_ins' ,'ins' ,'<ins datetime="' + datetime + '">' ,'</ins>' ,'s' ); edButtons[edButtons.length] = new edButton('ed_img' ,'img' ,'' ,'' ,'m' ,-1 ); // special case edButtons[edButtons.length] = new edButton('ed_ul' ,'ul' ,'<ul>\n' ,'</ul>\n\n' ,'u' ); edButtons[edButtons.length] = new edButton('ed_ol' ,'ol' ,'<ol>\n' ,'</ol>\n\n' ,'o' ); edButtons[edButtons.length] = new edButton('ed_li' ,'li' ,'\t<li>' ,'</li>\n' ,'l' ); edButtons[edButtons.length] = new edButton('ed_code' ,'code' ,'<code>' ,'</code>' ,'c' ); edButtons[edButtons.length] = new edButton('ed_more' ,'more' ,'<!--more-->' ,'' ,'t' ,-1 ); /* edButtons[edButtons.length] = new edButton('ed_next' ,'page' ,'<!--nextpage-->' ,'' ,'p' ,-1 ); */ function edLink() { this.display = ''; this.URL = ''; this.newWin = 0; } edLinks[edLinks.length] = new edLink('WordPress' ,'http://wordpress.org/' ); edLinks[edLinks.length] = new edLink('alexking.org' ,'http://www.alexking.org/' ); function edShowButton(button, i) { if (button.id == 'ed_img') { document.write('<input type="button" id="' + button.id + '" accesskey="' + button.access + '" class="ed_button" onclick="edInsertImage(edCanvas);" value="' + button.display + '" />'); } else if (button.id == 'ed_link') { document.write('<input type="button" id="' + button.id + '" accesskey="' + button.access + '" class="ed_button" onclick="edInsertLink(edCanvas, ' + i + ');" value="' + button.display + '" />'); } else { document.write('<input type="button" id="' + button.id + '" accesskey="' + button.access + '" class="ed_button" onclick="edInsertTag(edCanvas, ' + i + ');" value="' + button.display + '" />'); } } function edShowLinks() { var tempStr = '<select onchange="edQuickLink(this.options[this.selectedIndex].value, this);"><option value="-1" selected>' + quicktagsL10n.quickLinks + '</option>', i; for (i = 0; i < edLinks.length; i++) { tempStr += '<option value="' + i + '">' + edLinks[i].display + '</option>'; } tempStr += '</select>'; document.write(tempStr); } function edAddTag(button) { if (edButtons[button].tagEnd != '') { edOpenTags[edOpenTags.length] = button; document.getElementById(edButtons[button].id).value = '/' + document.getElementById(edButtons[button].id).value; } } function edRemoveTag(button) { for (var i = 0; i < edOpenTags.length; i++) { if (edOpenTags[i] == button) { edOpenTags.splice(i, 1); document.getElementById(edButtons[button].id).value = document.getElementById(edButtons[button].id).value.replace('/', ''); } } } function edCheckOpenTags(button) { var tag = 0, i; for (i = 0; i < edOpenTags.length; i++) { if (edOpenTags[i] == button) { tag++; } } if (tag > 0) { return true; // tag found } else { return false; // tag not found } } function edCloseAllTags() { var count = edOpenTags.length, o; for (o = 0; o < count; o++) { edInsertTag(edCanvas, edOpenTags[edOpenTags.length - 1]); } } function edQuickLink(i, thisSelect) { if (i > -1) { var newWin = '', tempStr; if (edLinks[i].newWin == 1) { newWin = ' target="_blank"'; } tempStr = '<a href="' + edLinks[i].URL + '"' + newWin + '>' + edLinks[i].display + '</a>'; thisSelect.selectedIndex = 0; edInsertContent(edCanvas, tempStr); } else { thisSelect.selectedIndex = 0; } } function edSpell(myField) { var word = '', sel, startPos, endPos; if (document.selection) { myField.focus(); sel = document.selection.createRange(); if (sel.text.length > 0) { word = sel.text; } } else if (myField.selectionStart || myField.selectionStart == '0') { startPos = myField.selectionStart; endPos = myField.selectionEnd; if (startPos != endPos) { word = myField.value.substring(startPos, endPos); } } if (word == '') { word = prompt(quicktagsL10n.wordLookup, ''); } if (word !== null && /^\w[\w ]*$/.test(word)) { window.open('http://www.answers.com/' + escape(word)); } } function edToolbar() { document.write('<div id="ed_toolbar">'); for (var i = 0; i < edButtons.length; i++) { edShowButton(edButtons[i], i); } document.write('<input type="button" id="ed_spell" class="ed_button" onclick="edSpell(edCanvas);" title="' + quicktagsL10n.dictionaryLookup + '" value="' + quicktagsL10n.lookup + '" />'); document.write('<input type="button" id="ed_close" class="ed_button" onclick="edCloseAllTags();" title="' + quicktagsL10n.closeAllOpenTags + '" value="' + quicktagsL10n.closeTags + '" />'); document.write('<input type="button" id="ed_fullscreen" class="ed_button" onclick="fullscreen.on();" title="' + quicktagsL10n.toggleFullscreen + '" value="' + quicktagsL10n.fullscreen + '" />'); // edShowLinks(); // disabled by default document.write('</div>'); } // insertion code function edInsertTag(myField, i) { //IE support if (document.selection) { myField.focus(); var sel = document.selection.createRange(); if (sel.text.length > 0) { sel.text = edButtons[i].tagStart + sel.text + edButtons[i].tagEnd; } else { if (!edCheckOpenTags(i) || edButtons[i].tagEnd == '') { sel.text = edButtons[i].tagStart; edAddTag(i); } else { sel.text = edButtons[i].tagEnd; edRemoveTag(i); } } myField.focus(); } //MOZILLA/NETSCAPE support else if (myField.selectionStart || myField.selectionStart == '0') { var startPos = myField.selectionStart, endPos = myField.selectionEnd, cursorPos = endPos, scrollTop = myField.scrollTop; if (startPos != endPos) { myField.value = myField.value.substring(0, startPos) + edButtons[i].tagStart + myField.value.substring(startPos, endPos) + edButtons[i].tagEnd + myField.value.substring(endPos, myField.value.length); cursorPos += edButtons[i].tagStart.length + edButtons[i].tagEnd.length; } else { if (!edCheckOpenTags(i) || edButtons[i].tagEnd == '') { myField.value = myField.value.substring(0, startPos) + edButtons[i].tagStart + myField.value.substring(endPos, myField.value.length); edAddTag(i); cursorPos = startPos + edButtons[i].tagStart.length; } else { myField.value = myField.value.substring(0, startPos) + edButtons[i].tagEnd + myField.value.substring(endPos, myField.value.length); edRemoveTag(i); cursorPos = startPos + edButtons[i].tagEnd.length; } } myField.focus(); myField.selectionStart = cursorPos; myField.selectionEnd = cursorPos; myField.scrollTop = scrollTop; } else { if (!edCheckOpenTags(i) || edButtons[i].tagEnd == '') { myField.value += edButtons[i].tagStart; edAddTag(i); } else { myField.value += edButtons[i].tagEnd; edRemoveTag(i); } myField.focus(); } } function edInsertContent(myField, myValue) { var sel, startPos, endPos, scrollTop; //IE support if (document.selection) { myField.focus(); sel = document.selection.createRange(); sel.text = myValue; myField.focus(); } //MOZILLA/NETSCAPE support else if (myField.selectionStart || myField.selectionStart == '0') { startPos = myField.selectionStart; endPos = myField.selectionEnd; scrollTop = myField.scrollTop; myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length); myField.focus(); myField.selectionStart = startPos + myValue.length; myField.selectionEnd = startPos + myValue.length; myField.scrollTop = scrollTop; } else { myField.value += myValue; myField.focus(); } } function edInsertLink(myField, i, defaultValue) { if ( 'object' == typeof(wpLink) ) { wpLink.open(); } else { if (!defaultValue) { defaultValue = 'http://'; } if (!edCheckOpenTags(i)) { var URL = prompt(quicktagsL10n.enterURL, defaultValue); if (URL) { edButtons[i].tagStart = '<a href="' + URL + '">'; edInsertTag(myField, i); } } else { edInsertTag(myField, i); } } } function edInsertImage(myField) { var myValue = prompt(quicktagsL10n.enterImageURL, 'http://'); if (myValue) { myValue = '<img src="' + myValue + '" alt="' + prompt(quicktagsL10n.enterImageDescription, '') + '" />'; edInsertContent(myField, myValue); } } // Allow multiple instances. // Name = unique value, id = textarea id, container = container div. // Can disable some buttons by passing comma delimited string as 4th param. var QTags = function(name, id, container, disabled) { var t = this, cont = document.getElementById(container), i, tag, tb, html, sel; t.Buttons = []; t.Links = []; t.OpenTags = []; t.Canvas = document.getElementById(id); if ( ! t.Canvas || ! cont ) return; disabled = ( typeof disabled != 'undefined' ) ? ','+disabled+',' : ''; t.edShowButton = function(button, i) { if ( disabled && (disabled.indexOf(','+button.display+',') != -1) ) return ''; else if ( button.id == name+'_img' ) return '<input type="button" id="' + button.id + '" accesskey="' + button.access + '" class="ed_button" onclick="edInsertImage('+name+'.Canvas);" value="' + button.display + '" />'; else if (button.id == name+'_link') return '<input type="button" id="' + button.id + '" accesskey="' + button.access + '" class="ed_button" onclick="'+name+'.edInsertLink('+i+');" value="'+button.display+'" />'; else return '<input type="button" id="' + button.id + '" accesskey="'+button.access+'" class="ed_button" onclick="'+name+'.edInsertTag('+i+');" value="'+button.display+'" />'; }; t.edAddTag = function(button) { if ( t.Buttons[button].tagEnd != '' ) { t.OpenTags[t.OpenTags.length] = button; document.getElementById(t.Buttons[button].id).value = '/' + document.getElementById(t.Buttons[button].id).value; } }; t.edRemoveTag = function(button) { for ( i = 0; i < t.OpenTags.length; i++ ) { if ( t.OpenTags[i] == button ) { t.OpenTags.splice(i, 1); document.getElementById(t.Buttons[button].id).value = document.getElementById(t.Buttons[button].id).value.replace('/', ''); } } }; t.edCheckOpenTags = function(button) { tag = 0; for ( var i = 0; i < t.OpenTags.length; i++ ) { if ( t.OpenTags[i] == button ) tag++; } if ( tag > 0 ) return true; // tag found else return false; // tag not found }; this.edCloseAllTags = function() { var count = t.OpenTags.length; for ( var o = 0; o < count; o++ ) t.edInsertTag(t.OpenTags[t.OpenTags.length - 1]); }; this.edQuickLink = function(i, thisSelect) { if ( i > -1 ) { var newWin = '', tempStr; if ( Links[i].newWin == 1 ) { newWin = ' target="_blank"'; } tempStr = '<a href="' + Links[i].URL + '"' + newWin + '>' + Links[i].display + '</a>'; thisSelect.selectedIndex = 0; edInsertContent(t.Canvas, tempStr); } else { thisSelect.selectedIndex = 0; } }; // insertion code t.edInsertTag = function(i) { //IE support if ( document.selection ) { t.Canvas.focus(); sel = document.selection.createRange(); if ( sel.text.length > 0 ) { sel.text = t.Buttons[i].tagStart + sel.text + t.Buttons[i].tagEnd; } else { if ( ! t.edCheckOpenTags(i) || t.Buttons[i].tagEnd == '' ) { sel.text = t.Buttons[i].tagStart; t.edAddTag(i); } else { sel.text = t.Buttons[i].tagEnd; t.edRemoveTag(i); } } t.Canvas.focus(); } else if ( t.Canvas.selectionStart || t.Canvas.selectionStart == '0' ) { //MOZILLA/NETSCAPE support var startPos = t.Canvas.selectionStart, endPos = t.Canvas.selectionEnd, cursorPos = endPos, scrollTop = t.Canvas.scrollTop; if ( startPos != endPos ) { t.Canvas.value = t.Canvas.value.substring(0, startPos) + t.Buttons[i].tagStart + t.Canvas.value.substring(startPos, endPos) + t.Buttons[i].tagEnd + t.Canvas.value.substring(endPos, t.Canvas.value.length); cursorPos += t.Buttons[i].tagStart.length + t.Buttons[i].tagEnd.length; } else { if ( !t.edCheckOpenTags(i) || t.Buttons[i].tagEnd == '' ) { t.Canvas.value = t.Canvas.value.substring(0, startPos) + t.Buttons[i].tagStart + t.Canvas.value.substring(endPos, t.Canvas.value.length); t.edAddTag(i); cursorPos = startPos + t.Buttons[i].tagStart.length; } else { t.Canvas.value = t.Canvas.value.substring(0, startPos) + t.Buttons[i].tagEnd + t.Canvas.value.substring(endPos, t.Canvas.value.length); t.edRemoveTag(i); cursorPos = startPos + t.Buttons[i].tagEnd.length; } } t.Canvas.focus(); t.Canvas.selectionStart = cursorPos; t.Canvas.selectionEnd = cursorPos; t.Canvas.scrollTop = scrollTop; } else { if ( ! t.edCheckOpenTags(i) || t.Buttons[i].tagEnd == '' ) { t.Canvas.value += Buttons[i].tagStart; t.edAddTag(i); } else { t.Canvas.value += Buttons[i].tagEnd; t.edRemoveTag(i); } t.Canvas.focus(); } }; this.edInsertLink = function(i, defaultValue) { if ( ! defaultValue ) defaultValue = 'http://'; if ( ! t.edCheckOpenTags(i) ) { var URL = prompt(quicktagsL10n.enterURL, defaultValue); if ( URL ) { t.Buttons[i].tagStart = '<a href="' + URL + '">'; t.edInsertTag(i); } } else { t.edInsertTag(i); } }; this.edInsertImage = function() { var myValue = prompt(quicktagsL10n.enterImageURL, 'http://'); if ( myValue ) { myValue = '<img src="' + myValue + '" alt="' + prompt(quicktagsL10n.enterImageDescription, '') + '" />'; edInsertContent(t.Canvas, myValue); } }; t.Buttons[t.Buttons.length] = new edButton(name+'_strong','b','<strong>','</strong>','b'); t.Buttons[t.Buttons.length] = new edButton(name+'_em','i','<em>','</em>','i'); t.Buttons[t.Buttons.length] = new edButton(name+'_link','link','','</a>','a'); // special case t.Buttons[t.Buttons.length] = new edButton(name+'_block','b-quote','\n\n<blockquote>','</blockquote>\n\n','q'); t.Buttons[t.Buttons.length] = new edButton(name+'_del','del','<del datetime="' + datetime + '">','</del>','d'); t.Buttons[t.Buttons.length] = new edButton(name+'_ins','ins','<ins datetime="' + datetime + '">','</ins>','s'); t.Buttons[t.Buttons.length] = new edButton(name+'_img','img','','','m',-1); // special case t.Buttons[t.Buttons.length] = new edButton(name+'_ul','ul','<ul>\n','</ul>\n\n','u'); t.Buttons[t.Buttons.length] = new edButton(name+'_ol','ol','<ol>\n','</ol>\n\n','o'); t.Buttons[t.Buttons.length] = new edButton(name+'_li','li','\t<li>','</li>\n','l'); t.Buttons[t.Buttons.length] = new edButton(name+'_code','code','<code>','</code>','c'); t.Buttons[t.Buttons.length] = new edButton(name+'_more','more','<!--more-->','','t',-1); // t.Buttons[t.Buttons.length] = new edButton(name+'_next','page','<!--nextpage-->','','p',-1); tb = document.createElement('div'); tb.id = name+'_qtags'; html = '<div id="'+name+'_toolbar">'; for (i = 0; i < t.Buttons.length; i++) html += t.edShowButton(t.Buttons[i], i); html += '<input type="button" id="'+name+'_ed_spell" class="ed_button" onclick="edSpell('+name+'.Canvas);" title="' + quicktagsL10n.dictionaryLookup + '" value="' + quicktagsL10n.lookup + '" />'; html += '<input type="button" id="'+name+'_ed_close" class="ed_button" onclick="'+name+'.edCloseAllTags();" title="' + quicktagsL10n.closeAllOpenTags + '" value="' + quicktagsL10n.closeTags + '" /></div>'; tb.innerHTML = html; cont.parentNode.insertBefore(tb, cont); };
JavaScript
//Used to ensure that Entities used in L10N strings are correct function convertEntities(o) { var c, v; c = function(s) { if (/&[^;]+;/.test(s)) { var e = document.createElement("div"); e.innerHTML = s; return !e.firstChild ? s : e.firstChild.nodeValue; } return s; } if ( typeof o === 'string' ) { return c(o); } else if ( typeof o === 'object' ) { for (v in o) { if ( typeof o[v] === 'string' ) { o[v] = c(o[v]); } } } return o; }
JavaScript
/* * Thickbox 3.1 - One Box To Rule Them All. * By Cody Lindley (http://www.codylindley.com) * Copyright (c) 2007 cody lindley * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php */ if ( typeof tb_pathToImage != 'string' ) { var tb_pathToImage = thickboxL10n.loadingAnimation; } if ( typeof tb_closeImage != 'string' ) { var tb_closeImage = thickboxL10n.closeImage; } /*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/ //on page load call tb_init jQuery(document).ready(function(){ tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox imgLoader = new Image();// preload image imgLoader.src = tb_pathToImage; }); //add thickbox to href & area elements that have a class of .thickbox function tb_init(domChunk){ jQuery(domChunk).live('click', tb_click); } function tb_click(){ var t = this.title || this.name || null; var a = this.href || this.alt; var g = this.rel || false; tb_show(t,a,g); this.blur(); return false; } function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link try { if (typeof document.body.style.maxHeight === "undefined") {//if IE 6 jQuery("body","html").css({height: "100%", width: "100%"}); jQuery("html").css("overflow","hidden"); if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6 jQuery("body").append("<iframe id='TB_HideSelect'>"+thickboxL10n.noiframes+"</iframe><div id='TB_overlay'></div><div id='TB_window'></div>"); jQuery("#TB_overlay").click(tb_remove); } }else{//all others if(document.getElementById("TB_overlay") === null){ jQuery("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>"); jQuery("#TB_overlay").click(tb_remove); } } if(tb_detectMacXFF()){ jQuery("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash }else{ jQuery("#TB_overlay").addClass("TB_overlayBG");//use background and opacity } if(caption===null){caption="";} jQuery("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page jQuery('#TB_load').show();//show loader var baseURL; if(url.indexOf("?")!==-1){ //ff there is a query string involved baseURL = url.substr(0, url.indexOf("?")); }else{ baseURL = url; } var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/; var urlType = baseURL.toLowerCase().match(urlString); if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images TB_PrevCaption = ""; TB_PrevURL = ""; TB_PrevHTML = ""; TB_NextCaption = ""; TB_NextURL = ""; TB_NextHTML = ""; TB_imageCount = ""; TB_FoundURL = false; if(imageGroup){ TB_TempArray = jQuery("a[rel="+imageGroup+"]").get(); for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) { var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString); if (!(TB_TempArray[TB_Counter].href == url)) { if (TB_FoundURL) { TB_NextCaption = TB_TempArray[TB_Counter].title; TB_NextURL = TB_TempArray[TB_Counter].href; TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>"+thickboxL10n.next+"</a></span>"; } else { TB_PrevCaption = TB_TempArray[TB_Counter].title; TB_PrevURL = TB_TempArray[TB_Counter].href; TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>"+thickboxL10n.prev+"</a></span>"; } } else { TB_FoundURL = true; TB_imageCount = thickboxL10n.image + ' ' + (TB_Counter + 1) + ' ' + thickboxL10n.of + ' ' + (TB_TempArray.length); } } } imgPreloader = new Image(); imgPreloader.onload = function(){ imgPreloader.onload = null; // Resizing large images - orginal by Christian Montoya edited by me. var pagesize = tb_getPageSize(); var x = pagesize[0] - 150; var y = pagesize[1] - 150; var imageWidth = imgPreloader.width; var imageHeight = imgPreloader.height; if (imageWidth > x) { imageHeight = imageHeight * (x / imageWidth); imageWidth = x; if (imageHeight > y) { imageWidth = imageWidth * (y / imageHeight); imageHeight = y; } } else if (imageHeight > y) { imageWidth = imageWidth * (y / imageHeight); imageHeight = y; if (imageWidth > x) { imageHeight = imageHeight * (x / imageWidth); imageWidth = x; } } // End Resizing TB_WIDTH = imageWidth + 30; TB_HEIGHT = imageHeight + 60; jQuery("#TB_window").append("<a href='' id='TB_ImageOff' title='"+thickboxL10n.close+"'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='"+thickboxL10n.close+"'><img src='" + tb_closeImage + "' /></a></div>"); jQuery("#TB_closeWindowButton").click(tb_remove); if (!(TB_PrevHTML === "")) { function goPrev(){ if(jQuery(document).unbind("click",goPrev)){jQuery(document).unbind("click",goPrev);} jQuery("#TB_window").remove(); jQuery("body").append("<div id='TB_window'></div>"); tb_show(TB_PrevCaption, TB_PrevURL, imageGroup); return false; } jQuery("#TB_prev").click(goPrev); } if (!(TB_NextHTML === "")) { function goNext(){ jQuery("#TB_window").remove(); jQuery("body").append("<div id='TB_window'></div>"); tb_show(TB_NextCaption, TB_NextURL, imageGroup); return false; } jQuery("#TB_next").click(goNext); } jQuery(document).bind('keydown.thickbox', function(e){ e.stopImmediatePropagation(); if ( e.which == 27 ){ // close if ( ! jQuery(document).triggerHandler( 'wp_CloseOnEscape', [{ event: e, what: 'thickbox', cb: tb_remove }] ) ) tb_remove(); } else if ( e.which == 190 ){ // display previous image if(!(TB_NextHTML == "")){ jQuery(document).unbind('thickbox'); goNext(); } } else if ( e.which == 188 ){ // display next image if(!(TB_PrevHTML == "")){ jQuery(document).unbind('thickbox'); goPrev(); } } return false; }); tb_position(); jQuery("#TB_load").remove(); jQuery("#TB_ImageOff").click(tb_remove); jQuery("#TB_window").css({display:"block"}); //for safari using css instead of show }; imgPreloader.src = url; }else{//code to show html var queryString = url.replace(/^[^\?]+\??/,''); var params = tb_parseQuery( queryString ); TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL ajaxContentW = TB_WIDTH - 30; ajaxContentH = TB_HEIGHT - 45; if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window urlNoQuery = url.split('TB_'); jQuery("#TB_iframeContent").remove(); if(params['modal'] != "true"){//iframe no modal jQuery("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='"+thickboxL10n.close+"'><img src='" + tb_closeImage + "' /></a></div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' >"+thickboxL10n.noiframes+"</iframe>"); }else{//iframe modal jQuery("#TB_overlay").unbind(); jQuery("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'>"+thickboxL10n.noiframes+"</iframe>"); } }else{// not an iframe, ajax if(jQuery("#TB_window").css("display") != "block"){ if(params['modal'] != "true"){//ajax no modal jQuery("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'><img src='" + tb_closeImage + "' /></a></div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>"); }else{//ajax modal jQuery("#TB_overlay").unbind(); jQuery("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>"); } }else{//this means the window is already up, we are just loading new content via ajax jQuery("#TB_ajaxContent")[0].style.width = ajaxContentW +"px"; jQuery("#TB_ajaxContent")[0].style.height = ajaxContentH +"px"; jQuery("#TB_ajaxContent")[0].scrollTop = 0; jQuery("#TB_ajaxWindowTitle").html(caption); } } jQuery("#TB_closeWindowButton").click(tb_remove); if(url.indexOf('TB_inline') != -1){ jQuery("#TB_ajaxContent").append(jQuery('#' + params['inlineId']).children()); jQuery("#TB_window").unload(function () { jQuery('#' + params['inlineId']).append( jQuery("#TB_ajaxContent").children() ); // move elements back when you're finished }); tb_position(); jQuery("#TB_load").remove(); jQuery("#TB_window").css({display:"block"}); }else if(url.indexOf('TB_iframe') != -1){ tb_position(); if(jQuery.browser.safari){//safari needs help because it will not fire iframe onload jQuery("#TB_load").remove(); jQuery("#TB_window").css({display:"block"}); } }else{ jQuery("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method tb_position(); jQuery("#TB_load").remove(); tb_init("#TB_ajaxContent a.thickbox"); jQuery("#TB_window").css({display:"block"}); }); } } if(!params['modal']){ jQuery(document).bind('keyup.thickbox', function(e){ if ( e.which == 27 ){ // close e.stopImmediatePropagation(); if ( ! jQuery(document).triggerHandler( 'wp_CloseOnEscape', [{ event: e, what: 'thickbox', cb: tb_remove }] ) ) tb_remove(); return false; } }); } } catch(e) { //nothing here } } //helper functions below function tb_showIframe(){ jQuery("#TB_load").remove(); jQuery("#TB_window").css({display:"block"}); } function tb_remove() { jQuery("#TB_imageOff").unbind("click"); jQuery("#TB_closeWindowButton").unbind("click"); jQuery("#TB_window").fadeOut("fast",function(){jQuery('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();}); jQuery("#TB_load").remove(); if (typeof document.body.style.maxHeight == "undefined") {//if IE 6 jQuery("body","html").css({height: "auto", width: "auto"}); jQuery("html").css("overflow",""); } jQuery(document).unbind('.thickbox'); return false; } function tb_position() { var isIE6 = typeof document.body.style.maxHeight === "undefined"; jQuery("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'}); if ( ! isIE6 ) { // take away IE6 jQuery("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'}); } } function tb_parseQuery ( query ) { var Params = {}; if ( ! query ) {return Params;}// return empty object var Pairs = query.split(/[;&]/); for ( var i = 0; i < Pairs.length; i++ ) { var KeyVal = Pairs[i].split('='); if ( ! KeyVal || KeyVal.length != 2 ) {continue;} var key = unescape( KeyVal[0] ); var val = unescape( KeyVal[1] ); val = val.replace(/\+/g, ' '); Params[key] = val; } return Params; } function tb_getPageSize(){ var de = document.documentElement; var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth; var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight; arrayPageSize = [w,h]; return arrayPageSize; } function tb_detectMacXFF() { var userAgent = navigator.userAgent.toLowerCase(); if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) { return true; } }
JavaScript
jQuery(function(){ // Ajax Login jQuery('.widget_wp_sidebarlogin form').submit(function(){ var thisform = this; jQuery(thisform).block({ message: null, overlayCSS: { backgroundColor: '#fff', opacity: 0.6 } }); jQuery.ajax({ type: 'POST', url: jQuery(thisform).attr('action'), data: jQuery(thisform).serialize(), success: function( result ) { jQuery('.login_error').remove(); result = jQuery.trim( result ); if (result=='SBL_SUCCESS' || result.indexOf( 'SBL_SUCCESS' ) > 0) { window.location = jQuery('.redirect_to:eq(0)', thisform).attr('value'); } else { jQuery(thisform).prepend('<p class="login_error">' + result + '</p>'); jQuery(thisform).unblock(); } } }); return false; }); });
JavaScript
jQuery(document).ready(function () { jQuery('.akismet-status').each(function () { var thisId = jQuery(this).attr('commentid'); jQuery(this).prependTo('#comment-' + thisId + ' .column-comment div:first-child'); }); jQuery('.akismet-user-comment-count').each(function () { var thisId = jQuery(this).attr('commentid'); jQuery(this).insertAfter('#comment-' + thisId + ' .author strong:first').show(); }); });
JavaScript
(function($) { $(document).ready( function() { $('.feature-slider a').click(function(e) { $('.featured-posts section.featured-post').css({ opacity: 0, visibility: 'hidden' }); $(this.hash).css({ opacity: 1, visibility: 'visible' }); $('.feature-slider a').removeClass('active'); $(this).addClass('active'); e.preventDefault(); }); }); })(jQuery);
JavaScript
var farbtastic; (function($){ var pickColor = function(a) { farbtastic.setColor(a); $('#link-color').val(a); $('#link-color-example').css('background-color', a); }; $(document).ready( function() { $('#default-color').wrapInner('<a href="#" />'); farbtastic = $.farbtastic('#colorPickerDiv', pickColor); pickColor( $('#link-color').val() ); $('.pickcolor').click( function(e) { $('#colorPickerDiv').show(); e.preventDefault(); }); $('#link-color').keyup( function() { var a = $('#link-color').val(), b = a; a = a.replace(/[^a-fA-F0-9]/, ''); if ( '#' + a !== b ) $('#link-color').val(a); if ( a.length === 3 || a.length === 6 ) pickColor( '#' + a ); }); $(document).mousedown( function() { $('#colorPickerDiv').hide(); }); $('#default-color a').click( function(e) { pickColor( '#' + this.innerHTML.replace(/[^a-fA-F0-9]/, '') ); e.preventDefault(); }); $('.image-radio-option.color-scheme input:radio').change( function() { var currentDefault = $('#default-color a'), newDefault = $(this).next().val(); if ( $('#link-color').val() == currentDefault.text() ) pickColor( newDefault ); currentDefault.text( newDefault ); }); }); })(jQuery);
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); /* * Supersubs v0.2b - jQuery plugin * 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 * * * This plugin automatically adjusts submenu widths of suckerfish-style menus to that of * their longest list item children. If you use this, please expect bugs and report them * to the jQuery Google Group with the word 'Superfish' in the subject line. * */ ;(function($){ // $ will refer to jQuery within this closure $.fn.supersubs = function(options){ var opts = $.extend({}, $.fn.supersubs.defaults, options); // return original object to support chaining return this.each(function() { // cache selections var $$ = $(this); // support metadata var o = $.meta ? $.extend({}, opts, $$.data()) : opts; // get the font size of menu. // .css('fontSize') returns various results cross-browser, so measure an em dash instead var fontsize = $('<li id="menu-fontsize">&#8212;</li>').css({ 'padding' : 0, 'position' : 'absolute', 'top' : '-999em', 'width' : 'auto' }).appendTo($$).width(); //clientWidth is faster, but was incorrect here // remove em dash $('#menu-fontsize').remove(); // cache all ul elements $ULs = $$.find('ul'); // loop through each ul in menu $ULs.each(function(i) { // cache this ul var $ul = $ULs.eq(i); // get all (li) children of this ul var $LIs = $ul.children(); // get all anchor grand-children var $As = $LIs.children('a'); // force content to one line and save current float property var liFloat = $LIs.css('white-space','nowrap').css('float'); // remove width restrictions and floats so elements remain vertically stacked var emWidth = $ul.add($LIs).add($As).css({ 'float' : 'none', 'width' : 'auto' }) // this ul will now be shrink-wrapped to longest li due to position:absolute // so save its width as ems. Clientwidth is 2 times faster than .width() - thanks Dan Switzer .end().end()[0].clientWidth / fontsize; // add more width to ensure lines don't turn over at certain sizes in various browsers emWidth += o.extraWidth; // restrict to at least minWidth and at most maxWidth if (emWidth > o.maxWidth) { emWidth = o.maxWidth; } else if (emWidth < o.minWidth) { emWidth = o.minWidth; } emWidth += 'em'; // set ul to width in ems $ul.css('width',emWidth); // restore li floats to avoid IE bugs // set li width to full width of this ul // revert white-space to normal $LIs.css({ 'float' : liFloat, 'width' : '100%', 'white-space' : 'normal' }) // update offset position of descendant ul to reflect new width of parent .each(function(){ var $childUl = $('>ul',this); var offsetDirection = $childUl.css('left')!==undefined ? 'left' : 'right'; $childUl.css(offsetDirection,emWidth); }); }); }); }; // expose defaults $.fn.supersubs.defaults = { minWidth : 9, // requires em unit. maxWidth : 25, // requires em unit. extraWidth : 0 // extra width can ensure lines don't sometimes turn over due to slight browser differences in how they round-off values }; })(jQuery); // plugin code ends /** * Hybrid drop-downs. * @author Justin Tadlock * @license http://www.gnu.org/licenses/gpl.html * @copyright 2008 - 2011 Justin Tadlock */ $j = jQuery.noConflict(); $j(document).ready( function() { /* Drop-down controls. */ $j('div.menu ul:first-child').supersubs( { minWidth: 12, maxWidth: 27, extraWidth: 1 } ).superfish( { delay: 100, animation: { opacity: 'show', height: 'show' }, dropShadows: false } ); /* @deprecated 0.8 Page and cat nav drop-downs. */ $j('#page-nav ul.menu').supersubs( { minWidth: 12, maxWidth: 27, extraWidth: 1 } ).superfish( { delay: 100, animation: { opacity: 'show', height: 'show' }, dropShadows: false } ); $j('#cat-nav ul.menu').supersubs( { minWidth: 12, maxWidth: 27, extraWidth: 1 } ).superfish( { delay: 100, animation: { opacity: 'show', height: 'show' }, dropShadows: false } ); } );
JavaScript
var showNotice, adminMenu, columns, validateForm, screenMeta; (function($){ // sidebar admin menu adminMenu = { init : function() { var menu = $('#adminmenu'); $('.wp-menu-toggle', menu).each( function() { var t = $(this), sub = t.siblings('.wp-submenu'); if ( sub.length ) t.click(function(){ adminMenu.toggle( sub ); }); else t.hide(); }); this.favorites(); $('#collapse-menu', menu).click(function(){ if ( $('body').hasClass('folded') ) { adminMenu.fold(1); deleteUserSetting( 'mfold' ); } else { adminMenu.fold(); setUserSetting( 'mfold', 'f' ); } return false; }); if ( $('body').hasClass('folded') ) this.fold(); }, restoreMenuState : function() { // (perhaps) needed for back-compat }, toggle : function(el) { el.slideToggle(150, function() { var id = el.css('display','').parent().toggleClass( 'wp-menu-open' ).attr('id'); if ( id ) { $('li.wp-has-submenu', '#adminmenu').each(function(i, e) { if ( id == e.id ) { var v = $(e).hasClass('wp-menu-open') ? 'o' : 'c'; setUserSetting( 'm'+i, v ); } }); } }); return false; }, fold : function(off) { if (off) { $('body').removeClass('folded'); $('#adminmenu li.wp-has-submenu').unbind(); } else { $('body').addClass('folded'); $('#adminmenu li.wp-has-submenu').hoverIntent({ over: function(e){ var m, b, h, o, f; m = $(this).find('.wp-submenu'); b = $(this).offset().top + m.height() + 1; // Bottom offset of the menu h = $('#wpwrap').height(); // Height of the entire page o = 60 + b - h; f = $(window).height() + $(window).scrollTop() - 15; // The fold if ( f < (b - o) ) { o = b - f; } if ( o > 1 ) { m.css({'marginTop':'-'+o+'px'}); } else if ( m.css('marginTop') ) { m.css({'marginTop':''}); } m.addClass('sub-open'); }, out: function(){ $(this).find('.wp-submenu').removeClass('sub-open'); }, timeout: 220, sensitivity: 8, interval: 100 }); } }, favorites : function() { $('#favorite-inside').width( $('#favorite-actions').width() - 4 ); $('#favorite-toggle, #favorite-inside').bind('mouseenter', function() { $('#favorite-inside').removeClass('slideUp').addClass('slideDown'); setTimeout(function() { if ( $('#favorite-inside').hasClass('slideDown') ) { $('#favorite-inside').slideDown(100); $('#favorite-first').addClass('slide-down'); } }, 200); }).bind('mouseleave', function() { $('#favorite-inside').removeClass('slideDown').addClass('slideUp'); setTimeout(function() { if ( $('#favorite-inside').hasClass('slideUp') ) { $('#favorite-inside').slideUp(100, function() { $('#favorite-first').removeClass('slide-down'); }); } }, 300); }); } }; $(document).ready(function(){ adminMenu.init(); }); // 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 = { links: { 'screen-options-link-wrap': 'screen-options-wrap', 'contextual-help-link-wrap': 'contextual-help-wrap' }, init: function() { $('.screen-meta-toggle').click( screenMeta.toggleEvent ); }, toggleEvent: function( e ) { var panel; e.preventDefault(); // Check to see if we found a panel. if ( ! screenMeta.links[ this.id ] ) return; panel = $('#' + screenMeta.links[ this.id ]); if ( panel.is(':visible') ) screenMeta.close( panel, $(this) ); else screenMeta.open( panel, $(this) ); }, open: function( panel, link ) { $('.screen-meta-toggle').not( link ).css('visibility', 'hidden'); panel.slideDown( 'fast', function() { link.addClass('screen-meta-active'); }); }, close: function( panel, link ) { panel.slideUp( 'fast', function() { link.removeClass('screen-meta-active'); $('.screen-meta-toggle').css('visibility', ''); }); } }; $(document).ready( function() { var lastClicked = false, checks, first, last, checked, dropdown, pageInput = $('input[name="paged"]'), currentPage; // 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(); // User info dropdown. dropdown = { doc: $(document), element: $('#user_info'), open: function() { if ( ! dropdown.element.hasClass('active') ) { dropdown.element.addClass('active'); dropdown.doc.one( 'click', dropdown.close ); return false; } }, close: function() { dropdown.element.removeClass('active'); } }; dropdown.element.click( dropdown.open ); // check all checkboxes $('tbody').children().children('.check-column').find(':checkbox').click( function(e) { if ( 'undefined' == e.shiftKey ) { return true; } if ( e.shiftKey ) { if ( !lastClicked ) { return true; } checks = $( lastClicked ).closest( 'form' ).find( ':checkbox' ); first = checks.index( lastClicked ); last = checks.index( this ); checked = $(this).prop('checked'); if ( 0 < first && 0 < last && first != last ) { checks.slice( first, last ).prop( 'checked', function(){ if ( $(this).closest('tr').is(':visible') ) return checked; return false; }); } } lastClicked = this; return true; }); $('thead, tfoot').find('.check-column :checkbox').click( function(e) { var c = $(this).prop('checked'), kbtoggle = 'undefined' == typeof toggleWithKeyboard ? false : toggleWithKeyboard, toggle = e.shiftKey || kbtoggle; $(this).closest( 'table' ).children( 'tbody' ).filter(':visible') .children().children('.check-column').find(':checkbox') .prop('checked', function() { if ( $(this).closest('tr').is(':hidden') ) return false; if ( toggle ) return $(this).prop( 'checked' ); else if (c) return true; return false; }); $(this).closest('table').children('thead, tfoot').filter(':visible') .children().children('.check-column').find(':checkbox') .prop('checked', function() { if ( toggle ) return false; else if (c) return true; return false; }); }); $('#default-password-nag-no').click( function() { setUserSetting('default_password_nag', 'hide'); $('div.default-password-nag').hide(); return false; }); // tab in textareas $('#newcontent').bind('keydown.wpevent_InsertTab', function(e) { if ( e.keyCode != 9 ) return true; var el = e.target, selStart = el.selectionStart, selEnd = el.selectionEnd, val = el.value, scroll, sel; try { this.lastKey = 9; // not a standard DOM property, lastKey is to help stop Opera tab event. See blur handler below. } catch(err) {} if ( document.selection ) { el.focus(); sel = document.selection.createRange(); sel.text = '\t'; } else if ( selStart >= 0 ) { scroll = this.scrollTop; el.value = val.substring(0, selStart).concat('\t', val.substring(selEnd) ); el.selectionStart = el.selectionEnd = selStart + 1; this.scrollTop = scroll; } if ( e.stopPropagation ) e.stopPropagation(); if ( e.preventDefault ) e.preventDefault(); }); $('#newcontent').bind('blur.wpevent_InsertTab', function(e) { if ( this.lastKey && 9 == this.lastKey ) this.focus(); }); if ( pageInput.length ) { currentPage = pageInput.val(); pageInput.closest('form').submit( function(){ // Reset paging var for new filters/searches. See #17685. if ( pageInput.val() == currentPage ) pageInput.val('1'); }); } }); // internal use $(document).bind( 'wp_CloseOnEscape', function( e, data ) { if ( typeof(data.cb) != 'function' ) return; if ( typeof(data.condition) != 'function' || data.condition() ) data.cb(); return true; }); })(jQuery);
JavaScript
(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() { $('#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)}); $('#first_name, #last_name, #nickname').blur(function(){ var select = $('#display_name'), current = select.find('option:selected').attr('id'), 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; } $('option', select).remove(); $.each(inputs, function( id, value ) { var val = value.replace(/<\/?[a-z][^>]*>/gi, ''); if ( inputs[id].length && $.inArray( val, dub ) == -1 ) { dub.push(val); $('<option />', { 'id': id, 'text': val, 'selected': (id == current) }).appendTo( select ); } }); }); }); })(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) { return tags.replace(/\s*,\s*/g, ',').replace(/,+/g, ',').replace(/[,\s]+$/, '').replace(/^[,\s]+/, ''); }, parseTags : function(el) { var id = el.id, num = id.split('-check-num-')[1], taxbox = $(el).closest('.tagsdiv'), thetags = taxbox.find('.the-tags'), current_tags = thetags.val().split(','), 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(',') ) ); 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(','); 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 text, tags = $('.the-tags', el), newtag = $('input.newtag', el), newtags; text = a ? $(a).text() : newtag.val(); tagsval = tags.val(); newtags = tagsval ? tagsval + ',' + text : text; newtags = this.clean( newtags ); newtags = array_unique_noempty( newtags.split(',') ).join(','); 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: "," } ); }); // save tags on post save/publish $('#post').submit(function(){ $('div.tagsdiv').each( function() { tagBox.flushTags(this, false, 1); }); }); // tag cloud $('a.tagcloud-link').click(function(){ tagBox.get( $(this).attr('id') ); $(this).unbind().click(function(){ $(this).siblings('.the-tagcloud').toggle(); return false; }); return false; }); } }; commentsBox = { st : 0, get : function(total, num) { var st = this.st, data; if ( ! num ) num = 20; this.st += num; this.total = total; $('#commentsdiv img.waiting').show(); data = { 'action' : 'get-comments', 'mode' : 'single', '_ajax_nonce' : $('#add_comment_nonce').val(), 'p' : $('#post_ID').val(), 'start' : st, 'number' : num }; $.post(ajaxurl, data, function(r) { r = wpAjax.parseAjaxResponse(r); $('#commentsdiv .widefat').show(); $('#commentsdiv img.waiting').hide(); if ( 'object' == typeof r && r.responses[0] ) { $('#the-comment-list').append( r.responses[0].data ); theList = theExtraList = null; $("a[className*=':']").unbind(); if ( commentsBox.st > commentsBox.total ) $('#show-comments').hide(); else $('#show-comments').html(postL10n.showcomm); return; } else if ( 1 == r ) { $('#show-comments').parent().html(postL10n.endcomm); return; } $('#the-comment-list').append('<tr><td colspan="2">'+wpAjax.broken+'</td></tr>'); } ); return false; } }; WPSetThumbnailHTML = function(html){ $('.inside', '#postimagediv').html(html); }; WPSetThumbnailID = function(id){ var field = $('input[value="_thumbnail_id"]', '#list-table'); if ( field.size() > 0 ) { $('#meta\\[' + field.attr('id').match(/[0-9]+/) + '\\]\\[value\\]').text(id); } }; WPRemoveThumbnail = function(nonce){ $.post(ajaxurl, { action:"set-post-thumbnail", post_id: $('#post_ID').val(), thumbnail_id: -1, _ajax_nonce: nonce, cookie: encodeURIComponent(document.cookie) }, function(str){ if ( str == '0' ) { alert( setPostThumbnailL10n.error ); } else { WPSetThumbnailHTML(str); } } ); }; })(jQuery); jQuery(document).ready( function($) { var stamp, visibility, sticky = '', last = 0, co = $('#content'); postboxes.add_postbox_toggles(pagenow); // multi-taxonomies if ( $('#tagsdiv-post_tag').length ) { tagBox.init(); } else { $('#side-sortables, #normal-sortables, #advanced-sortables').children('div.postbox').each(function(){ if ( this.id.indexOf('tagsdiv-') === 0 ) { tagBox.init(); return false; } }); } // categories $('.categorydiv').each( function(){ var this_id = $(this).attr('id'), noSyncChecks = false, syncChecks, catAddAfter, taxonomyParts, taxonomy, settingName; taxonomyParts = this_id.split('-'); taxonomyParts.shift(); taxonomy = taxonomyParts.join('-'); settingName = taxonomy + '_tab'; if ( taxonomy == 'category' ) settingName = 'cats'; // TODO: move to jQuery 1.3+, support for multiple hierarchical taxonomies, see wp-lists.dev.js $('a', '#' + taxonomy + '-tabs').click( function(){ var t = $(this).attr('href'); $(this).parent().addClass('tabs').siblings('li').removeClass('tabs'); $('#' + taxonomy + '-tabs').siblings('.tabs-panel').hide(); $(t).show(); if ( '#' + taxonomy + '-all' == t ) deleteUserSetting(settingName); else setUserSetting(settingName, 'pop'); return false; }); if ( getUserSetting(settingName) ) $('a[href="#' + taxonomy + '-pop"]', '#' + taxonomy + '-tabs').click(); // Ajax Cat $('#new' + taxonomy).one( 'focus', function() { $(this).val( '' ).removeClass( 'form-input-tip' ) } ); $('#' + taxonomy + '-add-submit').click( function(){ $('#new' + taxonomy).focus(); }); syncChecks = function() { if ( noSyncChecks ) return; noSyncChecks = true; var th = jQuery(this), c = th.is(':checked'), id = th.val().toString(); $('#in-' + taxonomy + '-' + id + ', #in-' + taxonomy + '-category-' + id).prop( 'checked', c ); noSyncChecks = false; }; catAddBefore = function( s ) { if ( !$('#new'+taxonomy).val() ) return false; s.data += '&' + $( ':checked', '#'+taxonomy+'checklist' ).serialize(); return s; }; catAddAfter = function( r, s ) { var sup, drop = $('#new'+taxonomy+'_parent'); if ( 'undefined' != s.parsed.responses[0] && (sup = s.parsed.responses[0].supplemental.newcat_parent) ) { drop.before(sup); drop.remove(); } }; $('#' + taxonomy + 'checklist').wpList({ alt: '', response: taxonomy + '-ajax-response', addBefore: catAddBefore, addAfter: catAddAfter }); $('#' + taxonomy + '-add-toggle').click( function() { $('#' + taxonomy + '-adder').toggleClass( 'wp-hidden-children' ); $('a[href="#' + taxonomy + '-all"]', '#' + taxonomy + '-tabs').click(); $('#new'+taxonomy).focus(); return false; }); $('#' + taxonomy + 'checklist li.popular-category :checkbox, #' + taxonomy + 'checklist-pop :checkbox').live( 'click', function(){ var t = $(this), c = t.is(':checked'), id = t.val(); if ( id && t.parents('#taxonomy-'+taxonomy).length ) $('#in-' + taxonomy + '-' + id + ', #in-popular-' + taxonomy + '-' + id).prop( 'checked', c ); }); }); // end cats // Custom Fields if ( $('#postcustom').length ) { $('#the-list').wpList( { addAfter: function( xml, s ) { $('table#list-table').show(); }, addBefore: function( s ) { s.data += '&post_id=' + $('#post_ID').val(); return s; } }); } // submitdiv if ( $('#submitdiv').length ) { stamp = $('#timestamp').html(); visibility = $('#post-visibility-display').html(); function updateVisibility() { var pvSelect = $('#post-visibility-select'); if ( $('input:radio:checked', pvSelect).val() != 'public' ) { $('#sticky').prop('checked', false); $('#sticky-span').hide(); } else { $('#sticky-span').show(); } if ( $('input:radio:checked', pvSelect).val() != 'password' ) { $('#password-span').hide(); } else { $('#password-span').show(); } } function updateText() { var attemptedDate, originalDate, currentDate, publishOn, postStatus = $('#post_status'), optPublish = $('option[value="publish"]', postStatus), aa = $('#aa').val(), mm = $('#mm').val(), jj = $('#jj').val(), hh = $('#hh').val(), mn = $('#mn').val(); attemptedDate = new Date( aa, mm - 1, jj, hh, mn ); originalDate = new Date( $('#hidden_aa').val(), $('#hidden_mm').val() -1, $('#hidden_jj').val(), $('#hidden_hh').val(), $('#hidden_mn').val() ); currentDate = new Date( $('#cur_aa').val(), $('#cur_mm').val() -1, $('#cur_jj').val(), $('#cur_hh').val(), $('#cur_mn').val() ); if ( attemptedDate.getFullYear() != aa || (1 + attemptedDate.getMonth()) != mm || attemptedDate.getDate() != jj || attemptedDate.getMinutes() != mn ) { $('.timestamp-wrap', '#timestampdiv').addClass('form-invalid'); return false; } else { $('.timestamp-wrap', '#timestampdiv').removeClass('form-invalid'); } if ( attemptedDate > currentDate && $('#original_post_status').val() != 'future' ) { publishOn = postL10n.publishOnFuture; $('#publish').val( postL10n.schedule ); } else if ( attemptedDate <= currentDate && $('#original_post_status').val() != 'publish' ) { publishOn = postL10n.publishOn; $('#publish').val( postL10n.publish ); } else { publishOn = postL10n.publishOnPast; $('#publish').val( postL10n.update ); } if ( originalDate.toUTCString() == attemptedDate.toUTCString() ) { //hack $('#timestamp').html(stamp); } else { $('#timestamp').html( publishOn + ' <b>' + $('option[value="' + $('#mm').val() + '"]', '#mm').text() + ' ' + jj + ', ' + aa + ' @ ' + hh + ':' + mn + '</b> ' ); } if ( $('input:radio:checked', '#post-visibility-select').val() == 'private' ) { $('#publish').val( postL10n.update ); if ( optPublish.length == 0 ) { postStatus.append('<option value="publish">' + postL10n.privatelyPublished + '</option>'); } else { optPublish.html( postL10n.privatelyPublished ); } $('option[value="publish"]', postStatus).prop('selected', true); $('.edit-post-status', '#misc-publishing-actions').hide(); } else { if ( $('#original_post_status').val() == 'future' || $('#original_post_status').val() == 'draft' ) { if ( optPublish.length ) { optPublish.remove(); postStatus.val($('#hidden_post_status').val()); } } else { optPublish.html( postL10n.published ); } if ( postStatus.is(':hidden') ) $('.edit-post-status', '#misc-publishing-actions').show(); } $('#post-status-display').html($('option:selected', postStatus).text()); if ( $('option:selected', postStatus).val() == 'private' || $('option:selected', postStatus).val() == 'publish' ) { $('#save-post').hide(); } else { $('#save-post').show(); if ( $('option:selected', postStatus).val() == 'pending' ) { $('#save-post').show().val( postL10n.savePending ); } else { $('#save-post').show().val( postL10n.saveDraft ); } } return true; } $('.edit-visibility', '#visibility').click(function () { if ($('#post-visibility-select').is(":hidden")) { updateVisibility(); $('#post-visibility-select').slideDown('fast'); $(this).hide(); } return false; }); $('.cancel-post-visibility', '#post-visibility-select').click(function () { $('#post-visibility-select').slideUp('fast'); $('#visibility-radio-' + $('#hidden-post-visibility').val()).prop('checked', true); $('#post_password').val($('#hidden_post_password').val()); $('#sticky').prop('checked', $('#hidden-post-sticky').prop('checked')); $('#post-visibility-display').html(visibility); $('.edit-visibility', '#visibility').show(); updateText(); return false; }); $('.save-post-visibility', '#post-visibility-select').click(function () { // crazyhorse - multiple ok cancels var pvSelect = $('#post-visibility-select'); pvSelect.slideUp('fast'); $('.edit-visibility', '#visibility').show(); updateText(); if ( $('input:radio:checked', pvSelect).val() != 'public' ) { $('#sticky').prop('checked', false); } // WEAPON LOCKED if ( true == $('#sticky').prop('checked') ) { sticky = 'Sticky'; } else { sticky = ''; } $('#post-visibility-display').html( postL10n[$('input:radio:checked', pvSelect).val() + sticky] ); return false; }); $('input:radio', '#post-visibility-select').change(function() { updateVisibility(); }); $('#timestampdiv').siblings('a.edit-timestamp').click(function() { if ($('#timestampdiv').is(":hidden")) { $('#timestampdiv').slideDown('fast'); $(this).hide(); } return false; }); $('.cancel-timestamp', '#timestampdiv').click(function() { $('#timestampdiv').slideUp('fast'); $('#mm').val($('#hidden_mm').val()); $('#jj').val($('#hidden_jj').val()); $('#aa').val($('#hidden_aa').val()); $('#hh').val($('#hidden_hh').val()); $('#mn').val($('#hidden_mn').val()); $('#timestampdiv').siblings('a.edit-timestamp').show(); updateText(); return false; }); $('.save-timestamp', '#timestampdiv').click(function () { // crazyhorse - multiple ok cancels if ( updateText() ) { $('#timestampdiv').slideUp('fast'); $('#timestampdiv').siblings('a.edit-timestamp').show(); } return false; }); $('#post-status-select').siblings('a.edit-post-status').click(function() { if ($('#post-status-select').is(":hidden")) { $('#post-status-select').slideDown('fast'); $(this).hide(); } return false; }); $('.save-post-status', '#post-status-select').click(function() { $('#post-status-select').slideUp('fast'); $('#post-status-select').siblings('a.edit-post-status').show(); updateText(); return false; }); $('.cancel-post-status', '#post-status-select').click(function() { $('#post-status-select').slideUp('fast'); $('#post_status').val($('#hidden_post_status').val()); $('#post-status-select').siblings('a.edit-post-status').show(); updateText(); return false; }); } // end submitdiv // permalink if ( $('#edit-slug-box').length ) { editPermalink = function(post_id) { var i, c = 0, e = $('#editable-post-name'), revert_e = e.html(), real_slug = $('#post_name'), revert_slug = real_slug.val(), b = $('#edit-slug-buttons'), revert_b = b.html(), full = $('#editable-post-name-full').html(); $('#view-post-btn').hide(); b.html('<a href="#" class="save button">'+postL10n.ok+'</a> <a class="cancel" href="#">'+postL10n.cancel+'</a>'); b.children('.save').click(function() { var new_slug = e.children('input').val(); $.post(ajaxurl, { action: 'sample-permalink', post_id: post_id, new_slug: new_slug, new_title: $('#title').val(), samplepermalinknonce: $('#samplepermalinknonce').val() }, function(data) { $('#edit-slug-box').html(data); b.html(revert_b); real_slug.val(new_slug); makeSlugeditClickable(); $('#view-post-btn').show(); }); return false; }); $('.cancel', '#edit-slug-buttons').click(function() { $('#view-post-btn').show(); e.html(revert_e); b.html(revert_b); real_slug.val(revert_slug); return false; }); for ( i = 0; i < full.length; ++i ) { if ( '%' == full.charAt(i) ) c++; } slug_value = ( c > full.length / 4 ) ? '' : full; e.html('<input type="text" id="new-post-slug" value="'+slug_value+'" />').children('input').keypress(function(e){ var key = e.keyCode || 0; // on enter, just save the new slug, don't save the post if ( 13 == key ) { b.children('.save').click(); return false; } if ( 27 == key ) { b.children('.cancel').click(); return false; } real_slug.val(this.value); }).focus(); } makeSlugeditClickable = function() { $('#editable-post-name').click(function() { $('#edit-slug-buttons').children('.edit-slug').click(); }); } makeSlugeditClickable(); } // word count if ( typeof(wpWordCount) != 'undefined' ) { $(document).triggerHandler('wpcountwords', [ co.val() ]); co.keyup( function(e) { var k = e.keyCode || e.charCode; if ( k == last ) return true; if ( 13 == k || 8 == last || 46 == last ) $(document).triggerHandler('wpcountwords', [ co.val() ]); last = k; return true; }); } wptitlehint = function(id) { id = id || 'title'; var title = $('#' + id), titleprompt = $('#' + id + '-prompt-text'); if ( title.val() == '' ) titleprompt.css('visibility', ''); titleprompt.click(function(){ $(this).css('visibility', 'hidden'); title.focus(); }); title.blur(function(){ if ( this.value == '' ) titleprompt.css('visibility', ''); }).focus(function(){ titleprompt.css('visibility', 'hidden'); }).keydown(function(e){ titleprompt.css('visibility', 'hidden'); $(this).unbind(e); }); } wptitlehint(); });
JavaScript
(function($) { inlineEditTax = { init : function() { var t = this, row = $('#inline-edit'); t.type = $('#the-list').attr('class').substr(5); t.what = '#'+t.type+'-'; $('.editinline').live('click', function(){ inlineEditTax.edit(this); return false; }); // prepare the edit row row.keyup(function(e) { if(e.which == 27) return inlineEditTax.revert(); }); $('a.cancel', row).click(function() { return inlineEditTax.revert(); }); $('a.save', row).click(function() { return inlineEditTax.save(this); }); $('input, select', row).keydown(function(e) { if(e.which == 13) return inlineEditTax.save(this); }); $('#posts-filter input[type="submit"]').mousedown(function(e){ t.revert(); }); }, toggle : function(el) { var t = this; $(t.what+t.getId(el)).css('display') == 'none' ? t.revert() : t.edit(el); }, edit : function(id) { var t = this, editRow; t.revert(); if ( typeof(id) == 'object' ) id = t.getId(id); editRow = $('#inline-edit').clone(true), rowData = $('#inline_'+id); $('td', editRow).attr('colspan', $('.widefat:first thead th:visible').length); if ( $(t.what+id).hasClass('alternate') ) $(editRow).addClass('alternate'); $(t.what+id).hide().after(editRow); $(':input[name="name"]', editRow).val( $('.name', rowData).text() ); $(':input[name="slug"]', editRow).val( $('.slug', rowData).text() ); $(editRow).attr('id', 'edit-'+id).addClass('inline-editor').show(); $('.ptitle', editRow).eq(0).focus(); return false; }, save : function(id) { var params, fields, tax = $('input[name="taxonomy"]').val() || ''; if( typeof(id) == 'object' ) id = this.getId(id); $('table.widefat .inline-edit-save .waiting').show(); params = { action: 'inline-save-tax', tax_type: this.type, tax_ID: id, taxonomy: tax }; fields = $('#edit-'+id+' :input').serialize(); params = fields + '&' + $.param(params); // make ajax request $.post('admin-ajax.php', params, function(r) { var row, new_id; $('table.widefat .inline-edit-save .waiting').hide(); if (r) { if ( -1 != r.indexOf('<tr') ) { $(inlineEditTax.what+id).remove(); new_id = $(r).attr('id'); $('#edit-'+id).before(r).remove(); row = new_id ? $('#'+new_id) : $(inlineEditTax.what+id); row.hide().fadeIn(); } else $('#edit-'+id+' .inline-edit-save .error').html(r).show(); } else $('#edit-'+id+' .inline-edit-save .error').html(inlineEditL10n.error).show(); } ); return false; }, revert : function() { var id = $('table.widefat tr.inline-editor').attr('id'); if ( id ) { $('table.widefat .inline-edit-save .waiting').hide(); $('#'+id).remove(); id = id.substr( id.lastIndexOf('-') + 1 ); $(this.what+id).show(); } return false; }, getId : function(o) { var id = o.tagName == 'TR' ? o.id : $(o).parents('tr').attr('id'), parts = id.split('-'); return parts[parts.length - 1]; } }; $(document).ready(function(){inlineEditTax.init();}); })(jQuery);
JavaScript
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
jQuery(document).ready( function($) { var stamp = $('#timestamp').html(); $('.edit-timestamp').click(function () { if ($('#timestampdiv').is(":hidden")) { $('#timestampdiv').slideDown("normal"); $('.edit-timestamp').hide(); } return false; }); $('.cancel-timestamp').click(function() { $('#timestampdiv').slideUp("normal"); $('#mm').val($('#hidden_mm').val()); $('#jj').val($('#hidden_jj').val()); $('#aa').val($('#hidden_aa').val()); $('#hh').val($('#hidden_hh').val()); $('#mn').val($('#hidden_mn').val()); $('#timestamp').html(stamp); $('.edit-timestamp').show(); return false; }); $('.save-timestamp').click(function () { // crazyhorse - multiple ok cancels var aa = $('#aa').val(), mm = $('#mm').val(), jj = $('#jj').val(), hh = $('#hh').val(), mn = $('#mn').val(), newD = new Date( aa, mm - 1, jj, hh, mn ); if ( newD.getFullYear() != aa || (1 + newD.getMonth()) != mm || newD.getDate() != jj || newD.getMinutes() != mn ) { $('.timestamp-wrap', '#timestampdiv').addClass('form-invalid'); return false; } else { $('.timestamp-wrap', '#timestampdiv').removeClass('form-invalid'); } $('#timestampdiv').slideUp("normal"); $('.edit-timestamp').show(); $('#timestamp').html( commentL10n.submittedOn + ' <b>' + $( '#mm option[value="' + mm + '"]' ).text() + ' ' + jj + ', ' + aa + ' @ ' + hh + ':' + mn + '</b> ' ); return false; }); });
JavaScript
jQuery(document).ready(function($) { 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(); return false; }); $('#hideall').click(function(){ $('#sort-buttons span a').toggle(); $('a.describe-toggle-on').show(); $('a.describe-toggle-off, table.slidetoggle').hide(); 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
/*! * Farbtastic: jQuery color picker plug-in v1.3u * * Licensed under the GPL license: * http://www.gnu.org/licenses/gpl.html */ (function($) { $.fn.farbtastic = function (options) { $.farbtastic(this, options); return this; }; $.farbtastic = function (container, callback) { var container = $(container).get(0); return container.farbtastic || (container.farbtastic = new $._farbtastic(container, callback)); }; $._farbtastic = function (container, callback) { // Store farbtastic object var fb = this; // Insert markup $(container).html('<div class="farbtastic"><div class="color"></div><div class="wheel"></div><div class="overlay"></div><div class="h-marker marker"></div><div class="sl-marker marker"></div></div>'); var e = $('.farbtastic', container); fb.wheel = $('.wheel', container).get(0); // Dimensions fb.radius = 84; fb.square = 100; fb.width = 194; // Fix background PNGs in IE6 if (navigator.appVersion.match(/MSIE [0-6]\./)) { $('*', e).each(function () { if (this.currentStyle.backgroundImage != 'none') { var image = this.currentStyle.backgroundImage; image = this.currentStyle.backgroundImage.substring(5, image.length - 2); $(this).css({ 'backgroundImage': 'none', 'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='" + image + "')" }); } }); } /** * Link to the given element(s) or callback. */ fb.linkTo = function (callback) { // Unbind previous nodes if (typeof fb.callback == 'object') { $(fb.callback).unbind('keyup', fb.updateValue); } // Reset color fb.color = null; // Bind callback or elements if (typeof callback == 'function') { fb.callback = callback; } else if (typeof callback == 'object' || typeof callback == 'string') { fb.callback = $(callback); fb.callback.bind('keyup', fb.updateValue); if (fb.callback.get(0).value) { fb.setColor(fb.callback.get(0).value); } } return this; }; fb.updateValue = function (event) { if (this.value && this.value != fb.color) { fb.setColor(this.value); } }; /** * Change color with HTML syntax #123456 */ fb.setColor = function (color) { var unpack = fb.unpack(color); if (fb.color != color && unpack) { fb.color = color; fb.rgb = unpack; fb.hsl = fb.RGBToHSL(fb.rgb); fb.updateDisplay(); } return this; }; /** * Change color with HSL triplet [0..1, 0..1, 0..1] */ fb.setHSL = function (hsl) { fb.hsl = hsl; fb.rgb = fb.HSLToRGB(hsl); fb.color = fb.pack(fb.rgb); fb.updateDisplay(); return this; }; ///////////////////////////////////////////////////// /** * Retrieve the coordinates of the given event relative to the center * of the widget. */ fb.widgetCoords = function (event) { var offset = $(fb.wheel).offset(); return { x: (event.pageX - offset.left) - fb.width / 2, y: (event.pageY - offset.top) - fb.width / 2 }; }; /** * Mousedown handler */ fb.mousedown = function (event) { // Capture mouse if (!document.dragging) { $(document).bind('mousemove', fb.mousemove).bind('mouseup', fb.mouseup); document.dragging = true; } // Check which area is being dragged var pos = fb.widgetCoords(event); fb.circleDrag = Math.max(Math.abs(pos.x), Math.abs(pos.y)) * 2 > fb.square; // Process fb.mousemove(event); return false; }; /** * Mousemove handler */ fb.mousemove = function (event) { // Get coordinates relative to color picker center var pos = fb.widgetCoords(event); // Set new HSL parameters if (fb.circleDrag) { var hue = Math.atan2(pos.x, -pos.y) / 6.28; if (hue < 0) hue += 1; fb.setHSL([hue, fb.hsl[1], fb.hsl[2]]); } else { var sat = Math.max(0, Math.min(1, -(pos.x / fb.square) + .5)); var lum = Math.max(0, Math.min(1, -(pos.y / fb.square) + .5)); fb.setHSL([fb.hsl[0], sat, lum]); } return false; }; /** * Mouseup handler */ fb.mouseup = function () { // Uncapture mouse $(document).unbind('mousemove', fb.mousemove); $(document).unbind('mouseup', fb.mouseup); document.dragging = false; }; /** * Update the markers and styles */ fb.updateDisplay = function () { // Markers var angle = fb.hsl[0] * 6.28; $('.h-marker', e).css({ left: Math.round(Math.sin(angle) * fb.radius + fb.width / 2) + 'px', top: Math.round(-Math.cos(angle) * fb.radius + fb.width / 2) + 'px' }); $('.sl-marker', e).css({ left: Math.round(fb.square * (.5 - fb.hsl[1]) + fb.width / 2) + 'px', top: Math.round(fb.square * (.5 - fb.hsl[2]) + fb.width / 2) + 'px' }); // Saturation/Luminance gradient $('.color', e).css('backgroundColor', fb.pack(fb.HSLToRGB([fb.hsl[0], 1, 0.5]))); // Linked elements or callback if (typeof fb.callback == 'object') { // Set background/foreground color $(fb.callback).css({ backgroundColor: fb.color, color: fb.hsl[2] > 0.5 ? '#000' : '#fff' }); // Change linked value $(fb.callback).each(function() { if (this.value && this.value != fb.color) { this.value = fb.color; } }); } else if (typeof fb.callback == 'function') { fb.callback.call(fb, fb.color); } }; /* Various color utility functions */ fb.pack = function (rgb) { var r = Math.round(rgb[0] * 255); var g = Math.round(rgb[1] * 255); var b = Math.round(rgb[2] * 255); return '#' + (r < 16 ? '0' : '') + r.toString(16) + (g < 16 ? '0' : '') + g.toString(16) + (b < 16 ? '0' : '') + b.toString(16); }; fb.unpack = function (color) { if (color.length == 7) { return [parseInt('0x' + color.substring(1, 3)) / 255, parseInt('0x' + color.substring(3, 5)) / 255, parseInt('0x' + color.substring(5, 7)) / 255]; } else if (color.length == 4) { return [parseInt('0x' + color.substring(1, 2)) / 15, parseInt('0x' + color.substring(2, 3)) / 15, parseInt('0x' + color.substring(3, 4)) / 15]; } }; fb.HSLToRGB = function (hsl) { var m1, m2, r, g, b; var h = hsl[0], s = hsl[1], l = hsl[2]; m2 = (l <= 0.5) ? l * (s + 1) : l + s - l*s; m1 = l * 2 - m2; return [this.hueToRGB(m1, m2, h+0.33333), this.hueToRGB(m1, m2, h), this.hueToRGB(m1, m2, h-0.33333)]; }; fb.hueToRGB = function (m1, m2, h) { h = (h < 0) ? h + 1 : ((h > 1) ? h - 1 : h); if (h * 6 < 1) return m1 + (m2 - m1) * h * 6; if (h * 2 < 1) return m2; if (h * 3 < 2) return m1 + (m2 - m1) * (0.66666 - h) * 6; return m1; }; fb.RGBToHSL = function (rgb) { var min, max, delta, h, s, l; var r = rgb[0], g = rgb[1], b = rgb[2]; min = Math.min(r, Math.min(g, b)); max = Math.max(r, Math.max(g, b)); delta = max - min; l = (min + max) / 2; s = 0; if (l > 0 && l < 1) { s = delta / (l < 0.5 ? (2 * l) : (2 - 2 * l)); } h = 0; if (delta > 0) { if (max == r && max != g) h += (g - b) / delta; if (max == g && max != b) h += (2 + (b - r) / delta); if (max == b && max != r) h += (4 + (r - g) / delta); h /= 6; } return [h, s, l]; }; // Install mousedown handler (the others are set on the document on-demand) $('*', e).mousedown(fb.mousedown); // Init color fb.setColor('#000000'); // Set linked elements/callback if (callback) { fb.linkTo(callback); } }; })(jQuery);
JavaScript
var farbtastic; function pickColor(color) { farbtastic.setColor(color); jQuery('#background-color').val(color); jQuery('#custom-background-image').css('background-color', color); if ( color && color !== '#' ) jQuery('#clearcolor').show(); else jQuery('#clearcolor').hide(); } jQuery(document).ready(function() { jQuery('#pickcolor').click(function() { jQuery('#colorPickerDiv').show(); return false; }); jQuery('#clearcolor a').click( function(e) { pickColor(''); e.preventDefault(); }); jQuery('#background-color').keyup(function() { var _hex = jQuery('#background-color').val(), hex = _hex; if ( hex.charAt(0) != '#' ) hex = '#' + hex; hex = hex.replace(/[^#a-fA-F0-9]+/, ''); if ( hex != _hex ) jQuery('#background-color').val(hex); if ( hex.length == 4 || hex.length == 7 ) pickColor( hex ); }); jQuery('input[name="background-position-x"]').change(function() { jQuery('#custom-background-image').css('background-position', jQuery(this).val() + ' top'); }); jQuery('input[name="background-repeat"]').change(function() { jQuery('#custom-background-image').css('background-repeat', jQuery(this).val()); }); farbtastic = jQuery.farbtastic('#colorPickerDiv', function(color) { pickColor(color); }); pickColor(jQuery('#background-color').val()); jQuery(document).mousedown(function(){ jQuery('#colorPickerDiv').each(function(){ var display = jQuery(this).css('display'); if ( display == 'block' ) jQuery(this).fadeOut(2); }); }); });
JavaScript
// send html to the post editor function send_to_editor(h) { var ed; if ( typeof tinyMCE != 'undefined' && ( ed = tinyMCE.activeEditor ) && !ed.isHidden() ) { // restore caret position on IE if ( tinymce.isIE && ed.windowManager.insertimagebookmark ) ed.selection.moveToBookmark(ed.windowManager.insertimagebookmark); if ( h.indexOf('[caption') === 0 ) { if ( ed.plugins.wpeditimage ) h = ed.plugins.wpeditimage._do_shcode(h); } else if ( h.indexOf('[gallery') === 0 ) { if ( ed.plugins.wpgallery ) h = ed.plugins.wpgallery._do_gallery(h); } else if ( h.indexOf('[embed') === 0 ) { if ( ed.plugins.wordpress ) h = ed.plugins.wordpress._setEmbed(h); } ed.execCommand('mceInsertContent', false, h); } else if ( typeof edInsertContent == 'function' ) { edInsertContent(edCanvas, h); } else { jQuery( edCanvas ).val( jQuery( edCanvas ).val() + h ); } tb_remove(); } // 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.activeEditor ) && !ed.isHidden() ) { ed.focus(); ed.windowManager.insertimagebookmark = ed.selection.getBookmark(); } }); }); })(jQuery);
JavaScript
var findPosts; (function($){ findPosts = { open : function(af_name, af_val) { var st = document.documentElement.scrollTop || $(document).scrollTop(); if ( af_name && af_val ) { $('#affected').attr('name', af_name).val(af_val); } $('#find-posts').show().draggable({ handle: '#find-posts-head' }).css({'top':st + 50 + 'px','left':'50%','marginLeft':'-250px'}); $('#find-posts-input').focus().keyup(function(e){ if (e.which == 27) { findPosts.close(); } // close on Escape }); return false; }, close : function() { $('#find-posts-response').html(''); $('#find-posts').draggable('destroy').hide(); }, send : function() { var post = { ps: $('#find-posts-input').val(), action: 'find_posts', _ajax_nonce: $('#_ajax_nonce').val() }; var selectedItem; $("input[@name='itemSelect[]']:checked").each(function() { selectedItem = $(this).val() }); post['post_type'] = selectedItem; $.ajax({ type : 'POST', url : ajaxurl, data : post, success : function(x) { findPosts.show(x); }, error : function(r) { findPosts.error(r); } }); }, show : function(x) { if ( typeof(x) == 'string' ) { this.error({'responseText': x}); return; } var r = wpAjax.parseAjaxResponse(x); if ( r.errors ) { this.error({'responseText': wpAjax.broken}); } r = r.responses[0]; $('#find-posts-response').html(r.data); }, error : function(r) { var er = r.statusText; if ( r.responseText ) { er = r.responseText.replace( /<.[^<>]*?>/g, '' ); } if ( er ) { $('#find-posts-response').html(er); } } }; $(document).ready(function() { $('#find-posts-submit').click(function(e) { if ( '' == $('#find-posts-response').html() ) e.preventDefault(); }); $( '#find-posts .find-box-search :input' ).keypress( function( event ) { if ( 13 == event.which ) { findPosts.send(); return false; } } ); $( '#find-posts-search' ).click( findPosts.send ); $( '#find-posts-close' ).click( findPosts.close ); $('#doaction, #doaction2').click(function(e){ $('select[name^="action"]').each(function(){ if ( $(this).val() == 'attach' ) { e.preventDefault(); findPosts.open(); } }); }); }); })(jQuery);
JavaScript
/** * 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 : 'title', 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; s.mode = $('#' + s.editor_id).is(':hidden') ? 'tinymce' : 'html'; if ( ! s.element ) api.ui.init(); s.is_mce_on = s.has_tinymce && typeof( tinyMCE.get(s.editor_id) ) != 'undefined'; api.ui.fade( 'show', 'showing', 'shown' ); }; /** * off() * * Turns fullscreen off. */ api.off = function() { if ( ! s.visible ) return; api.ui.fade( 'hide', 'hiding', 'hidden' ); }; /** * switchmode() * * @return string - The current mode. * * @param string to - The fullscreen mode to switch to. * @event switchMode * @eventparam string to - The new mode. * @eventparam string from - The old mode. */ api.switchmode = function( to ) { var from = s.mode; if ( ! to || ! s.visible || ! s.has_tinymce ) return from; // Don't switch if the mode is the same. if ( from == to ) return from; ps.publish( 'switchMode', [ from, to ] ); s.mode = to; ps.publish( 'switchedMode', [ from, to ] ); return to; }; /** * General */ api.save = function() { var hidden = $('#hiddenaction'), old = hidden.val(), spinner = $('#wp-fullscreen-save img'), message = $('#wp-fullscreen-save span'); spinner.show(); api.savecontent(); hidden.val('wp-fullscreen-save-post'); $.post( ajaxurl, $('form#post').serialize(), function(r){ spinner.hide(); message.show(); setTimeout( function(){ message.fadeOut(1000); }, 3000 ); if ( r.last_edited ) $('#wp-fullscreen-save input').attr( 'title', r.last_edited ); }, 'json'); hidden.val(old); } api.savecontent = function() { var ed, content; $('#' + 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 = $('#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 = edCanvas.value; if ( s.has_tinymce && s.mode === 'tinymce' ) tinyMCE.execCommand('wpFullScreenInit'); s._edCanvas = edCanvas; edCanvas = s.textarea_obj; 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 s.visible = true; // init the standard TinyMCE instance if missing if ( s.has_tinymce && ! s.is_mce_on ) { htmled = document.getElementById(s.editor_id), old_val = htmled.value; htmled.value = switchEditors.wpautop( old_val ); tinyMCE.settings.setup = function(ed) { ed.onInit.add(function(ed) { ed.hide(); delete tinyMCE.settings.setup; ed.getElement().value = old_val; }); } tinyMCE.execCommand("mceAddControl", false, s.editor_id); s.is_mce_on = true; } }); ps.subscribe( 'hide', function() { // This event occurs before the overlay blocks DFW. // Make sure the correct editor is displaying. if ( s.has_tinymce && s.mode === 'tinymce' && $('#' + s.editor_id).is(':visible') ) { switchEditors.go( s.editor_id, 'tinymce' ); } else if ( s.mode === 'html' && $('#' + s.editor_id).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'); set_title_hint( $('#' + s.title_id) ); // Restore and update edCanvas. edCanvas = s._edCanvas; edCanvas.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').removeAttr('style'); if ( s.has_tinymce && s.is_mce_on ) tinyMCE.execCommand('wpFullScreenClose'); s.textarea_obj.value = ''; api.oldheight = 0; }); 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' ) { 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.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 ) wptitlehint('wp-fullscreen-title'); $(document).keyup(function(e){ var c = e.keyCode || e.charCode, a, data; if ( !fullscreen.settings.visible ) return true; if ( navigator.platform && navigator.platform.indexOf('Mac') != -1 ) a = e.ctrlKey; // Ctrl key for Mac else a = e.altKey; // Alt key for Win & Linux if ( 27 == c ) { // Esc data = { event: e, what: 'dfw', cb: fullscreen.off, condition: function(){ if ( $('#TB_window').is(':visible') || $('.wp-dialog').is(':visible') ) return false; return true; } }; if ( ! jQuery(document).triggerHandler( 'wp_CloseOnEscape', [data] ) ) fullscreen.off(); } if ( a && (61 == c || 107 == c || 187 == c) ) // + api.dfw_width(25); if ( a && (45 == c || 109 == c || 189 == c) ) // - api.dfw_width(-25); if ( a && 48 == c ) // 0 api.dfw_width(0); return false; }); // word count in HTML mode if ( typeof(wpWordCount) != 'undefined' ) { txtarea.keyup( function(e) { var k = e.keyCode || e.charCode; if ( k == last ) return true; if ( 13 == k || 8 == last || 46 == last ) $(document).triggerHandler('wpcountwords', [ txtarea.val() ]); last = k; return true; }); } topbar.mouseenter(function(e){ s.toolbars.addClass('fullscreen-make-sticky'); $( document ).unbind( '.fullscreen' ); clearTimeout( s.timer ); s.timer = 0; }).mouseleave(function(e){ s.toolbars.removeClass('fullscreen-make-sticky'); if ( s.visible ) $( document ).bind( 'mousemove.fullscreen', function(e) { bounder( 'showToolbar', 'hideToolbar', 2000, e ); } ); }); }, fade: function( before, during, after ) { if ( ! s.element ) api.ui.init(); // If any callback bound to before returns false, bail. if ( before && ! ps.publish( before ) ) return; api.fade.In( s.element, 600, function() { if ( during ) ps.publish( during ); api.fade.Out( s.element, 600, function() { if ( after ) ps.publish( after ); }) }); } }; api.fade = { transitionend: 'transitionend webkitTransitionEnd oTransitionEnd', // Sensitivity to allow browsers to render the blank element before animating. sensitivity: 100, In: function( element, speed, callback, stop ) { callback = callback || $.noop; speed = speed || 400; stop = stop || false; if ( api.fade.transitions ) { if ( element.is(':visible') ) { element.addClass( 'fade-trigger' ); return element; } element.show(); element.first().one( this.transitionend, function() { callback(); }); setTimeout( function() { element.addClass( 'fade-trigger' ); }, this.sensitivity ); } else { if ( stop ) element.stop(); element.css( 'opacity', 1 ); element.first().fadeIn( speed, callback ); if ( element.length > 1 ) element.not(':first').fadeIn( speed ); } return element; }, Out: function( element, speed, callback, stop ) { callback = callback || $.noop; speed = speed || 400; stop = stop || false; if ( ! element.is(':visible') ) return element; if ( api.fade.transitions ) { element.first().one( api.fade.transitionend, function() { if ( element.hasClass('fade-trigger') ) return; element.hide(); callback(); }); setTimeout( function() { element.removeClass( 'fade-trigger' ); }, this.sensitivity ); } else { if ( stop ) element.stop(); element.first().fadeOut( speed, callback ); if ( element.length > 1 ) element.not(':first').fadeOut( speed ); } return element; }, transitions: (function() { // Check if the browser supports CSS 3.0 transitions var s = document.documentElement.style; return ( typeof ( s.WebkitTransition ) == 'string' || typeof ( s.MozTransition ) == 'string' || typeof ( s.OTransition ) == 'string' || typeof ( s.transition ) == 'string' ); })() }; /** * Resize API * * Automatically updates textarea height. */ api.bind_resize = function() { $(s.textarea_obj).bind('keypress.grow click.grow paste.grow', function(){ setTimeout( api.resize_textarea, 200 ); }); } api.oldheight = 0; api.resize_textarea = function() { var txt = s.textarea_obj, newheight; newheight = txt.scrollHeight > 300 ? txt.scrollHeight : 300; if ( newheight != api.oldheight ) { txt.style.height = newheight + 'px'; api.oldheight = newheight; } }; })(jQuery);
JavaScript
(function($) { wpWordCount = { settings : { strip : /<[a-zA-Z\/][^<>]*>/g, // strip HTML tags clean : /[0-9.(),;:!?%#$¿'"_+=\\/-]+/g, // regexp to remove punctuation, etc. count : /\S\s+/g // counting regexp }, block : 0, wc : function(tx) { var t = this, w = $('.word-count'), tc = 0; 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.count, function(){tc++;} ); } w.html(tc.toString()); setTimeout( function() { t.block = 0; }, 2000 ); }, 1 ); } } $(document).bind( 'wpcountwords', function(e, txt) { wpWordCount.wc(txt); }); }(jQuery));
JavaScript
// utility functions var wpCookies = { // The following functions are from Cookie.js class in TinyMCE, Moxiecode, used under LGPL. each : function(o, cb, s) { var n, l; if (!o) return 0; s = s || o; if (typeof(o.length) != 'undefined') { for (n=0, l = o.length; n<l; n++) { if (cb.call(s, o[n], n, o) === false) return 0; } } else { for (n in o) { if (o.hasOwnProperty(n)) { if (cb.call(s, o[n], n, o) === false) { return 0; } } } } return 1; }, getHash : function(n) { var v = this.get(n), h; if (v) { this.each(v.split('&'), function(v) { v = v.split('='); h = h || {}; h[v[0]] = v[1]; }); } return h; }, setHash : function(n, v, e, p, d, s) { var o = ''; this.each(v, function(v, k) { o += (!o ? '' : '&') + k + '=' + v; }); this.set(n, o, e, p, d, s); }, get : function(n) { var c = document.cookie, e, p = n + "=", b; if (!c) return; b = c.indexOf("; " + p); if (b == -1) { b = c.indexOf(p); if (b != 0) return null; } else { b += 2; } e = c.indexOf(";", b); if (e == -1) e = c.length; return decodeURIComponent(c.substring(b + p.length, e)); }, set : function(n, v, e, p, d, s) { document.cookie = n + "=" + encodeURIComponent(v) + ((e) ? "; expires=" + e.toGMTString() : "") + ((p) ? "; path=" + p : "") + ((d) ? "; domain=" + d : "") + ((s) ? "; secure" : ""); }, remove : function(n, p) { var d = new Date(); d.setTime(d.getTime() - 1000); this.set(n, '', d, p, d); } }; // Returns the value as string. Second arg or empty string is returned when value is not set. function getUserSetting( name, def ) { var o = getAllUserSettings(); if ( o.hasOwnProperty(name) ) return o[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 c = 'wp-settings-' + userSettings.uid, o = wpCookies.getHash(c) || {}, d = new Date(), p, n = name.toString().replace(/[^A-Za-z0-9_]/, ''), v = value.toString().replace(/[^A-Za-z0-9_]/, ''); if ( del ) { delete o[n]; } else { o[n] = v; } d.setTime( d.getTime() + 31536000000 ); p = userSettings.url; wpCookies.setHash(c, o, d, p); wpCookies.set('wp-settings-time-'+userSettings.uid, userSettings.time, d, p); 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 postboxes; (function($) { postboxes = { add_postbox_toggles : function(page,args) { this.init(page,args); $('.postbox h3, .postbox .handlediv').click( function() { var p = $(this).parent('.postbox'), id = p.attr('id'); if ( 'dashboard_browser_nag' == id ) return; p.toggleClass('closed'); postboxes.save_state(page); if ( id ) { if ( !p.hasClass('closed') && $.isFunction(postboxes.pbshow) ) postboxes.pbshow(id); else if ( p.hasClass('closed') && $.isFunction(postboxes.pbhide) ) postboxes.pbhide(id); } } ); $('.postbox h3 a').click( function(e) { e.stopPropagation(); } ); $('.postbox a.dismiss').click( function(e) { var hide_id = $(this).parents('.postbox').attr('id') + '-hide'; $( '#' + hide_id ).prop('checked', false).triggerHandler('click'); return false; } ); $('.hide-postbox-tog').click( function() { var box = $(this).val(); if ( $(this).prop('checked') ) { $('#' + box).show(); if ( $.isFunction( postboxes.pbshow ) ) postboxes.pbshow( box ); } else { $('#' + box).hide(); if ( $.isFunction( postboxes.pbhide ) ) postboxes.pbhide( box ); } postboxes.save_state(page); } ); $('.columns-prefs input[type="radio"]').click(function(){ var num = $(this).val(), i, el, p = $('#poststuff'); if ( p.length ) { // write pages if ( num == 2 ) { p.addClass('has-right-sidebar'); $('#side-sortables').addClass('temp-border'); } else if ( num == 1 ) { p.removeClass('has-right-sidebar'); $('#normal-sortables').append($('#side-sortables').children('.postbox')); } } else { // dashboard for ( i = 4; ( i > num && i > 1 ); i-- ) { el = $('#' + colname(i) + '-sortables'); $('#' + colname(i-1) + '-sortables').append(el.children('.postbox')); el.parent().hide(); } for ( i = 1; i <= num; i++ ) { el = $('#' + colname(i) + '-sortables'); if ( el.parent().is(':hidden') ) el.addClass('temp-border').parent().show(); } $('.postbox-container:visible').css('width', 98/num + '%'); } postboxes.save_order(page); }); function colname(n) { switch (n) { case 1: return 'normal'; break case 2: return 'side'; break case 3: return 'column3'; break case 4: return 'column4'; break default: return ''; } } }, init : function(page, args) { $.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', 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); ui.item.parent().removeClass('temp-border'); }, receive: function(e,ui) { if ( 'dashboard_browser_nag' == ui.item[0].id ) $(ui.sender).sortable('cancel'); } }); }, 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 ); }, /* Callbacks */ pbshow : false, pbhide : false }; }(jQuery));
JavaScript
/** * WordPress Administration Navigation Menu * Interface JS functions * * @version 2.0.0 * * @package WordPress * @subpackage Administration */ var wpNavMenu; (function($) { var api = wpNavMenu = { options : { menuItemDepthPerLevel : 30, // Do not use directly. Use depthToPx and pxToDepth instead. globalMaxDepth : 11 }, menuList : undefined, // Set in init. targetList : undefined, // Set in init. menusChanged : false, isRTL: !! ( 'undefined' != typeof isRtl && isRtl ), negateIfRTL: ( 'undefined' != typeof isRtl && isRtl ) ? -1 : 1, // Functions that run on init. init : function() { api.menuList = $('#menu-to-edit'); api.targetList = api.menuList; this.jQueryExtensions(); this.attachMenuEditListeners(); this.setupInputWithDefaultTitle(); this.attachQuickSearchListeners(); this.attachThemeLocationsListeners(); this.attachTabsPanelListeners(); this.attachUnsavedChangesListener(); if( api.menuList.length ) // If no menu, we're in the + tab. this.initSortables(); this.initToggles(); this.initTabManager(); }, jQueryExtensions : function() { // jQuery extensions $.fn.extend({ menuItemDepth : function() { var margin = api.isRTL ? this.eq(0).css('margin-right') : this.eq(0).css('margin-left'); return api.pxToDepth( margin && -1 != margin.indexOf('px') ? margin.slice(0, -2) : 0 ); }, updateDepthClass : function(current, prev) { return this.each(function(){ var t = $(this); prev = prev || t.menuItemDepth(); $(this).removeClass('menu-item-depth-'+ prev ) .addClass('menu-item-depth-'+ current ); }); }, shiftDepthClass : function(change) { return this.each(function(){ var t = $(this), depth = t.menuItemDepth(); $(this).removeClass('menu-item-depth-'+ depth ) .addClass('menu-item-depth-'+ (depth + change) ); }); }, childMenuItems : function() { var result = $(); this.each(function(){ var t = $(this), depth = t.menuItemDepth(), next = t.next(); while( next.length && next.menuItemDepth() > depth ) { result = result.add( next ); next = next.next(); } }); return result; }, updateParentMenuItemDBId : function() { return this.each(function(){ var item = $(this), input = item.find('.menu-item-data-parent-id'), depth = item.menuItemDepth(), parent = item.prev(); if( depth == 0 ) { // Item is on the top level, has no parent input.val(0); } else { // Find the parent item, and retrieve its object id. while( ! parent[0] || ! parent[0].className || -1 == parent[0].className.indexOf('menu-item') || ( parent.menuItemDepth() != depth - 1 ) ) parent = parent.prev(); input.val( parent.find('.menu-item-data-db-id').val() ); } }); }, hideAdvancedMenuItemFields : function() { return this.each(function(){ var that = $(this); $('.hide-column-tog').not(':checked').each(function(){ that.find('.field-' + $(this).val() ).addClass('hidden-field'); }); }); }, /** * Adds selected menu items to the menu. * * @param jQuery metabox The metabox jQuery object. */ addSelectedToMenu : function(processMethod) { if ( 0 == $('#menu-to-edit').length ) { return false; } return this.each(function() { var t = $(this), menuItems = {}, checkboxes = t.find('.tabs-panel-active .categorychecklist li input:checked'), re = new RegExp('menu-item\\[(\[^\\]\]*)'); processMethod = processMethod || api.addMenuItemToBottom; // If no items are checked, bail. if ( !checkboxes.length ) return false; // Show the ajax spinner t.find('img.waiting').show(); // Retrieve menu item data $(checkboxes).each(function(){ var t = $(this), listItemDBIDMatch = re.exec( t.attr('name') ), listItemDBID = 'undefined' == typeof listItemDBIDMatch[1] ? 0 : parseInt(listItemDBIDMatch[1], 10); if ( this.className && -1 != this.className.indexOf('add-to-top') ) processMethod = api.addMenuItemToTop; menuItems[listItemDBID] = t.closest('li').getItemData( 'add-menu-item', listItemDBID ); }); // Add the items api.addItemToMenu(menuItems, processMethod, function(){ // Deselect the items and hide the ajax spinner checkboxes.removeAttr('checked'); t.find('img.waiting').hide(); }); }); }, getItemData : function( itemType, id ) { itemType = itemType || 'menu-item'; var itemData = {}, i, fields = [ 'menu-item-db-id', 'menu-item-object-id', 'menu-item-object', 'menu-item-parent-id', 'menu-item-position', 'menu-item-type', 'menu-item-title', 'menu-item-url', 'menu-item-description', 'menu-item-attr-title', 'menu-item-target', 'menu-item-classes', 'menu-item-xfn' ]; if( !id && itemType == 'menu-item' ) { id = this.find('.menu-item-data-db-id').val(); } if( !id ) return itemData; this.find('input').each(function() { var field; i = fields.length; while ( i-- ) { if( itemType == 'menu-item' ) field = fields[i] + '[' + id + ']'; else if( itemType == 'add-menu-item' ) field = 'menu-item[' + id + '][' + fields[i] + ']'; if ( this.name && field == this.name ) { itemData[fields[i]] = this.value; } } }); return itemData; }, setItemData : function( itemData, itemType, id ) { // Can take a type, such as 'menu-item', or an id. itemType = itemType || 'menu-item'; if( !id && itemType == 'menu-item' ) { id = $('.menu-item-data-db-id', this).val(); } if( !id ) return this; this.find('input').each(function() { var t = $(this), field; $.each( itemData, function( attr, val ) { if( itemType == 'menu-item' ) field = attr + '[' + id + ']'; else if( itemType == 'add-menu-item' ) field = 'menu-item[' + id + '][' + attr + ']'; if ( field == t.attr('name') ) { t.val( val ); } }); }); return this; } }); }, initToggles : function() { // init postboxes postboxes.add_postbox_toggles('nav-menus'); // adjust columns functions for menus UI columns.useCheckboxesForHidden(); columns.checked = function(field) { $('.field-' + field).removeClass('hidden-field'); } columns.unchecked = function(field) { $('.field-' + field).addClass('hidden-field'); } // hide fields api.menuList.hideAdvancedMenuItemFields(); }, initSortables : function() { var currentDepth = 0, originalDepth, minDepth, maxDepth, prev, next, prevBottom, nextThreshold, helperHeight, transport, menuEdge = api.menuList.offset().left, body = $('body'), maxChildDepth, menuMaxDepth = initialMenuMaxDepth(); // Use the right edge if RTL. menuEdge += api.isRTL ? api.menuList.width() : 0; api.menuList.sortable({ handle: '.menu-item-handle', placeholder: 'sortable-placeholder', start: function(e, ui) { var height, width, parent, children, tempHolder; // handle placement for rtl orientation if ( api.isRTL ) ui.item[0].style.right = 'auto'; transport = ui.item.children('.menu-item-transport'); // Set depths. currentDepth must be set before children are located. originalDepth = ui.item.menuItemDepth(); updateCurrentDepth(ui, originalDepth); // Attach child elements to parent // Skip the placeholder parent = ( ui.item.next()[0] == ui.placeholder[0] ) ? ui.item.next() : ui.item; children = parent.childMenuItems(); transport.append( children ); // Update the height of the placeholder to match the moving item. height = transport.outerHeight(); // If there are children, account for distance between top of children and parent height += ( height > 0 ) ? (ui.placeholder.css('margin-top').slice(0, -2) * 1) : 0; height += ui.helper.outerHeight(); helperHeight = height; height -= 2; // Subtract 2 for borders ui.placeholder.height(height); // Update the width of the placeholder to match the moving item. maxChildDepth = originalDepth; children.each(function(){ var depth = $(this).menuItemDepth(); maxChildDepth = (depth > maxChildDepth) ? depth : maxChildDepth; }); width = ui.helper.find('.menu-item-handle').outerWidth(); // Get original width width += api.depthToPx(maxChildDepth - originalDepth); // Account for children width -= 2; // Subtract 2 for borders ui.placeholder.width(width); // Update the list of menu items. tempHolder = ui.placeholder.next(); tempHolder.css( 'margin-top', helperHeight + 'px' ); // Set the margin to absorb the placeholder ui.placeholder.detach(); // detach or jQuery UI will think the placeholder is a menu item $(this).sortable( "refresh" ); // The children aren't sortable. We should let jQ UI know. ui.item.after( ui.placeholder ); // reattach the placeholder. tempHolder.css('margin-top', 0); // reset the margin // Now that the element is complete, we can update... updateSharedVars(ui); }, stop: function(e, ui) { var children, depthChange = currentDepth - originalDepth; // Return child elements to the list children = transport.children().insertAfter(ui.item); // Update depth classes if( depthChange != 0 ) { ui.item.updateDepthClass( currentDepth ); children.shiftDepthClass( depthChange ); updateMenuMaxDepth( depthChange ); } // Register a change api.registerChange(); // Update the item data. ui.item.updateParentMenuItemDBId(); // address sortable's incorrectly-calculated top in opera ui.item[0].style.top = 0; // handle drop placement for rtl orientation if ( api.isRTL ) { ui.item[0].style.left = 'auto'; ui.item[0].style.right = 0; } // The width of the tab bar might have changed. Just in case. api.refreshMenuTabs( true ); }, change: function(e, ui) { // Make sure the placeholder is inside the menu. // Otherwise fix it, or we're in trouble. if( ! ui.placeholder.parent().hasClass('menu') ) (prev.length) ? prev.after( ui.placeholder ) : api.menuList.prepend( ui.placeholder ); updateSharedVars(ui); }, sort: function(e, ui) { var offset = ui.helper.offset(), edge = api.isRTL ? offset.left + ui.helper.width() : offset.left, depth = api.negateIfRTL * api.pxToDepth( edge - menuEdge ); // Check and correct if depth is not within range. // Also, if the dragged element is dragged upwards over // an item, shift the placeholder to a child position. if ( depth > maxDepth || offset.top < prevBottom ) depth = maxDepth; else if ( depth < minDepth ) depth = minDepth; if( depth != currentDepth ) updateCurrentDepth(ui, depth); // If we overlap the next element, manually shift downwards if( nextThreshold && offset.top + helperHeight > nextThreshold ) { next.after( ui.placeholder ); updateSharedVars( ui ); $(this).sortable( "refreshPositions" ); } } }); function updateSharedVars(ui) { var depth; prev = ui.placeholder.prev(); next = ui.placeholder.next(); // Make sure we don't select the moving item. if( prev[0] == ui.item[0] ) prev = prev.prev(); if( next[0] == ui.item[0] ) next = next.next(); prevBottom = (prev.length) ? prev.offset().top + prev.height() : 0; nextThreshold = (next.length) ? next.offset().top + next.height() / 3 : 0; minDepth = (next.length) ? next.menuItemDepth() : 0; if( prev.length ) maxDepth = ( (depth = prev.menuItemDepth() + 1) > api.options.globalMaxDepth ) ? api.options.globalMaxDepth : depth; else maxDepth = 0; } function updateCurrentDepth(ui, depth) { ui.placeholder.updateDepthClass( depth, currentDepth ); currentDepth = depth; } function initialMenuMaxDepth() { if( ! body[0].className ) return 0; var match = body[0].className.match(/menu-max-depth-(\d+)/); return match && match[1] ? parseInt(match[1]) : 0; } function updateMenuMaxDepth( depthChange ) { var depth, newDepth = menuMaxDepth; if ( depthChange === 0 ) { return; } else if ( depthChange > 0 ) { depth = maxChildDepth + depthChange; if( depth > menuMaxDepth ) newDepth = depth; } else if ( depthChange < 0 && maxChildDepth == menuMaxDepth ) { while( ! $('.menu-item-depth-' + newDepth, api.menuList).length && newDepth > 0 ) newDepth--; } // Update the depth class. body.removeClass( 'menu-max-depth-' + menuMaxDepth ).addClass( 'menu-max-depth-' + newDepth ); menuMaxDepth = newDepth; } }, attachMenuEditListeners : function() { var that = this; $('#update-nav-menu').bind('click', function(e) { if ( e.target && e.target.className ) { if ( -1 != e.target.className.indexOf('item-edit') ) { return that.eventOnClickEditLink(e.target); } else if ( -1 != e.target.className.indexOf('menu-save') ) { return that.eventOnClickMenuSave(e.target); } else if ( -1 != e.target.className.indexOf('menu-delete') ) { return that.eventOnClickMenuDelete(e.target); } else if ( -1 != e.target.className.indexOf('item-delete') ) { return that.eventOnClickMenuItemDelete(e.target); } else if ( -1 != e.target.className.indexOf('item-cancel') ) { return that.eventOnClickCancelLink(e.target); } } }); }, /** * An interface for managing default values for input elements * that is both JS and accessibility-friendly. * * Input elements that add the class 'input-with-default-title' * will have their values set to the provided HTML title when empty. */ setupInputWithDefaultTitle : function() { var name = 'input-with-default-title'; $('.' + name).each( function(){ var $t = $(this), title = $t.attr('title'), val = $t.val(); $t.data( name, title ); if( '' == val ) $t.val( title ); else if ( title == val ) return; else $t.removeClass( name ); }).focus( function(){ var $t = $(this); if( $t.val() == $t.data(name) ) $t.val('').removeClass( name ); }).blur( function(){ var $t = $(this); if( '' == $t.val() ) $t.addClass( name ).val( $t.data(name) ); }); }, attachThemeLocationsListeners : function() { var loc = $('#nav-menu-theme-locations'), params = {}; params['action'] = 'menu-locations-save'; params['menu-settings-column-nonce'] = $('#menu-settings-column-nonce').val(); loc.find('input[type="submit"]').click(function() { loc.find('select').each(function() { params[this.name] = $(this).val(); }); loc.find('.waiting').show(); $.post( ajaxurl, params, function(r) { loc.find('.waiting').hide(); }); return false; }); }, attachQuickSearchListeners : function() { var searchTimer; $('.quick-search').keypress(function(e){ var t = $(this); if( 13 == e.which ) { api.updateQuickSearchResults( t ); return false; } if( searchTimer ) clearTimeout(searchTimer); searchTimer = setTimeout(function(){ api.updateQuickSearchResults( t ); }, 400); }).attr('autocomplete','off'); }, updateQuickSearchResults : function(input) { var panel, params, minSearchLength = 2, q = input.val(); if( q.length < minSearchLength ) return; panel = input.parents('.tabs-panel'); params = { 'action': 'menu-quick-search', 'response-format': 'markup', 'menu': $('#menu').val(), 'menu-settings-column-nonce': $('#menu-settings-column-nonce').val(), 'q': q, 'type': input.attr('name') }; $('img.waiting', panel).show(); $.post( ajaxurl, params, function(menuMarkup) { api.processQuickSearchQueryResponse(menuMarkup, params, panel); }); }, addCustomLink : function( processMethod ) { var url = $('#custom-menu-item-url').val(), label = $('#custom-menu-item-name').val(); processMethod = processMethod || api.addMenuItemToBottom; if ( '' == url || 'http://' == url ) return false; // Show the ajax spinner $('.customlinkdiv img.waiting').show(); this.addLinkToMenu( url, label, processMethod, function() { // Remove the ajax spinner $('.customlinkdiv img.waiting').hide(); // Set custom link form back to defaults $('#custom-menu-item-name').val('').blur(); $('#custom-menu-item-url').val('http://'); }); }, addLinkToMenu : function(url, label, processMethod, callback) { processMethod = processMethod || api.addMenuItemToBottom; callback = callback || function(){}; api.addItemToMenu({ '-1': { 'menu-item-type': 'custom', 'menu-item-url': url, 'menu-item-title': label } }, processMethod, callback); }, addItemToMenu : function(menuItem, processMethod, callback) { var menu = $('#menu').val(), nonce = $('#menu-settings-column-nonce').val(); processMethod = processMethod || function(){}; callback = callback || function(){}; params = { 'action': 'add-menu-item', 'menu': menu, 'menu-settings-column-nonce': nonce, 'menu-item': menuItem }; $.post( ajaxurl, params, function(menuMarkup) { var ins = $('#menu-instructions'); processMethod(menuMarkup, params); if( ! ins.hasClass('menu-instructions-inactive') && ins.siblings().length ) ins.addClass('menu-instructions-inactive'); callback(); }); }, /** * Process the add menu item request response into menu list item. * * @param string menuMarkup The text server response of menu item markup. * @param object req The request arguments. */ addMenuItemToBottom : function( menuMarkup, req ) { $(menuMarkup).hideAdvancedMenuItemFields().appendTo( api.targetList ); }, addMenuItemToTop : function( menuMarkup, req ) { $(menuMarkup).hideAdvancedMenuItemFields().prependTo( api.targetList ); }, attachUnsavedChangesListener : function() { $('#menu-management input, #menu-management select, #menu-management, #menu-management textarea').change(function(){ api.registerChange(); }); if ( 0 != $('#menu-to-edit').length ) { window.onbeforeunload = function(){ if ( api.menusChanged ) return navMenuL10n.saveAlert; }; } else { // Make the post boxes read-only, as they can't be used yet $('#menu-settings-column').find('input,select').prop('disabled', true).end().find('a').attr('href', '#').unbind('click'); } }, registerChange : function() { api.menusChanged = true; }, attachTabsPanelListeners : function() { $('#menu-settings-column').bind('click', function(e) { var selectAreaMatch, panelId, wrapper, items, target = $(e.target); if ( target.hasClass('nav-tab-link') ) { panelId = /#(.*)$/.exec(e.target.href); if ( panelId && panelId[1] ) panelId = panelId[1] else return false; wrapper = target.parents('.inside').first(); // upon changing tabs, we want to uncheck all checkboxes $('input', wrapper).removeAttr('checked'); $('.tabs-panel-active', wrapper).removeClass('tabs-panel-active').addClass('tabs-panel-inactive'); $('#' + panelId, wrapper).removeClass('tabs-panel-inactive').addClass('tabs-panel-active'); $('.tabs', wrapper).removeClass('tabs'); target.parent().addClass('tabs'); // select the search bar $('.quick-search', wrapper).focus(); return false; } else if ( target.hasClass('select-all') ) { selectAreaMatch = /#(.*)$/.exec(e.target.href); if ( selectAreaMatch && selectAreaMatch[1] ) { items = $('#' + selectAreaMatch[1] + ' .tabs-panel-active .menu-item-title input'); if( items.length === items.filter(':checked').length ) items.removeAttr('checked'); else items.prop('checked', true); return false; } } else if ( target.hasClass('submit-add-to-menu') ) { api.registerChange(); if ( e.target.id && 'submit-customlinkdiv' == e.target.id ) api.addCustomLink( api.addMenuItemToBottom ); else if ( e.target.id && -1 != e.target.id.indexOf('submit-') ) $('#' + e.target.id.replace(/submit-/, '')).addSelectedToMenu( api.addMenuItemToBottom ); return false; } else if ( target.hasClass('page-numbers') ) { $.post( ajaxurl, e.target.href.replace(/.*\?/, '').replace(/action=([^&]*)/, '') + '&action=menu-get-metabox', function( resp ) { if ( -1 == resp.indexOf('replace-id') ) return; var metaBoxData = $.parseJSON(resp), toReplace = document.getElementById(metaBoxData['replace-id']), placeholder = document.createElement('div'), wrap = document.createElement('div'); if ( ! metaBoxData['markup'] || ! toReplace ) return; wrap.innerHTML = metaBoxData['markup'] ? metaBoxData['markup'] : ''; toReplace.parentNode.insertBefore( placeholder, toReplace ); placeholder.parentNode.removeChild( toReplace ); placeholder.parentNode.insertBefore( wrap, placeholder ); placeholder.parentNode.removeChild( placeholder ); } ); return false; } }); }, initTabManager : function() { var fixed = $('.nav-tabs-wrapper'), fluid = fixed.children('.nav-tabs'), active = fluid.children('.nav-tab-active'), tabs = fluid.children('.nav-tab'), tabsWidth = 0, fixedRight, fixedLeft, arrowLeft, arrowRight, resizeTimer, css = {}, marginFluid = api.isRTL ? 'margin-right' : 'margin-left', marginFixed = api.isRTL ? 'margin-left' : 'margin-right', msPerPx = 2; /** * Refreshes the menu tabs. * Will show and hide arrows where necessary. * Scrolls to the active tab by default. * * @param savePosition {boolean} Optional. Prevents scrolling so * that the current position is maintained. Default false. **/ api.refreshMenuTabs = function( savePosition ) { var fixedWidth = fixed.width(), margin = 0, css = {}; fixedLeft = fixed.offset().left; fixedRight = fixedLeft + fixedWidth; if( !savePosition ) active.makeTabVisible(); // Prevent space from building up next to the last tab if there's more to show if( tabs.last().isTabVisible() ) { margin = fixed.width() - tabsWidth; margin = margin > 0 ? 0 : margin; css[marginFluid] = margin + 'px'; fluid.animate( css, 100, "linear" ); } // Show the arrows only when necessary if( fixedWidth > tabsWidth ) arrowLeft.add( arrowRight ).hide(); else arrowLeft.add( arrowRight ).show(); } $.fn.extend({ makeTabVisible : function() { var t = this.eq(0), left, right, css = {}, shift = 0; if( ! t.length ) return this; left = t.offset().left; right = left + t.outerWidth(); if( right > fixedRight ) shift = fixedRight - right; else if ( left < fixedLeft ) shift = fixedLeft - left; if( ! shift ) return this; css[marginFluid] = "+=" + api.negateIfRTL * shift + 'px'; fluid.animate( css, Math.abs( shift ) * msPerPx, "linear" ); return this; }, isTabVisible : function() { var t = this.eq(0), left = t.offset().left, right = left + t.outerWidth(); return ( right <= fixedRight && left >= fixedLeft ) ? true : false; } }); // Find the width of all tabs tabs.each(function(){ tabsWidth += $(this).outerWidth(true); }); // Set up fixed margin for overflow, unset padding css['padding'] = 0; css[marginFixed] = (-1 * tabsWidth) + 'px'; fluid.css( css ); // Build tab navigation arrowLeft = $('<div class="nav-tabs-arrow nav-tabs-arrow-left"><a>&laquo;</a></div>'); arrowRight = $('<div class="nav-tabs-arrow nav-tabs-arrow-right"><a>&raquo;</a></div>'); // Attach to the document fixed.wrap('<div class="nav-tabs-nav"/>').parent().prepend( arrowLeft ).append( arrowRight ); // Set the menu tabs api.refreshMenuTabs(); // Make sure the tabs reset on resize $(window).resize(function() { if( resizeTimer ) clearTimeout(resizeTimer); resizeTimer = setTimeout( api.refreshMenuTabs, 200); }); // Build arrow functions $.each([{ arrow : arrowLeft, next : "next", last : "first", operator : "+=" },{ arrow : arrowRight, next : "prev", last : "last", operator : "-=" }], function(){ var that = this; this.arrow.mousedown(function(){ var marginFluidVal = Math.abs( parseInt( fluid.css(marginFluid) ) ), shift = marginFluidVal, css = {}; if( "-=" == that.operator ) shift = Math.abs( tabsWidth - fixed.width() ) - marginFluidVal; if( ! shift ) return; css[marginFluid] = that.operator + shift + 'px'; fluid.animate( css, shift * msPerPx, "linear" ); }).mouseup(function(){ var tab, next; fluid.stop(true); tab = tabs[that.last](); while( (next = tab[that.next]()) && next.length && ! next.isTabVisible() ) { tab = next; } tab.makeTabVisible(); }); }); }, eventOnClickEditLink : function(clickedEl) { var settings, item, matchedSection = /#(.*)$/.exec(clickedEl.href); if ( matchedSection && matchedSection[1] ) { settings = $('#'+matchedSection[1]); item = settings.parent(); if( 0 != item.length ) { if( item.hasClass('menu-item-edit-inactive') ) { if( ! settings.data('menu-item-data') ) { settings.data( 'menu-item-data', settings.getItemData() ); } settings.slideDown('fast'); item.removeClass('menu-item-edit-inactive') .addClass('menu-item-edit-active'); } else { settings.slideUp('fast'); item.removeClass('menu-item-edit-active') .addClass('menu-item-edit-inactive'); } return false; } } }, eventOnClickCancelLink : function(clickedEl) { var settings = $(clickedEl).closest('.menu-item-settings'); settings.setItemData( settings.data('menu-item-data') ); return false; }, eventOnClickMenuSave : function(clickedEl) { var locs = '', menuName = $('#menu-name'), menuNameVal = menuName.val(); // Cancel and warn if invalid menu name if( !menuNameVal || menuNameVal == menuName.attr('title') || !menuNameVal.replace(/\s+/, '') ) { menuName.parent().addClass('form-invalid'); return false; } // Copy menu theme locations $('#nav-menu-theme-locations select').each(function() { locs += '<input type="hidden" name="' + this.name + '" value="' + $(this).val() + '" />'; }); $('#update-nav-menu').append( locs ); // Update menu item position data api.menuList.find('.menu-item-data-position').val( function(index) { return index + 1; } ); window.onbeforeunload = null; return true; }, eventOnClickMenuDelete : function(clickedEl) { // Delete warning AYS if ( confirm( navMenuL10n.warnDeleteMenu ) ) { window.onbeforeunload = null; return true; } return false; }, eventOnClickMenuItemDelete : function(clickedEl) { var itemID = parseInt(clickedEl.id.replace('delete-', ''), 10); api.removeMenuItem( $('#menu-item-' + itemID) ); api.registerChange(); return false; }, /** * Process the quick search response into a search result * * @param string resp The server response to the query. * @param object req The request arguments. * @param jQuery panel The tabs panel we're searching in. */ processQuickSearchQueryResponse : function(resp, req, panel) { var matched, newID, takenIDs = {}, form = document.getElementById('nav-menu-meta'), pattern = new RegExp('menu-item\\[(\[^\\]\]*)', 'g'), $items = $('<div>').html(resp).find('li'), $item; if( ! $items.length ) { $('.categorychecklist', panel).html( '<li><p>' + navMenuL10n.noResultsFound + '</p></li>' ); $('img.waiting', panel).hide(); return; } $items.each(function(){ $item = $(this); // make a unique DB ID number matched = pattern.exec($item.html()); if ( matched && matched[1] ) { newID = matched[1]; while( form.elements['menu-item[' + newID + '][menu-item-type]'] || takenIDs[ newID ] ) { newID--; } takenIDs[newID] = true; if ( newID != matched[1] ) { $item.html( $item.html().replace(new RegExp( 'menu-item\\[' + matched[1] + '\\]', 'g'), 'menu-item[' + newID + ']' ) ); } } }); $('.categorychecklist', panel).html( $items ); $('img.waiting', panel).hide(); }, removeMenuItem : function(el) { var children = el.childMenuItems(); el.addClass('deleting').animate({ opacity : 0, height: 0 }, 350, function() { var ins = $('#menu-instructions'); el.remove(); children.shiftDepthClass(-1).updateParentMenuItemDBId(); if( ! ins.siblings().length ) ins.removeClass('menu-instructions-inactive'); }); }, depthToPx : function(depth) { return depth * api.options.menuItemDepthPerLevel; }, pxToDepth : function(px) { return Math.floor(px / api.options.menuItemDepthPerLevel); } }; $(document).ready(function(){ wpNavMenu.init(); }); })(jQuery);
JavaScript
var ajaxWidgets, ajaxPopulateWidgets, quickPressLoad; jQuery(document).ready( function($) { // 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.replace( '/admin-ajax.php', '' ) + '/index-extra.php?jax=' + id, '', function() { p.hide().slideDown('normal', function(){ $(this).css('display', ''); }); }); }, i * 500 ); } } if ( el ) { el = el.toString(); if ( $.inArray(el, ajaxWidgets) != -1 ) show(0, el); } else { $.each( ajaxWidgets, show ); } }; ajaxPopulateWidgets(); postboxes.add_postbox_toggles(pagenow, { pbshow: ajaxPopulateWidgets } ); /* QuickPress */ quickPressLoad = function() { var act = $('#quickpost-action'), t; t = $('#quick-press').submit( function() { $('#dashboard_quick_press #publishing-action img.waiting').css('visibility', 'visible'); $('#quick-press .submit input[type="submit"], #quick-press .submit input[type="reset"]').prop('disabled', true); if ( 'post' == act.val() ) { act.val( 'post-quickpress-publish' ); } $('#dashboard_quick_press div.inside').load( t.attr( 'action' ), t.serializeArray(), function() { $('#dashboard_quick_press #publishing-action img.waiting').css('visibility', 'hidden'); $('#quick-press .submit input[type="submit"], #quick-press .submit input[type="reset"]').prop('disabled', false); $('#dashboard_quick_press ul').next('p').remove(); $('#dashboard_quick_press ul').find('li').each( function() { $('#dashboard_recent_drafts ul').prepend( this ); } ).end().remove(); quickPressLoad(); } ); return false; } ); $('#publish').click( function() { act.val( 'post-quickpress-publish' ); } ); }; quickPressLoad(); } );
JavaScript