code
stringlengths
1
2.08M
language
stringclasses
1 value
(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
/** * 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
/** * 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; // Register commands ed.addCommand('wpFullScreenClose', function() { // this removes the editor, content has to be saved first with tinyMCE.execCommand('wpFullScreenSave'); if ( ed.getParam('wp_fullscreen_is_enabled') ) { DOM.win.setTimeout(function() { tinyMCE.remove(ed); DOM.remove('wp_mce_fullscreen_parent'); tinyMCE.settings = tinyMCE.oldSettings; // Restore old settings }, 10); } }); ed.addCommand('wpFullScreenSave', function() { var ed = tinyMCE.get('wp_mce_fullscreen'), edd; ed.focus(); edd = tinyMCE.get( ed.getParam('wp_fullscreen_editor_id') ); edd.setContent( ed.getContent({format : 'raw'}), {format : 'raw'} ); }); ed.addCommand('wpFullScreenInit', function() { var d, b, fsed; ed = tinyMCE.activeEditor; d = ed.getDoc(); b = d.body; tinyMCE.oldSettings = tinyMCE.settings; // Store old settings tinymce.each(ed.settings, function(v, n) { s[n] = v; }); s.id = 'wp_mce_fullscreen'; s.wp_fullscreen_is_enabled = true; s.wp_fullscreen_editor_id = ed.id; s.theme_advanced_resizing = false; s.theme_advanced_statusbar_location = 'none'; s.content_css = s.content_css ? s.content_css + ',' + s.wp_fullscreen_content_css : s.wp_fullscreen_content_css; s.height = tinymce.isIE ? b.scrollHeight : b.offsetHeight; tinymce.each(ed.getParam('wp_fullscreen_settings'), function(v, k) { s[k] = v; }); fsed = new tinymce.Editor('wp_mce_fullscreen', s); fsed.onInit.add(function(edd) { var DOM = tinymce.DOM, buttons = DOM.select('a.mceButton', DOM.get('wp-fullscreen-buttons')); if ( !ed.isHidden() ) edd.setContent( ed.getContent() ); else edd.setContent( switchEditors.wpautop( edd.getElement().value ) ); setTimeout(function(){ // add last edd.onNodeChange.add(function(ed, cm, e){ tinymce.each(buttons, function(c) { var btn, cls; if ( btn = DOM.get( 'wp_mce_fullscreen_' + c.id.substr(6) ) ) { cls = btn.className; if ( cls ) c.className = cls; } }); }); }, 1000); edd.dom.addClass(edd.getBody(), 'wp-fullscreen-editor'); edd.focus(); }); fsed.render(); if ( 'undefined' != fullscreen ) { fsed.dom.bind( fsed.dom.doc, 'mousemove', function(e){ fullscreen.bounder( 'showToolbar', 'hideToolbar', 2000, e ); }); } }); // Register buttons if ( 'undefined' != fullscreen ) { ed.addButton('wp_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() { var d = ed.getDoc(), DOM = tinymce.DOM, resizeHeight, myHeight; // Get height differently depending on the browser used if ( tinymce.isWebKit ) myHeight = d.body.offsetHeight; else myHeight = d.body.scrollHeight; // Don't make it smaller than 300px resizeHeight = (myHeight > 300) ? myHeight : 300; // Resize content element if ( oldHeight != resizeHeight ) { DOM.setStyle(DOM.get(ed.id + '_ifr'), 'height', resizeHeight + 'px'); oldHeight = resizeHeight; ed.getWin().scrollTo(0,0); } }; // Add appropriate listeners for resizing content area ed.onInit.add(function(ed, l) { ed.onChange.add(resize); ed.onSetContent.add(resize); ed.onPaste.add(resize); ed.onKeyUp.add(resize); ed.onPostRender.add(resize); ed.getBody().style.overflowY = "hidden"; }); if (ed.getParam('autoresize_on_init', true)) { ed.onLoadContent.add(function(ed, l) { // Because the content area resizes when its content CSS loads, // and we can't easily add a listener to its onload event, // we'll just trigger a resize after a short loading period setTimeout(function() { resize(); }, 1200); }); } // Register the command so that it can be invoked by using tinyMCE.activeEditor.execCommand('mceExample'); ed.addCommand('wpAutoResize', resize); }, getInfo : function() { return { longname : 'WP Fullscreen', author : 'WordPress', authorurl : 'http://wordpress.org', infourl : '', version : '1.0' }; } }); // Register plugin tinymce.PluginManager.add('wpfullscreen', tinymce.plugins.wpFullscreenPlugin); })();
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { var DOM = tinymce.DOM, Element = tinymce.dom.Element, Event = tinymce.dom.Event, each = tinymce.each, is = tinymce.is; tinymce.create('tinymce.plugins.InlinePopups', { init : function(ed, url) { // Replace window manager ed.onBeforeRenderUI.add(function() { ed.windowManager = new tinymce.InlineWindowManager(ed); DOM.loadCSS(url + '/skins/' + (ed.settings.inlinepopups_skin || 'clearlooks2') + "/window.css"); }); }, getInfo : function() { return { longname : 'InlinePopups', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/inlinepopups', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); tinymce.create('tinymce.InlineWindowManager:tinymce.WindowManager', { InlineWindowManager : function(ed) { var t = this; t.parent(ed); t.zIndex = 300000; t.count = 0; t.windows = {}; }, open : function(f, p) { var t = this, id, opt = '', ed = t.editor, dw = 0, dh = 0, vp, po, mdf, clf, we, w, u, parentWindow; f = f || {}; p = p || {}; // Run native windows if (!f.inline) return t.parent(f, p); parentWindow = t._frontWindow(); if (parentWindow && DOM.get(parentWindow.id + '_ifr')) { parentWindow.focussedElement = DOM.get(parentWindow.id + '_ifr').contentWindow.document.activeElement; } // Only store selection if the type is a normal window if (!f.type) t.bookmark = ed.selection.getBookmark(1); id = DOM.uniqueId(); vp = DOM.getViewPort(); f.width = parseInt(f.width || 320); f.height = parseInt(f.height || 240) + (tinymce.isIE ? 8 : 0); f.min_width = parseInt(f.min_width || 150); f.min_height = parseInt(f.min_height || 100); f.max_width = parseInt(f.max_width || 2000); f.max_height = parseInt(f.max_height || 2000); f.left = f.left || Math.round(Math.max(vp.x, vp.x + (vp.w / 2.0) - (f.width / 2.0))); f.top = f.top || Math.round(Math.max(vp.y, vp.y + (vp.h / 2.0) - (f.height / 2.0))); f.movable = f.resizable = true; p.mce_width = f.width; p.mce_height = f.height; p.mce_inline = true; p.mce_window_id = id; p.mce_auto_focus = f.auto_focus; // Transpose // po = DOM.getPos(ed.getContainer()); // f.left -= po.x; // f.top -= po.y; t.features = f; t.params = p; t.onOpen.dispatch(t, f, p); if (f.type) { opt += ' mceModal'; if (f.type) opt += ' mce' + f.type.substring(0, 1).toUpperCase() + f.type.substring(1); f.resizable = false; } if (f.statusbar) opt += ' mceStatusbar'; if (f.resizable) opt += ' mceResizable'; if (f.minimizable) opt += ' mceMinimizable'; if (f.maximizable) opt += ' mceMaximizable'; if (f.movable) opt += ' mceMovable'; // Create DOM objects t._addAll(DOM.doc.body, ['div', {id : id, role : 'dialog', 'aria-labelledby': f.type ? id + '_content' : id + '_title', 'class' : (ed.settings.inlinepopups_skin || 'clearlooks2') + (tinymce.isIE && window.getSelection ? ' ie9' : ''), style : 'width:100px;height:100px'}, ['div', {id : id + '_wrapper', 'class' : 'mceWrapper' + opt}, ['div', {id : id + '_top', 'class' : 'mceTop'}, ['div', {'class' : 'mceLeft'}], ['div', {'class' : 'mceCenter'}], ['div', {'class' : 'mceRight'}], ['span', {id : id + '_title'}, f.title || ''] ], ['div', {id : id + '_middle', 'class' : 'mceMiddle'}, ['div', {id : id + '_left', 'class' : 'mceLeft', tabindex : '0'}], ['span', {id : id + '_content'}], ['div', {id : id + '_right', 'class' : 'mceRight', tabindex : '0'}] ], ['div', {id : id + '_bottom', 'class' : 'mceBottom'}, ['div', {'class' : 'mceLeft'}], ['div', {'class' : 'mceCenter'}], ['div', {'class' : 'mceRight'}], ['span', {id : id + '_status'}, 'Content'] ], ['a', {'class' : 'mceMove', tabindex : '-1', href : 'javascript:;'}], ['a', {'class' : 'mceMin', tabindex : '-1', href : 'javascript:;', onmousedown : 'return false;'}], ['a', {'class' : 'mceMax', tabindex : '-1', href : 'javascript:;', onmousedown : 'return false;'}], ['a', {'class' : 'mceMed', tabindex : '-1', href : 'javascript:;', onmousedown : 'return false;'}], ['a', {'class' : 'mceClose', tabindex : '-1', href : 'javascript:;', onmousedown : 'return false;'}], ['a', {id : id + '_resize_n', 'class' : 'mceResize mceResizeN', tabindex : '-1', href : 'javascript:;'}], ['a', {id : id + '_resize_s', 'class' : 'mceResize mceResizeS', tabindex : '-1', href : 'javascript:;'}], ['a', {id : id + '_resize_w', 'class' : 'mceResize mceResizeW', tabindex : '-1', href : 'javascript:;'}], ['a', {id : id + '_resize_e', 'class' : 'mceResize mceResizeE', tabindex : '-1', href : 'javascript:;'}], ['a', {id : id + '_resize_nw', 'class' : 'mceResize mceResizeNW', tabindex : '-1', href : 'javascript:;'}], ['a', {id : id + '_resize_ne', 'class' : 'mceResize mceResizeNE', tabindex : '-1', href : 'javascript:;'}], ['a', {id : id + '_resize_sw', 'class' : 'mceResize mceResizeSW', tabindex : '-1', href : 'javascript:;'}], ['a', {id : id + '_resize_se', 'class' : 'mceResize mceResizeSE', tabindex : '-1', href : 'javascript:;'}] ] ] ); DOM.setStyles(id, {top : -10000, left : -10000}); // Fix gecko rendering bug, where the editors iframe messed with window contents if (tinymce.isGecko) DOM.setStyle(id, 'overflow', 'auto'); // Measure borders if (!f.type) { dw += DOM.get(id + '_left').clientWidth; dw += DOM.get(id + '_right').clientWidth; dh += DOM.get(id + '_top').clientHeight; dh += DOM.get(id + '_bottom').clientHeight; } // Resize window DOM.setStyles(id, {top : f.top, left : f.left, width : f.width + dw, height : f.height + dh}); u = f.url || f.file; if (u) { if (tinymce.relaxedDomain) u += (u.indexOf('?') == -1 ? '?' : '&') + 'mce_rdomain=' + tinymce.relaxedDomain; u = tinymce._addVer(u); } if (!f.type) { DOM.add(id + '_content', 'iframe', {id : id + '_ifr', src : 'javascript:""', frameBorder : 0, style : 'border:0;width:10px;height:10px'}); DOM.setStyles(id + '_ifr', {width : f.width, height : f.height}); DOM.setAttrib(id + '_ifr', 'src', u); } else { DOM.add(id + '_wrapper', 'a', {id : id + '_ok', 'class' : 'mceButton mceOk', href : 'javascript:;', onmousedown : 'return false;'}, 'Ok'); if (f.type == 'confirm') DOM.add(id + '_wrapper', 'a', {'class' : 'mceButton mceCancel', href : 'javascript:;', onmousedown : 'return false;'}, 'Cancel'); DOM.add(id + '_middle', 'div', {'class' : 'mceIcon'}); DOM.setHTML(id + '_content', f.content.replace('\n', '<br />')); Event.add(id, 'keyup', function(evt) { var VK_ESCAPE = 27; if (evt.keyCode === VK_ESCAPE) { f.button_func(false); return Event.cancel(evt); } }); Event.add(id, 'keydown', function(evt) { var cancelButton, VK_TAB = 9; if (evt.keyCode === VK_TAB) { cancelButton = DOM.select('a.mceCancel', id + '_wrapper')[0]; if (cancelButton && cancelButton !== evt.target) { cancelButton.focus(); } else { DOM.get(id + '_ok').focus(); } return Event.cancel(evt); } }); } // Register events mdf = Event.add(id, 'mousedown', function(e) { var n = e.target, w, vp; w = t.windows[id]; t.focus(id); if (n.nodeName == 'A' || n.nodeName == 'a') { if (n.className == 'mceClose') { t.close(null, id); return Event.cancel(e); } else if (n.className == 'mceMax') { w.oldPos = w.element.getXY(); w.oldSize = w.element.getSize(); vp = DOM.getViewPort(); // Reduce viewport size to avoid scrollbars vp.w -= 2; vp.h -= 2; w.element.moveTo(vp.x, vp.y); w.element.resizeTo(vp.w, vp.h); DOM.setStyles(id + '_ifr', {width : vp.w - w.deltaWidth, height : vp.h - w.deltaHeight}); DOM.addClass(id + '_wrapper', 'mceMaximized'); } else if (n.className == 'mceMed') { // Reset to old size w.element.moveTo(w.oldPos.x, w.oldPos.y); w.element.resizeTo(w.oldSize.w, w.oldSize.h); w.iframeElement.resizeTo(w.oldSize.w - w.deltaWidth, w.oldSize.h - w.deltaHeight); DOM.removeClass(id + '_wrapper', 'mceMaximized'); } else if (n.className == 'mceMove') return t._startDrag(id, e, n.className); else if (DOM.hasClass(n, 'mceResize')) return t._startDrag(id, e, n.className.substring(13)); } }); clf = Event.add(id, 'click', function(e) { var n = e.target; t.focus(id); if (n.nodeName == 'A' || n.nodeName == 'a') { switch (n.className) { case 'mceClose': t.close(null, id); return Event.cancel(e); case 'mceButton mceOk': case 'mceButton mceCancel': f.button_func(n.className == 'mceButton mceOk'); return Event.cancel(e); } } }); // Make sure the tab order loops within the dialog. Event.add([id + '_left', id + '_right'], 'focus', function(evt) { var iframe = DOM.get(id + '_ifr'); if (iframe) { var body = iframe.contentWindow.document.body; var focusable = DOM.select(':input:enabled,*[tabindex=0]', body); if (evt.target.id === (id + '_left')) { focusable[focusable.length - 1].focus(); } else { focusable[0].focus(); } } else { DOM.get(id + '_ok').focus(); } }); // Add window w = t.windows[id] = { id : id, mousedown_func : mdf, click_func : clf, element : new Element(id, {blocker : 1, container : ed.getContainer()}), iframeElement : new Element(id + '_ifr'), features : f, deltaWidth : dw, deltaHeight : dh }; w.iframeElement.on('focus', function() { t.focus(id); }); // Setup blocker if (t.count == 0 && t.editor.getParam('dialog_type', 'modal') == 'modal') { DOM.add(DOM.doc.body, 'div', { id : 'mceModalBlocker', 'class' : (t.editor.settings.inlinepopups_skin || 'clearlooks2') + '_modalBlocker', style : {zIndex : t.zIndex - 1} }); DOM.show('mceModalBlocker'); // Reduces flicker in IE DOM.setAttrib(DOM.doc.body, 'aria-hidden', 'true'); } else DOM.setStyle('mceModalBlocker', 'z-index', t.zIndex - 1); if (tinymce.isIE6 || /Firefox\/2\./.test(navigator.userAgent) || (tinymce.isIE && !DOM.boxModel)) DOM.setStyles('mceModalBlocker', {position : 'absolute', left : vp.x, top : vp.y, width : vp.w - 2, height : vp.h - 2}); DOM.setAttrib(id, 'aria-hidden', 'false'); t.focus(id); t._fixIELayout(id, 1); // Focus ok button if (DOM.get(id + '_ok')) DOM.get(id + '_ok').focus(); t.count++; return w; }, focus : function(id) { var t = this, w; if (w = t.windows[id]) { w.zIndex = this.zIndex++; w.element.setStyle('zIndex', w.zIndex); w.element.update(); id = id + '_wrapper'; DOM.removeClass(t.lastId, 'mceFocus'); DOM.addClass(id, 'mceFocus'); t.lastId = id; if (w.focussedElement) { w.focussedElement.focus(); } else if (DOM.get(id + '_ok')) { DOM.get(w.id + '_ok').focus(); } else if (DOM.get(w.id + '_ifr')) { DOM.get(w.id + '_ifr').focus(); } } }, _addAll : function(te, ne) { var i, n, t = this, dom = tinymce.DOM; if (is(ne, 'string')) te.appendChild(dom.doc.createTextNode(ne)); else if (ne.length) { te = te.appendChild(dom.create(ne[0], ne[1])); for (i=2; i<ne.length; i++) t._addAll(te, ne[i]); } }, _startDrag : function(id, se, ac) { var t = this, mu, mm, d = DOM.doc, eb, w = t.windows[id], we = w.element, sp = we.getXY(), p, sz, ph, cp, vp, sx, sy, sex, sey, dx, dy, dw, dh; // Get positons and sizes // cp = DOM.getPos(t.editor.getContainer()); cp = {x : 0, y : 0}; vp = DOM.getViewPort(); // Reduce viewport size to avoid scrollbars while dragging vp.w -= 2; vp.h -= 2; sex = se.screenX; sey = se.screenY; dx = dy = dw = dh = 0; // Handle mouse up mu = Event.add(d, 'mouseup', function(e) { Event.remove(d, 'mouseup', mu); Event.remove(d, 'mousemove', mm); if (eb) eb.remove(); we.moveBy(dx, dy); we.resizeBy(dw, dh); sz = we.getSize(); DOM.setStyles(id + '_ifr', {width : sz.w - w.deltaWidth, height : sz.h - w.deltaHeight}); t._fixIELayout(id, 1); return Event.cancel(e); }); if (ac != 'Move') startMove(); function startMove() { if (eb) return; t._fixIELayout(id, 0); // Setup event blocker DOM.add(d.body, 'div', { id : 'mceEventBlocker', 'class' : 'mceEventBlocker ' + (t.editor.settings.inlinepopups_skin || 'clearlooks2'), style : {zIndex : t.zIndex + 1} }); if (tinymce.isIE6 || (tinymce.isIE && !DOM.boxModel)) DOM.setStyles('mceEventBlocker', {position : 'absolute', left : vp.x, top : vp.y, width : vp.w - 2, height : vp.h - 2}); eb = new Element('mceEventBlocker'); eb.update(); // Setup placeholder p = we.getXY(); sz = we.getSize(); sx = cp.x + p.x - vp.x; sy = cp.y + p.y - vp.y; DOM.add(eb.get(), 'div', {id : 'mcePlaceHolder', 'class' : 'mcePlaceHolder', style : {left : sx, top : sy, width : sz.w, height : sz.h}}); ph = new Element('mcePlaceHolder'); }; // Handle mouse move/drag mm = Event.add(d, 'mousemove', function(e) { var x, y, v; startMove(); x = e.screenX - sex; y = e.screenY - sey; switch (ac) { case 'ResizeW': dx = x; dw = 0 - x; break; case 'ResizeE': dw = x; break; case 'ResizeN': case 'ResizeNW': case 'ResizeNE': if (ac == "ResizeNW") { dx = x; dw = 0 - x; } else if (ac == "ResizeNE") dw = x; dy = y; dh = 0 - y; break; case 'ResizeS': case 'ResizeSW': case 'ResizeSE': if (ac == "ResizeSW") { dx = x; dw = 0 - x; } else if (ac == "ResizeSE") dw = x; dh = y; break; case 'mceMove': dx = x; dy = y; break; } // Boundary check if (dw < (v = w.features.min_width - sz.w)) { if (dx !== 0) dx += dw - v; dw = v; } if (dh < (v = w.features.min_height - sz.h)) { if (dy !== 0) dy += dh - v; dh = v; } dw = Math.min(dw, w.features.max_width - sz.w); dh = Math.min(dh, w.features.max_height - sz.h); dx = Math.max(dx, vp.x - (sx + vp.x)); dy = Math.max(dy, vp.y - (sy + vp.y)); dx = Math.min(dx, (vp.w + vp.x) - (sx + sz.w + vp.x)); dy = Math.min(dy, (vp.h + vp.y) - (sy + sz.h + vp.y)); // Move if needed if (dx + dy !== 0) { if (sx + dx < 0) dx = 0; if (sy + dy < 0) dy = 0; ph.moveTo(sx + dx, sy + dy); } // Resize if needed if (dw + dh !== 0) ph.resizeTo(sz.w + dw, sz.h + dh); return Event.cancel(e); }); return Event.cancel(se); }, resizeBy : function(dw, dh, id) { var w = this.windows[id]; if (w) { w.element.resizeBy(dw, dh); w.iframeElement.resizeBy(dw, dh); } }, close : function(win, id) { var t = this, w, d = DOM.doc, fw, id; id = t._findId(id || win); // Probably not inline if (!t.windows[id]) { t.parent(win); return; } t.count--; if (t.count == 0) { DOM.remove('mceModalBlocker'); DOM.setAttrib(DOM.doc.body, 'aria-hidden', 'false'); t.editor.focus(); } if (w = t.windows[id]) { t.onClose.dispatch(t); Event.remove(d, 'mousedown', w.mousedownFunc); Event.remove(d, 'click', w.clickFunc); Event.clear(id); Event.clear(id + '_ifr'); DOM.setAttrib(id + '_ifr', 'src', 'javascript:""'); // Prevent leak w.element.remove(); delete t.windows[id]; fw = t._frontWindow(); if (fw) t.focus(fw.id); } }, // Find front most window _frontWindow : function() { var fw, ix = 0; // Find front most window and focus that each (this.windows, function(w) { if (w.zIndex > ix) { fw = w; ix = w.zIndex; } }); return fw; }, setTitle : function(w, ti) { var e; w = this._findId(w); if (e = DOM.get(w + '_title')) e.innerHTML = DOM.encode(ti); }, alert : function(txt, cb, s) { var t = this, w; w = t.open({ title : t, type : 'alert', button_func : function(s) { if (cb) cb.call(s || t, s); t.close(null, w.id); }, content : DOM.encode(t.editor.getLang(txt, txt)), inline : 1, width : 400, height : 130 }); }, confirm : function(txt, cb, s) { var t = this, w; w = t.open({ title : t, type : 'confirm', button_func : function(s) { if (cb) cb.call(s || t, s); t.close(null, w.id); }, content : DOM.encode(t.editor.getLang(txt, txt)), inline : 1, width : 400, height : 130 }); }, // Internal functions _findId : function(w) { var t = this; if (typeof(w) == 'string') return w; each(t.windows, function(wo) { var ifr = DOM.get(wo.id + '_ifr'); if (ifr && w == ifr.contentWindow) { w = wo.id; return false; } }); return w; }, _fixIELayout : function(id, s) { var w, img; if (!tinymce.isIE6) return; // Fixes the bug where hover flickers and does odd things in IE6 each(['n','s','w','e','nw','ne','sw','se'], function(v) { var e = DOM.get(id + '_resize_' + v); DOM.setStyles(e, { width : s ? e.clientWidth : '', height : s ? e.clientHeight : '', cursor : DOM.getStyle(e, 'cursor', 1) }); DOM.setStyle(id + "_bottom", 'bottom', '-1px'); e = 0; }); // Fixes graphics glitch if (w = this.windows[id]) { // Fixes rendering bug after resize w.element.hide(); w.element.show(); // Forced a repaint of the window //DOM.get(id).style.filter = ''; // IE has a bug where images used in CSS won't get loaded // sometimes when the cache in the browser is disabled // This fix tries to solve it by loading the images using the image object each(DOM.select('div,a', id), function(e, i) { if (e.currentStyle.backgroundImage != 'none') { img = new Image(); img.src = e.currentStyle.backgroundImage.replace(/url\(\"(.+)\"\)/, '$1'); } }); DOM.get(id).style.filter = ''; } } }); // Register plugin tinymce.PluginManager.add('inlinepopups', tinymce.plugins.InlinePopups); })();
JavaScript
(function() { var url; if (url = tinyMCEPopup.getParam("media_external_list_url")) document.write('<script language="javascript" type="text/javascript" src="' + tinyMCEPopup.editor.documentBaseURI.toAbsolute(url) + '"></script>'); function get(id) { return document.getElementById(id); } function clone(obj) { var i, len, copy, attr; if (null == obj || "object" != typeof obj) return obj; // Handle Array if ('length' in obj) { copy = []; for (i = 0, len = obj.length; i < len; ++i) { copy[i] = clone(obj[i]); } return copy; } // Handle Object copy = {}; for (attr in obj) { if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]); } return copy; } function getVal(id) { var elm = get(id); if (elm.nodeName == "SELECT") return elm.options[elm.selectedIndex].value; if (elm.type == "checkbox") return elm.checked; return elm.value; } function setVal(id, value, name) { if (typeof(value) != 'undefined' && value != null) { var elm = get(id); if (elm.nodeName == "SELECT") selectByValue(document.forms[0], id, value); else if (elm.type == "checkbox") { if (typeof(value) == 'string') { value = value.toLowerCase(); value = (!name && value === 'true') || (name && value === name.toLowerCase()); } elm.checked = !!value; } else elm.value = value; } } window.Media = { init : function() { var html, editor, self = this; self.editor = editor = tinyMCEPopup.editor; // Setup file browsers and color pickers get('filebrowsercontainer').innerHTML = getBrowserHTML('filebrowser','src','media','media'); get('qtsrcfilebrowsercontainer').innerHTML = getBrowserHTML('qtsrcfilebrowser','quicktime_qtsrc','media','media'); get('bgcolor_pickcontainer').innerHTML = getColorPickerHTML('bgcolor_pick','bgcolor'); get('video_altsource1_filebrowser').innerHTML = getBrowserHTML('video_filebrowser_altsource1','video_altsource1','media','media'); get('video_altsource2_filebrowser').innerHTML = getBrowserHTML('video_filebrowser_altsource2','video_altsource2','media','media'); get('audio_altsource1_filebrowser').innerHTML = getBrowserHTML('audio_filebrowser_altsource1','audio_altsource1','media','media'); get('audio_altsource2_filebrowser').innerHTML = getBrowserHTML('audio_filebrowser_altsource2','audio_altsource2','media','media'); get('video_poster_filebrowser').innerHTML = getBrowserHTML('filebrowser_poster','video_poster','media','image'); html = self.getMediaListHTML('medialist', 'src', 'media', 'media'); if (html == "") get("linklistrow").style.display = 'none'; else get("linklistcontainer").innerHTML = html; if (isVisible('filebrowser')) get('src').style.width = '230px'; if (isVisible('video_filebrowser_altsource1')) get('video_altsource1').style.width = '220px'; if (isVisible('video_filebrowser_altsource2')) get('video_altsource2').style.width = '220px'; if (isVisible('audio_filebrowser_altsource1')) get('audio_altsource1').style.width = '220px'; if (isVisible('audio_filebrowser_altsource2')) get('audio_altsource2').style.width = '220px'; if (isVisible('filebrowser_poster')) get('video_poster').style.width = '220px'; editor.dom.setOuterHTML(get('media_type'), self.getMediaTypeHTML(editor)); self.setDefaultDialogSettings(editor); self.data = clone(tinyMCEPopup.getWindowArg('data')); self.dataToForm(); self.preview(); updateColor('bgcolor_pick', 'bgcolor'); }, insert : function() { var editor = tinyMCEPopup.editor; this.formToData(); editor.execCommand('mceRepaint'); tinyMCEPopup.restoreSelection(); editor.selection.setNode(editor.plugins.media.dataToImg(this.data)); tinyMCEPopup.close(); }, preview : function() { get('prev').innerHTML = this.editor.plugins.media.dataToHtml(this.data, true); }, moveStates : function(to_form, field) { var data = this.data, editor = this.editor, mediaPlugin = editor.plugins.media, ext, src, typeInfo, defaultStates, src; defaultStates = { // QuickTime quicktime_autoplay : true, quicktime_controller : true, // Flash flash_play : true, flash_loop : true, flash_menu : true, // WindowsMedia windowsmedia_autostart : true, windowsmedia_enablecontextmenu : true, windowsmedia_invokeurls : true, // RealMedia realmedia_autogotourl : true, realmedia_imagestatus : true }; function parseQueryParams(str) { var out = {}; if (str) { tinymce.each(str.split('&'), function(item) { var parts = item.split('='); out[unescape(parts[0])] = unescape(parts[1]); }); } return out; }; function setOptions(type, names) { var i, name, formItemName, value, list; if (type == data.type || type == 'global') { names = tinymce.explode(names); for (i = 0; i < names.length; i++) { name = names[i]; formItemName = type == 'global' ? name : type + '_' + name; if (type == 'global') list = data; else if (type == 'video' || type == 'audio') { list = data.video.attrs; if (!list && !to_form) data.video.attrs = list = {}; } else list = data.params; if (list) { if (to_form) { setVal(formItemName, list[name], type == 'video' || type == 'audio' ? name : ''); } else { delete list[name]; value = getVal(formItemName); if ((type == 'video' || type == 'audio') && value === true) value = name; if (defaultStates[formItemName]) { if (value !== defaultStates[formItemName]) { value = "" + value; list[name] = value; } } else if (value) { value = "" + value; list[name] = value; } } } } } } if (!to_form) { data.type = get('media_type').options[get('media_type').selectedIndex].value; data.width = getVal('width'); data.height = getVal('height'); // Switch type based on extension src = getVal('src'); if (field == 'src') { ext = src.replace(/^.*\.([^.]+)$/, '$1'); if (typeInfo = mediaPlugin.getType(ext)) data.type = typeInfo.name.toLowerCase(); setVal('media_type', data.type); } if (data.type == "video" || data.type == "audio") { if (!data.video.sources) data.video.sources = []; data.video.sources[0] = {src: getVal('src')}; } } // Hide all fieldsets and show the one active get('video_options').style.display = 'none'; get('audio_options').style.display = 'none'; get('flash_options').style.display = 'none'; get('quicktime_options').style.display = 'none'; get('shockwave_options').style.display = 'none'; get('windowsmedia_options').style.display = 'none'; get('realmedia_options').style.display = 'none'; get('embeddedaudio_options').style.display = 'none'; if (get(data.type + '_options')) get(data.type + '_options').style.display = 'block'; setVal('media_type', data.type); setOptions('flash', 'play,loop,menu,swliveconnect,quality,scale,salign,wmode,base,flashvars'); setOptions('quicktime', 'loop,autoplay,cache,controller,correction,enablejavascript,kioskmode,autohref,playeveryframe,targetcache,scale,starttime,endtime,target,qtsrcchokespeed,volume,qtsrc'); setOptions('shockwave', 'sound,progress,autostart,swliveconnect,swvolume,swstretchstyle,swstretchhalign,swstretchvalign'); setOptions('windowsmedia', 'autostart,enabled,enablecontextmenu,fullscreen,invokeurls,mute,stretchtofit,windowlessvideo,balance,baseurl,captioningid,currentmarker,currentposition,defaultframe,playcount,rate,uimode,volume'); setOptions('realmedia', 'autostart,loop,autogotourl,center,imagestatus,maintainaspect,nojava,prefetch,shuffle,console,controls,numloop,scriptcallbacks'); setOptions('video', 'poster,autoplay,loop,muted,preload,controls'); setOptions('audio', 'autoplay,loop,preload,controls'); setOptions('embeddedaudio', 'autoplay,loop,controls'); setOptions('global', 'id,name,vspace,hspace,bgcolor,align,width,height'); if (to_form) { if (data.type == 'video') { if (data.video.sources[0]) setVal('src', data.video.sources[0].src); src = data.video.sources[1]; if (src) setVal('video_altsource1', src.src); src = data.video.sources[2]; if (src) setVal('video_altsource2', src.src); } else if (data.type == 'audio') { if (data.video.sources[0]) setVal('src', data.video.sources[0].src); src = data.video.sources[1]; if (src) setVal('audio_altsource1', src.src); src = data.video.sources[2]; if (src) setVal('audio_altsource2', src.src); } else { // Check flash vars if (data.type == 'flash') { tinymce.each(editor.getParam('flash_video_player_flashvars', {url : '$url', poster : '$poster'}), function(value, name) { if (value == '$url') data.params.src = parseQueryParams(data.params.flashvars)[name] || data.params.src || ''; }); } setVal('src', data.params.src); } } else { src = getVal("src"); // YouTube *NEW* if (src.match(/youtu.be\/[a-z1-9.-_]+/)) { data.width = 425; data.height = 350; data.params.frameborder = '0'; data.type = 'iframe'; src = 'http://www.youtube.com/embed/' + src.match(/youtu.be\/([a-z1-9.-_]+)/)[1]; setVal('src', src); setVal('media_type', data.type); } // YouTube if (src.match(/youtube.com(.+)v=([^&]+)/)) { data.width = 425; data.height = 350; data.params.frameborder = '0'; data.type = 'iframe'; src = 'http://www.youtube.com/embed/' + src.match(/v=([^&]+)/)[1]; setVal('src', src); setVal('media_type', data.type); } // Google video if (src.match(/video.google.com(.+)docid=([^&]+)/)) { data.width = 425; data.height = 326; data.type = 'flash'; src = 'http://video.google.com/googleplayer.swf?docId=' + src.match(/docid=([^&]+)/)[1] + '&hl=en'; setVal('src', src); setVal('media_type', data.type); } if (data.type == 'video') { if (!data.video.sources) data.video.sources = []; data.video.sources[0] = {src : src}; src = getVal("video_altsource1"); if (src) data.video.sources[1] = {src : src}; src = getVal("video_altsource2"); if (src) data.video.sources[2] = {src : src}; } else if (data.type == 'audio') { if (!data.video.sources) data.video.sources = []; data.video.sources[0] = {src : src}; src = getVal("audio_altsource1"); if (src) data.video.sources[1] = {src : src}; src = getVal("audio_altsource2"); if (src) data.video.sources[2] = {src : src}; } else data.params.src = src; // Set default size setVal('width', data.width || (data.type == 'audio' ? 300 : 320)); setVal('height', data.height || (data.type == 'audio' ? 32 : 240)); } }, dataToForm : function() { this.moveStates(true); }, formToData : function(field) { if (field == "width" || field == "height") this.changeSize(field); if (field == 'source') { this.moveStates(false, field); setVal('source', this.editor.plugins.media.dataToHtml(this.data)); this.panel = 'source'; } else { if (this.panel == 'source') { this.data = clone(this.editor.plugins.media.htmlToData(getVal('source'))); this.dataToForm(); this.panel = ''; } this.moveStates(false, field); this.preview(); } }, beforeResize : function() { this.width = parseInt(getVal('width') || (this.data.type == 'audio' ? "300" : "320"), 10); this.height = parseInt(getVal('height') || (this.data.type == 'audio' ? "32" : "240"), 10); }, changeSize : function(type) { var width, height, scale, size; if (get('constrain').checked) { width = parseInt(getVal('width') || (this.data.type == 'audio' ? "300" : "320"), 10); height = parseInt(getVal('height') || (this.data.type == 'audio' ? "32" : "240"), 10); if (type == 'width') { this.height = Math.round((width / this.width) * height); setVal('height', this.height); } else { this.width = Math.round((height / this.height) * width); setVal('width', this.width); } } }, getMediaListHTML : function() { if (typeof(tinyMCEMediaList) != "undefined" && tinyMCEMediaList.length > 0) { var html = ""; html += '<select id="linklist" name="linklist" style="width: 250px" onchange="this.form.src.value=this.options[this.selectedIndex].value;Media.formToData(\'src\');">'; html += '<option value="">---</option>'; for (var i=0; i<tinyMCEMediaList.length; i++) html += '<option value="' + tinyMCEMediaList[i][1] + '">' + tinyMCEMediaList[i][0] + '</option>'; html += '</select>'; return html; } return ""; }, getMediaTypeHTML : function(editor) { function option(media_type, element) { if (!editor.schema.getElementRule(element || media_type)) { return ''; } return '<option value="'+media_type+'">'+tinyMCEPopup.editor.translate("media_dlg."+media_type)+'</option>' } var html = ""; html += '<select id="media_type" name="media_type" onchange="Media.formToData(\'type\');">'; html += option("video"); html += option("audio"); html += option("flash", "object"); html += option("quicktime", "object"); html += option("shockwave", "object"); html += option("windowsmedia", "object"); html += option("realmedia", "object"); html += option("iframe"); if (editor.getParam('media_embedded_audio', false)) { html += option('embeddedaudio', "object"); } html += '</select>'; return html; }, setDefaultDialogSettings : function(editor) { var defaultDialogSettings = editor.getParam("media_dialog_defaults", {}); tinymce.each(defaultDialogSettings, function(v, k) { setVal(k, v); }); } }; tinyMCEPopup.requireLangPack(); tinyMCEPopup.onInit.add(function() { Media.init(); }); })();
JavaScript
/** * This script contains embed functions for common plugins. This scripts are complety free to use for any purpose. */ function writeFlash(p) { writeEmbed( 'D27CDB6E-AE6D-11cf-96B8-444553540000', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0', 'application/x-shockwave-flash', p ); } function writeShockWave(p) { writeEmbed( '166B1BCA-3F9C-11CF-8075-444553540000', 'http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab#version=8,5,1,0', 'application/x-director', p ); } function writeQuickTime(p) { writeEmbed( '02BF25D5-8C17-4B23-BC80-D3488ABDDC6B', 'http://www.apple.com/qtactivex/qtplugin.cab#version=6,0,2,0', 'video/quicktime', p ); } function writeRealMedia(p) { writeEmbed( 'CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0', 'audio/x-pn-realaudio-plugin', p ); } function writeWindowsMedia(p) { p.url = p.src; writeEmbed( '6BF52A52-394A-11D3-B153-00C04F79FAA6', 'http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701', 'application/x-mplayer2', p ); } function writeEmbed(cls, cb, mt, p) { var h = '', n; h += '<object classid="clsid:' + cls + '" codebase="' + cb + '"'; h += typeof(p.id) != "undefined" ? 'id="' + p.id + '"' : ''; h += typeof(p.name) != "undefined" ? 'name="' + p.name + '"' : ''; h += typeof(p.width) != "undefined" ? 'width="' + p.width + '"' : ''; h += typeof(p.height) != "undefined" ? 'height="' + p.height + '"' : ''; h += typeof(p.align) != "undefined" ? 'align="' + p.align + '"' : ''; h += '>'; for (n in p) h += '<param name="' + n + '" value="' + p[n] + '">'; h += '<embed type="' + mt + '"'; for (n in p) h += n + '="' + p[n] + '" '; h += '></embed></object>'; document.write(h); }
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { var rootAttributes = tinymce.explode('id,name,width,height,style,align,class,hspace,vspace,bgcolor,type'), excludedAttrs = tinymce.makeMap(rootAttributes.join(',')), Node = tinymce.html.Node, mediaTypes, scriptRegExp, JSON = tinymce.util.JSON, mimeTypes; // Media types supported by this plugin mediaTypes = [ // Type, clsid:s, mime types, codebase ["Flash", "d27cdb6e-ae6d-11cf-96b8-444553540000", "application/x-shockwave-flash", "http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"], ["ShockWave", "166b1bca-3f9c-11cf-8075-444553540000", "application/x-director", "http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab#version=8,5,1,0"], ["WindowsMedia", "6bf52a52-394a-11d3-b153-00c04f79faa6,22d6f312-b0f6-11d0-94ab-0080c74c7e95,05589fa1-c356-11ce-bf01-00aa0055595a", "application/x-mplayer2", "http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701"], ["QuickTime", "02bf25d5-8c17-4b23-bc80-d3488abddc6b", "video/quicktime", "http://www.apple.com/qtactivex/qtplugin.cab#version=6,0,2,0"], ["RealMedia", "cfcdaa03-8be4-11cf-b84b-0020afbbccfa", "audio/x-pn-realaudio-plugin", "http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"], ["Java", "8ad9c840-044e-11d1-b3e9-00805f499d93", "application/x-java-applet", "http://java.sun.com/products/plugin/autodl/jinstall-1_5_0-windows-i586.cab#Version=1,5,0,0"], ["Silverlight", "dfeaf541-f3e1-4c24-acac-99c30715084a", "application/x-silverlight-2"], ["Iframe"], ["Video"], ["EmbeddedAudio"], ["Audio"] ]; function toArray(obj) { var undef, out, i; if (obj && !obj.splice) { out = []; for (i = 0; true; i++) { if (obj[i]) out[i] = obj[i]; else break; } return out; } return obj; }; tinymce.create('tinymce.plugins.MediaPlugin', { init : function(ed, url) { var self = this, lookup = {}, i, y, item, name; function isMediaImg(node) { return node && node.nodeName === 'IMG' && ed.dom.hasClass(node, 'mceItemMedia'); }; self.editor = ed; self.url = url; // Parse media types into a lookup table scriptRegExp = ''; for (i = 0; i < mediaTypes.length; i++) { name = mediaTypes[i][0]; item = { name : name, clsids : tinymce.explode(mediaTypes[i][1] || ''), mimes : tinymce.explode(mediaTypes[i][2] || ''), codebase : mediaTypes[i][3] }; for (y = 0; y < item.clsids.length; y++) lookup['clsid:' + item.clsids[y]] = item; for (y = 0; y < item.mimes.length; y++) lookup[item.mimes[y]] = item; lookup['mceItem' + name] = item; lookup[name.toLowerCase()] = item; scriptRegExp += (scriptRegExp ? '|' : '') + name; } // Handle the media_types setting tinymce.each(ed.getParam("media_types", "video=mp4,m4v,ogv,webm;" + "silverlight=xap;" + "flash=swf,flv;" + "shockwave=dcr;" + "quicktime=mov,qt,mpg,mpeg;" + "shockwave=dcr;" + "windowsmedia=avi,wmv,wm,asf,asx,wmx,wvx;" + "realmedia=rm,ra,ram;" + "java=jar;" + "audio=mp3,ogg" ).split(';'), function(item) { var i, extensions, type; item = item.split(/=/); extensions = tinymce.explode(item[1].toLowerCase()); for (i = 0; i < extensions.length; i++) { type = lookup[item[0].toLowerCase()]; if (type) lookup[extensions[i]] = type; } }); scriptRegExp = new RegExp('write(' + scriptRegExp + ')\\(([^)]+)\\)'); self.lookup = lookup; ed.onPreInit.add(function() { // Allow video elements ed.schema.addValidElements('object[id|style|width|height|classid|codebase|*],param[name|value],embed[id|style|width|height|type|src|*],video[*],audio[*],source[*]'); // Convert video elements to image placeholder ed.parser.addNodeFilter('object,embed,video,audio,script,iframe', function(nodes) { var i = nodes.length; while (i--) self.objectToImg(nodes[i]); }); // Convert image placeholders to video elements ed.serializer.addNodeFilter('img', function(nodes, name, args) { var i = nodes.length, node; while (i--) { node = nodes[i]; if ((node.attr('class') || '').indexOf('mceItemMedia') !== -1) self.imgToObject(node, args); } }); }); ed.onInit.add(function() { // Display "media" instead of "img" in element path if (ed.theme && ed.theme.onResolveName) { ed.theme.onResolveName.add(function(theme, path_object) { if (path_object.name === 'img' && ed.dom.hasClass(path_object.node, 'mceItemMedia')) path_object.name = 'media'; }); } // Add contect menu if it's loaded if (ed && ed.plugins.contextmenu) { ed.plugins.contextmenu.onContextMenu.add(function(plugin, menu, element) { if (element.nodeName === 'IMG' && element.className.indexOf('mceItemMedia') !== -1) menu.add({title : 'media.edit', icon : 'media', cmd : 'mceMedia'}); }); } }); // Register commands ed.addCommand('mceMedia', function() { var data, img; img = ed.selection.getNode(); if (isMediaImg(img)) { data = ed.dom.getAttrib(img, 'data-mce-json'); if (data) { data = JSON.parse(data); // Add some extra properties to the data object tinymce.each(rootAttributes, function(name) { var value = ed.dom.getAttrib(img, name); if (value) data[name] = value; }); data.type = self.getType(img.className).name.toLowerCase(); } } if (!data) { data = { type : 'flash', video: {sources:[]}, params: {} }; } ed.windowManager.open({ file : url + '/media.htm', width : 430 + parseInt(ed.getLang('media.delta_width', 0)), height : 500 + parseInt(ed.getLang('media.delta_height', 0)), inline : 1 }, { plugin_url : url, data : data }); }); // Register buttons ed.addButton('media', {title : 'media.desc', cmd : 'mceMedia'}); // Update media selection status ed.onNodeChange.add(function(ed, cm, node) { cm.setActive('media', isMediaImg(node)); }); }, convertUrl : function(url, force_absolute) { var self = this, editor = self.editor, settings = editor.settings, urlConverter = settings.url_converter, urlConverterScope = settings.url_converter_scope || self; if (!url) return url; if (force_absolute) return editor.documentBaseURI.toAbsolute(url); return urlConverter.call(urlConverterScope, url, 'src', 'object'); }, getInfo : function() { return { longname : 'Media', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/media', version : tinymce.majorVersion + "." + tinymce.minorVersion }; }, /** * Converts the JSON data object to an img node. */ dataToImg : function(data, force_absolute) { var self = this, editor = self.editor, baseUri = editor.documentBaseURI, sources, attrs, img, i; data.params.src = self.convertUrl(data.params.src, force_absolute); attrs = data.video.attrs; if (attrs) attrs.src = self.convertUrl(attrs.src, force_absolute); if (attrs) attrs.poster = self.convertUrl(attrs.poster, force_absolute); sources = toArray(data.video.sources); if (sources) { for (i = 0; i < sources.length; i++) sources[i].src = self.convertUrl(sources[i].src, force_absolute); } img = self.editor.dom.create('img', { id : data.id, style : data.style, align : data.align, hspace : data.hspace, vspace : data.vspace, src : self.editor.theme.url + '/img/trans.gif', 'class' : 'mceItemMedia mceItem' + self.getType(data.type).name, 'data-mce-json' : JSON.serialize(data, "'") }); img.width = data.width || (data.type == 'audio' ? "300" : "320"); img.height = data.height || (data.type == 'audio' ? "32" : "240"); return img; }, /** * Converts the JSON data object to a HTML string. */ dataToHtml : function(data, force_absolute) { return this.editor.serializer.serialize(this.dataToImg(data, force_absolute), {forced_root_block : '', force_absolute : force_absolute}); }, /** * Converts the JSON data object to a HTML string. */ htmlToData : function(html) { var fragment, img, data; data = { type : 'flash', video: {sources:[]}, params: {} }; fragment = this.editor.parser.parse(html); img = fragment.getAll('img')[0]; if (img) { data = JSON.parse(img.attr('data-mce-json')); data.type = this.getType(img.attr('class')).name.toLowerCase(); // Add some extra properties to the data object tinymce.each(rootAttributes, function(name) { var value = img.attr(name); if (value) data[name] = value; }); } return data; }, /** * Get type item by extension, class, clsid or mime type. * * @method getType * @param {String} value Value to get type item by. * @return {Object} Type item object or undefined. */ getType : function(value) { var i, values, typeItem; // Find type by checking the classes values = tinymce.explode(value, ' '); for (i = 0; i < values.length; i++) { typeItem = this.lookup[values[i]]; if (typeItem) return typeItem; } }, /** * Converts a tinymce.html.Node image element to video/object/embed. */ imgToObject : function(node, args) { var self = this, editor = self.editor, video, object, embed, iframe, name, value, data, source, sources, params, param, typeItem, i, item, mp4Source, replacement, posterSrc, style, audio; // Adds the flash player function addPlayer(video_src, poster_src) { var baseUri, flashVars, flashVarsOutput, params, flashPlayer; flashPlayer = editor.getParam('flash_video_player_url', self.convertUrl(self.url + '/moxieplayer.swf')); if (flashPlayer) { baseUri = editor.documentBaseURI; data.params.src = flashPlayer; // Convert the movie url to absolute urls if (editor.getParam('flash_video_player_absvideourl', true)) { video_src = baseUri.toAbsolute(video_src || '', true); poster_src = baseUri.toAbsolute(poster_src || '', true); } // Generate flash vars flashVarsOutput = ''; flashVars = editor.getParam('flash_video_player_flashvars', {url : '$url', poster : '$poster'}); tinymce.each(flashVars, function(value, name) { // Replace $url and $poster variables in flashvars value value = value.replace(/\$url/, video_src || ''); value = value.replace(/\$poster/, poster_src || ''); if (value.length > 0) flashVarsOutput += (flashVarsOutput ? '&' : '') + name + '=' + escape(value); }); if (flashVarsOutput.length) data.params.flashvars = flashVarsOutput; params = editor.getParam('flash_video_player_params', { allowfullscreen: true, allowscriptaccess: true }); tinymce.each(params, function(value, name) { data.params[name] = "" + value; }); } }; data = node.attr('data-mce-json'); if (!data) return; data = JSON.parse(data); typeItem = this.getType(node.attr('class')); style = node.attr('data-mce-style') if (!style) { style = node.attr('style'); if (style) style = editor.dom.serializeStyle(editor.dom.parseStyle(style, 'img')); } // Handle iframe if (typeItem.name === 'Iframe') { replacement = new Node('iframe', 1); tinymce.each(rootAttributes, function(name) { var value = node.attr(name); if (name == 'class' && value) value = value.replace(/mceItem.+ ?/g, ''); if (value && value.length > 0) replacement.attr(name, value); }); for (name in data.params) replacement.attr(name, data.params[name]); replacement.attr({ style: style, src: data.params.src }); node.replace(replacement); return; } // Handle scripts if (this.editor.settings.media_use_script) { replacement = new Node('script', 1).attr('type', 'text/javascript'); value = new Node('#text', 3); value.value = 'write' + typeItem.name + '(' + JSON.serialize(tinymce.extend(data.params, { width: node.attr('width'), height: node.attr('height') })) + ');'; replacement.append(value); node.replace(replacement); return; } // Add HTML5 video element if (typeItem.name === 'Video' && data.video.sources[0]) { // Create new object element video = new Node('video', 1).attr(tinymce.extend({ id : node.attr('id'), width: node.attr('width'), height: node.attr('height'), style : style }, data.video.attrs)); // Get poster source and use that for flash fallback if (data.video.attrs) posterSrc = data.video.attrs.poster; sources = data.video.sources = toArray(data.video.sources); for (i = 0; i < sources.length; i++) { if (/\.mp4$/.test(sources[i].src)) mp4Source = sources[i].src; } if (!sources[0].type) { video.attr('src', sources[0].src); sources.splice(0, 1); } for (i = 0; i < sources.length; i++) { source = new Node('source', 1).attr(sources[i]); source.shortEnded = true; video.append(source); } // Create flash fallback for video if we have a mp4 source if (mp4Source) { addPlayer(mp4Source, posterSrc); typeItem = self.getType('flash'); } else data.params.src = ''; } // Add HTML5 audio element if (typeItem.name === 'Audio' && data.video.sources[0]) { // Create new object element audio = new Node('audio', 1).attr(tinymce.extend({ id : node.attr('id'), width: node.attr('width'), height: node.attr('height'), style : style }, data.video.attrs)); // Get poster source and use that for flash fallback if (data.video.attrs) posterSrc = data.video.attrs.poster; sources = data.video.sources = toArray(data.video.sources); if (!sources[0].type) { audio.attr('src', sources[0].src); sources.splice(0, 1); } for (i = 0; i < sources.length; i++) { source = new Node('source', 1).attr(sources[i]); source.shortEnded = true; audio.append(source); } data.params.src = ''; } if (typeItem.name === 'EmbeddedAudio') { embed = new Node('embed', 1); embed.shortEnded = true; embed.attr({ id: node.attr('id'), width: node.attr('width'), height: node.attr('height'), style : style, type: node.attr('type') }); for (name in data.params) embed.attr(name, data.params[name]); tinymce.each(rootAttributes, function(name) { if (data[name] && name != 'type') embed.attr(name, data[name]); }); data.params.src = ''; } // Do we have a params src then we can generate object if (data.params.src) { // Is flv movie add player for it if (/\.flv$/i.test(data.params.src)) addPlayer(data.params.src, ''); if (args && args.force_absolute) data.params.src = editor.documentBaseURI.toAbsolute(data.params.src); // Create new object element object = new Node('object', 1).attr({ id : node.attr('id'), width: node.attr('width'), height: node.attr('height'), style : style }); tinymce.each(rootAttributes, function(name) { var value = data[name]; if (name == 'class' && value) value = value.replace(/mceItem.+ ?/g, ''); if (value && name != 'type') object.attr(name, value); }); // Add params for (name in data.params) { param = new Node('param', 1); param.shortEnded = true; value = data.params[name]; // Windows media needs to use url instead of src for the media URL if (name === 'src' && typeItem.name === 'WindowsMedia') name = 'url'; param.attr({name: name, value: value}); object.append(param); } // Setup add type and classid if strict is disabled if (this.editor.getParam('media_strict', true)) { object.attr({ data: data.params.src, type: typeItem.mimes[0] }); } else { object.attr({ classid: "clsid:" + typeItem.clsids[0], codebase: typeItem.codebase }); embed = new Node('embed', 1); embed.shortEnded = true; embed.attr({ id: node.attr('id'), width: node.attr('width'), height: node.attr('height'), style : style, type: typeItem.mimes[0] }); for (name in data.params) embed.attr(name, data.params[name]); tinymce.each(rootAttributes, function(name) { if (data[name] && name != 'type') embed.attr(name, data[name]); }); object.append(embed); } // Insert raw HTML if (data.object_html) { value = new Node('#text', 3); value.raw = true; value.value = data.object_html; object.append(value); } // Append object to video element if it exists if (video) video.append(object); } if (video) { // Insert raw HTML if (data.video_html) { value = new Node('#text', 3); value.raw = true; value.value = data.video_html; video.append(value); } } if (audio) { // Insert raw HTML if (data.video_html) { value = new Node('#text', 3); value.raw = true; value.value = data.video_html; audio.append(value); } } var n = video || audio || object || embed; if (n) node.replace(n); else node.remove(); }, /** * Converts a tinymce.html.Node video/object/embed to an img element. * * The video/object/embed will be converted into an image placeholder with a JSON data attribute like this: * <img class="mceItemMedia mceItemFlash" width="100" height="100" data-mce-json="{..}" /> * * The JSON structure will be like this: * {'params':{'flashvars':'something','quality':'high','src':'someurl'}, 'video':{'sources':[{src: 'someurl', type: 'video/mp4'}]}} */ objectToImg : function(node) { var object, embed, video, iframe, img, name, id, width, height, style, i, html, param, params, source, sources, data, type, lookup = this.lookup, matches, attrs, urlConverter = this.editor.settings.url_converter, urlConverterScope = this.editor.settings.url_converter_scope, hspace, vspace, align, bgcolor; function getInnerHTML(node) { return new tinymce.html.Serializer({ inner: true, validate: false }).serialize(node); }; function lookupAttribute(o, attr) { return lookup[(o.attr(attr) || '').toLowerCase()]; } function lookupExtension(src) { var ext = src.replace(/^.*\.([^.]+)$/, '$1'); return lookup[ext.toLowerCase() || '']; } // If node isn't in document if (!node.parent) return; // Handle media scripts if (node.name === 'script') { if (node.firstChild) matches = scriptRegExp.exec(node.firstChild.value); if (!matches) return; type = matches[1]; data = {video : {}, params : JSON.parse(matches[2])}; width = data.params.width; height = data.params.height; } // Setup data objects data = data || { video : {}, params : {} }; // Setup new image object img = new Node('img', 1); img.attr({ src : this.editor.theme.url + '/img/trans.gif' }); // Video element name = node.name; if (name === 'video' || name == 'audio') { video = node; object = node.getAll('object')[0]; embed = node.getAll('embed')[0]; width = video.attr('width'); height = video.attr('height'); id = video.attr('id'); data.video = {attrs : {}, sources : []}; // Get all video attributes attrs = data.video.attrs; for (name in video.attributes.map) attrs[name] = video.attributes.map[name]; source = node.attr('src'); if (source) data.video.sources.push({src : urlConverter.call(urlConverterScope, source, 'src', node.name)}); // Get all sources sources = video.getAll("source"); for (i = 0; i < sources.length; i++) { source = sources[i].remove(); data.video.sources.push({ src: urlConverter.call(urlConverterScope, source.attr('src'), 'src', 'source'), type: source.attr('type'), media: source.attr('media') }); } // Convert the poster URL if (attrs.poster) attrs.poster = urlConverter.call(urlConverterScope, attrs.poster, 'poster', node.name); } // Object element if (node.name === 'object') { object = node; embed = node.getAll('embed')[0]; } // Embed element if (node.name === 'embed') embed = node; // Iframe element if (node.name === 'iframe') { iframe = node; type = 'Iframe'; } if (object) { // Get width/height width = width || object.attr('width'); height = height || object.attr('height'); style = style || object.attr('style'); id = id || object.attr('id'); hspace = hspace || object.attr('hspace'); vspace = vspace || object.attr('vspace'); align = align || object.attr('align'); bgcolor = bgcolor || object.attr('bgcolor'); data.name = object.attr('name'); // Get all object params params = object.getAll("param"); for (i = 0; i < params.length; i++) { param = params[i]; name = param.remove().attr('name'); if (!excludedAttrs[name]) data.params[name] = param.attr('value'); } data.params.src = data.params.src || object.attr('data'); } if (embed) { // Get width/height width = width || embed.attr('width'); height = height || embed.attr('height'); style = style || embed.attr('style'); id = id || embed.attr('id'); hspace = hspace || embed.attr('hspace'); vspace = vspace || embed.attr('vspace'); align = align || embed.attr('align'); bgcolor = bgcolor || embed.attr('bgcolor'); // Get all embed attributes for (name in embed.attributes.map) { if (!excludedAttrs[name] && !data.params[name]) data.params[name] = embed.attributes.map[name]; } } if (iframe) { // Get width/height width = iframe.attr('width'); height = iframe.attr('height'); style = style || iframe.attr('style'); id = iframe.attr('id'); hspace = iframe.attr('hspace'); vspace = iframe.attr('vspace'); align = iframe.attr('align'); bgcolor = iframe.attr('bgcolor'); tinymce.each(rootAttributes, function(name) { img.attr(name, iframe.attr(name)); }); // Get all iframe attributes for (name in iframe.attributes.map) { if (!excludedAttrs[name] && !data.params[name]) data.params[name] = iframe.attributes.map[name]; } } // Use src not movie if (data.params.movie) { data.params.src = data.params.src || data.params.movie; delete data.params.movie; } // Convert the URL to relative/absolute depending on configuration if (data.params.src) data.params.src = urlConverter.call(urlConverterScope, data.params.src, 'src', 'object'); if (video) { if (node.name === 'video') type = lookup.video.name; else if (node.name === 'audio') type = lookup.audio.name; } if (object && !type) type = (lookupAttribute(object, 'clsid') || lookupAttribute(object, 'classid') || lookupAttribute(object, 'type') || {}).name; if (embed && !type) type = (lookupAttribute(embed, 'type') || lookupExtension(data.params.src) || {}).name; // for embedded audio we preserve the original specified type if (embed && type == 'EmbeddedAudio') { data.params.type = embed.attr('type'); } // Replace the video/object/embed element with a placeholder image containing the data node.replace(img); // Remove embed if (embed) embed.remove(); // Serialize the inner HTML of the object element if (object) { html = getInnerHTML(object.remove()); if (html) data.object_html = html; } // Serialize the inner HTML of the video element if (video) { html = getInnerHTML(video.remove()); if (html) data.video_html = html; } data.hspace = hspace; data.vspace = vspace; data.align = align; data.bgcolor = bgcolor; // Set width/height of placeholder img.attr({ id : id, 'class' : 'mceItemMedia mceItem' + (type || 'Flash'), style : style, width : width || (node.name == 'audio' ? "300" : "320"), height : height || (node.name == 'audio' ? "32" : "240"), hspace : hspace, vspace : vspace, align : align, bgcolor : bgcolor, "data-mce-json" : JSON.serialize(data, "'") }); } }); // Register plugin tinymce.PluginManager.add('media', tinymce.plugins.MediaPlugin); })();
JavaScript
(function() { tinymce.create('tinymce.plugins.wpGallery', { init : function(ed, url) { var t = this; t.url = url; t._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
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { var DOM = tinymce.DOM; tinymce.create('tinymce.plugins.FullScreenPlugin', { init : function(ed, url) { var t = this, s = {}, vp, posCss; t.editor = ed; // Register commands ed.addCommand('mceFullScreen', function() { var win, de = DOM.doc.documentElement; if (ed.getParam('fullscreen_is_enabled')) { if (ed.getParam('fullscreen_new_window')) closeFullscreen(); // Call to close in new window else { DOM.win.setTimeout(function() { tinymce.dom.Event.remove(DOM.win, 'resize', t.resizeFunc); tinyMCE.get(ed.getParam('fullscreen_editor_id')).setContent(ed.getContent()); tinyMCE.remove(ed); DOM.remove('mce_fullscreen_container'); de.style.overflow = ed.getParam('fullscreen_html_overflow'); DOM.setStyle(DOM.doc.body, 'overflow', ed.getParam('fullscreen_overflow')); DOM.win.scrollTo(ed.getParam('fullscreen_scrollx'), ed.getParam('fullscreen_scrolly')); tinyMCE.settings = tinyMCE.oldSettings; // Restore old settings }, 10); } return; } if (ed.getParam('fullscreen_new_window')) { win = DOM.win.open(url + "/fullscreen.htm", "mceFullScreenPopup", "fullscreen=yes,menubar=no,toolbar=no,scrollbars=no,resizable=yes,left=0,top=0,width=" + screen.availWidth + ",height=" + screen.availHeight); try { win.resizeTo(screen.availWidth, screen.availHeight); } catch (e) { // Ignore } } else { tinyMCE.oldSettings = tinyMCE.settings; // Store old settings s.fullscreen_overflow = DOM.getStyle(DOM.doc.body, 'overflow', 1) || 'auto'; s.fullscreen_html_overflow = DOM.getStyle(de, 'overflow', 1); vp = DOM.getViewPort(); s.fullscreen_scrollx = vp.x; s.fullscreen_scrolly = vp.y; // Fixes an Opera bug where the scrollbars doesn't reappear if (tinymce.isOpera && s.fullscreen_overflow == 'visible') s.fullscreen_overflow = 'auto'; // Fixes an IE bug where horizontal scrollbars would appear if (tinymce.isIE && s.fullscreen_overflow == 'scroll') s.fullscreen_overflow = 'auto'; // Fixes an IE bug where the scrollbars doesn't reappear if (tinymce.isIE && (s.fullscreen_html_overflow == 'visible' || s.fullscreen_html_overflow == 'scroll')) s.fullscreen_html_overflow = 'auto'; if (s.fullscreen_overflow == '0px') s.fullscreen_overflow = ''; DOM.setStyle(DOM.doc.body, 'overflow', 'hidden'); de.style.overflow = 'hidden'; //Fix for IE6/7 vp = DOM.getViewPort(); DOM.win.scrollTo(0, 0); if (tinymce.isIE) vp.h -= 1; // Use fixed position if it exists if (tinymce.isIE6) posCss = 'absolute;top:' + vp.y; else posCss = 'fixed;top:0'; n = DOM.add(DOM.doc.body, 'div', { id : 'mce_fullscreen_container', style : 'position:' + posCss + ';left:0;width:' + vp.w + 'px;height:' + vp.h + 'px;z-index:200000;'}); DOM.add(n, 'div', {id : 'mce_fullscreen'}); tinymce.each(ed.settings, function(v, n) { s[n] = v; }); s.id = 'mce_fullscreen'; s.width = n.clientWidth; s.height = n.clientHeight - 15; s.fullscreen_is_enabled = true; s.fullscreen_editor_id = ed.id; s.theme_advanced_resizing = false; s.save_onsavecallback = function() { ed.setContent(tinyMCE.get(s.id).getContent()); ed.execCommand('mceSave'); }; tinymce.each(ed.getParam('fullscreen_settings'), function(v, k) { s[k] = v; }); if (s.theme_advanced_toolbar_location === 'external') s.theme_advanced_toolbar_location = 'top'; t.fullscreenEditor = new tinymce.Editor('mce_fullscreen', s); t.fullscreenEditor.onInit.add(function() { t.fullscreenEditor.setContent(ed.getContent()); t.fullscreenEditor.focus(); }); t.fullscreenEditor.render(); t.fullscreenElement = new tinymce.dom.Element('mce_fullscreen_container'); t.fullscreenElement.update(); //document.body.overflow = 'hidden'; t.resizeFunc = tinymce.dom.Event.add(DOM.win, 'resize', function() { var vp = tinymce.DOM.getViewPort(), fed = t.fullscreenEditor, outerSize, innerSize; // Get outer/inner size to get a delta size that can be used to calc the new iframe size outerSize = fed.dom.getSize(fed.getContainer().firstChild); innerSize = fed.dom.getSize(fed.getContainer().getElementsByTagName('iframe')[0]); fed.theme.resizeTo(vp.w - outerSize.w + innerSize.w, vp.h - outerSize.h + innerSize.h); }); } }); // Register buttons ed.addButton('fullscreen', {title : 'fullscreen.desc', cmd : 'mceFullScreen'}); ed.onNodeChange.add(function(ed, cm) { cm.setActive('fullscreen', ed.getParam('fullscreen_is_enabled')); }); }, getInfo : function() { return { longname : 'Fullscreen', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/fullscreen', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); // Register plugin tinymce.PluginManager.add('fullscreen', tinymce.plugins.FullScreenPlugin); })();
JavaScript
var tinymce = null, tinyMCEPopup, tinyMCE, wpImage; tinyMCEPopup = { 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; // 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.frameElement && window.dialogArguments) || opener || parent || top; }, getParam : function(n, dv) { return this.editor.getParam(n, dv); }, close : function() { var t = this; // To avoid domain relaxing issue in Opera function close() { t.editor.windowManager.close(window); tinymce = tinyMCE = t.editor = t.params = t.dom = t.dom.doc = null; // Cleanup }; if (tinymce.isOpera) t.getWin().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(1); }, 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 ed = tinyMCEPopup.editor, 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.getElementsByTagName('head')[0].appendChild( ed.dom.create('link', {rel:'stylesheet', href: url}) ); break; } } }, 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, DD, 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); } DD = ed.dom.select('dd.wp-caption-dd', DL); if ( DD && DD[0] ) caption = ed.serializer.serialize(DD[0]).replace(/^<p>/, '').replace(/<\/p>$/, ''); } f.img_cap_text.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, caption; tinyMCEPopup.restoreSelection(); el = ed.selection.getNode(); if (el.nodeName != 'IMG') return; if (f.img_src.value === '') { t.remove(); return; } if ( f.img_cap_text.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"); if ( f.width.value != el.width || f.height.value != el.height ) img_class = img_class.replace(/size-[^ "']+/, ''); 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); 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#' ) { 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'; caption = f.img_cap_text.value; caption = caption.replace(/\r\n|\r/g, '\n').replace(/<[a-zA-Z0-9]+( [^<>]+)?>/g, function(a){ return a.replace(/[\r\n\t]+/, ' '); }); caption = caption.replace(/\s*\n\s*/g, '<br />'); 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, caption); } 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">'+caption+'</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', { url: '', editor: {}, init: function(ed, url) { var t = this, mouse = {}; t.url = url; t.editor = ed; t._createButtons(); // Register the command so that it can be invoked by using tinyMCE.activeEditor.execCommand('...'); ed.addCommand('WP_EditImage', function() { var el = ed.selection.getNode(), vp, H, W, cls = ed.dom.getAttrib(el, 'class'); if ( cls.indexOf('mceItem') != -1 || cls.indexOf('wpGallery') != -1 || el.nodeName != 'IMG' ) return; vp = tinymce.DOM.getViewPort(); H = 680 < (vp.h - 70) ? 680 : vp.h - 70; W = 650 < vp.w ? 650 : vp.w; ed.windowManager.open({ file: url + '/editimage.html', width: W+'px', height: H+'px', inline: true }); }); ed.onInit.add(function(ed) { ed.dom.events.add(ed.getBody(), 'dragstart', function(e) { var parent; if ( e.target.nodeName == 'IMG' && ( parent = ed.dom.getParent(e.target, 'div.mceTemp') ) ) { ed.selection.select(parent); } }); }); // 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 ( mouse.x && (e.clientX != mouse.x || e.clientY != mouse.y) ) { var n = ed.selection.getNode(); if ( 'IMG' == n.nodeName ) { window.setTimeout(function(){ var DL = ed.dom.getParent(n, 'dl.wp-caption'), width; if ( n.width != mouse.img_w || n.height != mouse.img_h ) n.className = n.className.replace(/size-[^ "']+/, ''); if ( DL ) { width = ed.dom.getAttrib(n, 'width') || n.width; width = parseInt(width, 10); ed.dom.setStyle(DL, 'width', 10 + width); ed.execCommand('mceRepaint'); } }, 100); } } mouse = {}; }); // show editimage buttons ed.onMouseDown.add(function(ed, e) { var target = e.target; if ( target.nodeName != 'IMG' ) { if ( target.firstChild && target.firstChild.nodeName == 'IMG' && target.childNodes.length == 1 ) target = target.firstChild; else return; } if ( ed.dom.getAttrib(target, 'class').indexOf('mceItem') == -1 ) { mouse = { x: e.clientX, y: e.clientY, img_w: target.clientWidth, img_h: target.clientHeight }; ed.plugins.wordpress._showButtons(target, 'wp_editbtns'); } }); // when pressing Return inside a caption move the caret 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'); if ( DL ) DIV = ed.dom.getParent(DL, 'div.mceTemp'); if ( DIV ) { P = ed.dom.create('p', {}, '<br>'); ed.dom.insertAfter( P, DIV ); ed.selection.select(P.firstChild); if ( tinymce.isIE ) { ed.selection.setContent(''); } else { ed.selection.setContent('<br _moz_dirty="">'); ed.selection.setCursorLocation(P, 0); } ed.dom.events.cancel(e); return false; } } }); ed.onBeforeSetContent.add(function(ed, o) { o.content = ed.wpSetImgCaption(o.content); }); ed.onPostProcess.add(function(ed, o) { if (o.get) o.content = ed.wpGetImgCaption(o.content); }); ed.wpSetImgCaption = function(content) { return t._do_shcode(content); }; ed.wpGetImgCaption = function(content) { return t._get_shcode(content); }; }, _do_shcode : function(content) { return content.replace(/(?:<p>)?\[(?:wp_)?caption([^\]]+)\]([\s\S]+?)\[\/(?:wp_)?caption\](?:<\/p>)?/g, function(a,b,c){ var id, cls, w, cap, div_cls, img, trim = tinymce.trim; id = b.match(/id=['"]([^'"]*)['"] ?/); b = b.replace(id[0], ''); cls = b.match(/align=['"]([^'"]*)['"] ?/); b = b.replace(cls[0], ''); w = b.match(/width=['"]([0-9]*)['"] ?/); b = b.replace(w[0], ''); c = trim(c); img = c.match(/((?:<a [^>]+>)?<img [^>]+>(?:<\/a>)?)([\s\S]*)/i); if ( img && img[2] ) { cap = trim( img[2] ); img = trim( img[1] ); } else { // old captions shortcode style cap = trim(b).replace(/caption=['"]/, '').replace(/['"]$/, ''); img = c; } id = ( id && id[1] ) ? id[1] : ''; cls = ( cls && cls[1] ) ? cls[1] : 'alignnone'; w = ( w && w[1] ) ? w[1] : ''; if ( !w || !cap ) return c; div_cls = 'mceTemp'; if ( cls == 'aligncenter' ) div_cls += ' mceIEcenter'; return '<div class="'+div_cls+'"><dl id="'+id+'" class="wp-caption '+cls+'" style="width: '+( 10 + parseInt(w) )+ 'px"><dt class="wp-caption-dt">'+img+'</dt><dd class="wp-caption-dd">'+cap+'</dd></dl></div>'; }); }, _get_shcode : function(content) { return content.replace(/<div (?:id="attachment_|class="mceTemp)[^>]*>([\s\S]+?)<\/div>/g, function(a, b){ var ret = b.replace(/<dl ([^>]+)>\s*<dt [^>]+>([\s\S]+?)<\/dt>\s*<dd [^>]+>([\s\S]*?)<\/dd>\s*<\/dl>/gi, function(a,b,c,cap){ var id, cls, w; w = c.match(/width="([0-9]*)"/); w = ( w && w[1] ) ? w[1] : ''; if ( !w || !cap ) return c; id = b.match(/id="([^"]*)"/); id = ( id && id[1] ) ? id[1] : ''; cls = b.match(/class="([^"]*)"/); cls = ( cls && cls[1] ) ? cls[1] : ''; cls = cls.match(/align[a-z]+/) || 'alignnone'; cap = cap.replace(/\r\n|\r/g, '\n').replace(/<[a-zA-Z0-9]+( [^<>]+)?>/g, function(a){ // no line breaks inside HTML tags return a.replace(/[\r\n\t]+/, ' '); }); // convert remaining line breaks to <br> cap = cap.replace(/\s*\n\s*/g, '<br />'); return '[caption id="'+id+'" align="'+cls+'" width="'+w+'"]'+c+' '+cap+'[/caption]'; }); if ( ret.indexOf('[caption') !== 0 ) { // the caption html seems brocken, try to find the image that may be wrapped in a link // and may be followed by <p> with the caption text. ret = b.replace(/[\s\S]*?((?:<a [^>]+>)?<img [^>]+>(?:<\/a>)?)(<p>[\s\S]*<\/p>)?[\s\S]*/gi, '<p>$1</p>$2'); } return ret; }); }, _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 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
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
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { var each = tinymce.each, defs = { paste_auto_cleanup_on_paste : true, paste_enable_default_filters : true, paste_block_drop : false, paste_retain_style_properties : "none", paste_strip_class_attributes : "mso", paste_remove_spans : false, paste_remove_styles : false, paste_remove_styles_if_webkit : true, paste_convert_middot_lists : true, paste_convert_headers_to_strong : false, paste_dialog_width : "450", paste_dialog_height : "400", paste_text_use_dialog : false, paste_text_sticky : false, paste_text_sticky_default : false, paste_text_notifyalways : false, paste_text_linebreaktype : "combined", paste_text_replacements : [ [/\u2026/g, "..."], [/[\x93\x94\u201c\u201d]/g, '"'], [/[\x60\x91\x92\u2018\u2019]/g, "'"] ] }; function getParam(ed, name) { return ed.getParam(name, defs[name]); } tinymce.create('tinymce.plugins.PastePlugin', { init : function(ed, url) { var t = this; t.editor = ed; t.url = url; // Setup plugin events t.onPreProcess = new tinymce.util.Dispatcher(t); t.onPostProcess = new tinymce.util.Dispatcher(t); // Register default handlers t.onPreProcess.add(t._preProcess); t.onPostProcess.add(t._postProcess); // Register optional preprocess handler t.onPreProcess.add(function(pl, o) { ed.execCallback('paste_preprocess', pl, o); }); // Register optional postprocess t.onPostProcess.add(function(pl, o) { ed.execCallback('paste_postprocess', pl, o); }); ed.onKeyDown.addToTop(function(ed, e) { // Block ctrl+v from adding an undo level since the default logic in tinymce.Editor will add that if (((tinymce.isMac ? e.metaKey : e.ctrlKey) && e.keyCode == 86) || (e.shiftKey && e.keyCode == 45)) return false; // Stop other listeners }); // Initialize plain text flag ed.pasteAsPlainText = getParam(ed, 'paste_text_sticky_default'); // This function executes the process handlers and inserts the contents // force_rich overrides plain text mode set by user, important for pasting with execCommand function process(o, force_rich) { var dom = ed.dom, rng; // Execute pre process handlers t.onPreProcess.dispatch(t, o); // Create DOM structure o.node = dom.create('div', 0, o.content); // If pasting inside the same element and the contents is only one block // remove the block and keep the text since Firefox will copy parts of pre and h1-h6 as a pre element if (tinymce.isGecko) { rng = ed.selection.getRng(true); if (rng.startContainer == rng.endContainer && rng.startContainer.nodeType == 3) { // Is only one block node and it doesn't contain word stuff if (o.node.childNodes.length === 1 && /^(p|h[1-6]|pre)$/i.test(o.node.firstChild.nodeName) && o.content.indexOf('__MCE_ITEM__') === -1) dom.remove(o.node.firstChild, true); } } // Execute post process handlers t.onPostProcess.dispatch(t, o); // Serialize content o.content = ed.serializer.serialize(o.node, {getInner : 1, forced_root_block : ''}); // Plain text option active? if ((!force_rich) && (ed.pasteAsPlainText)) { t._insertPlainText(o.content); if (!getParam(ed, "paste_text_sticky")) { ed.pasteAsPlainText = false; ed.controlManager.setActive("pastetext", false); } } else { t._insert(o.content); } } // Add command for external usage ed.addCommand('mceInsertClipboardContent', function(u, o) { process(o, true); }); if (!getParam(ed, "paste_text_use_dialog")) { ed.addCommand('mcePasteText', function(u, v) { var cookie = tinymce.util.Cookie; ed.pasteAsPlainText = !ed.pasteAsPlainText; ed.controlManager.setActive('pastetext', ed.pasteAsPlainText); if ((ed.pasteAsPlainText) && (!cookie.get("tinymcePasteText"))) { if (getParam(ed, "paste_text_sticky")) { ed.windowManager.alert(ed.translate('paste.plaintext_mode_sticky')); } else { ed.windowManager.alert(ed.translate('paste.plaintext_mode')); } if (!getParam(ed, "paste_text_notifyalways")) { cookie.set("tinymcePasteText", "1", new Date(new Date().getFullYear() + 1, 12, 31)) } } }); } ed.addButton('pastetext', {title: 'paste.paste_text_desc', cmd: 'mcePasteText'}); ed.addButton('selectall', {title: 'paste.selectall_desc', cmd: 'selectall'}); // This function grabs the contents from the clipboard by adding a // hidden div and placing the caret inside it and after the browser paste // is done it grabs that contents and processes that function grabContent(e) { var n, or, rng, oldRng, sel = ed.selection, dom = ed.dom, body = ed.getBody(), posY, textContent; // Check if browser supports direct plaintext access if (e.clipboardData || dom.doc.dataTransfer) { textContent = (e.clipboardData || dom.doc.dataTransfer).getData('Text'); if (ed.pasteAsPlainText) { e.preventDefault(); process({content : dom.encode(textContent).replace(/\r?\n/g, '<br />')}); return; } } if (dom.get('_mcePaste')) return; // Create container to paste into n = dom.add(body, 'div', {id : '_mcePaste', 'class' : 'mcePaste', 'data-mce-bogus' : '1'}, '\uFEFF\uFEFF'); // If contentEditable mode we need to find out the position of the closest element if (body != ed.getDoc().body) posY = dom.getPos(ed.selection.getStart(), body).y; else posY = body.scrollTop + dom.getViewPort(ed.getWin()).y; // Styles needs to be applied after the element is added to the document since WebKit will otherwise remove all styles // If also needs to be in view on IE or the paste would fail dom.setStyles(n, { position : 'absolute', left : tinymce.isGecko ? -40 : 0, // Need to move it out of site on Gecko since it will othewise display a ghost resize rect for the div top : posY - 25, width : 1, height : 1, overflow : 'hidden' }); if (tinymce.isIE) { // Store away the old range oldRng = sel.getRng(); // Select the container rng = dom.doc.body.createTextRange(); rng.moveToElementText(n); rng.execCommand('Paste'); // Remove container dom.remove(n); // Check if the contents was changed, if it wasn't then clipboard extraction failed probably due // to IE security settings so we pass the junk though better than nothing right if (n.innerHTML === '\uFEFF\uFEFF') { ed.execCommand('mcePasteWord'); e.preventDefault(); return; } // Restore the old range and clear the contents before pasting sel.setRng(oldRng); sel.setContent(''); // For some odd reason we need to detach the the mceInsertContent call from the paste event // It's like IE has a reference to the parent element that you paste in and the selection gets messed up // when it tries to restore the selection setTimeout(function() { // Process contents process({content : n.innerHTML}); }, 0); // Block the real paste event return tinymce.dom.Event.cancel(e); } else { function block(e) { e.preventDefault(); }; // Block mousedown and click to prevent selection change dom.bind(ed.getDoc(), 'mousedown', block); dom.bind(ed.getDoc(), 'keydown', block); or = ed.selection.getRng(); // Move select contents inside DIV n = n.firstChild; rng = ed.getDoc().createRange(); rng.setStart(n, 0); rng.setEnd(n, 2); sel.setRng(rng); // Wait a while and grab the pasted contents window.setTimeout(function() { var h = '', nl; // Paste divs duplicated in paste divs seems to happen when you paste plain text so lets first look for that broken behavior in WebKit if (!dom.select('div.mcePaste > div.mcePaste').length) { nl = dom.select('div.mcePaste'); // WebKit will split the div into multiple ones so this will loop through then all and join them to get the whole HTML string each(nl, function(n) { var child = n.firstChild; // WebKit inserts a DIV container with lots of odd styles if (child && child.nodeName == 'DIV' && child.style.marginTop && child.style.backgroundColor) { dom.remove(child, 1); } // Remove apply style spans each(dom.select('span.Apple-style-span', n), function(n) { dom.remove(n, 1); }); // Remove bogus br elements each(dom.select('br[data-mce-bogus]', n), function(n) { dom.remove(n); }); // WebKit will make a copy of the DIV for each line of plain text pasted and insert them into the DIV if (n.parentNode.className != 'mcePaste') h += n.innerHTML; }); } else { // Found WebKit weirdness so force the content into paragraphs this seems to happen when you paste plain text from Nodepad etc // So this logic will replace double enter with paragraphs and single enter with br so it kind of looks the same h = '<p>' + dom.encode(textContent).replace(/\r?\n\r?\n/g, '</p><p>').replace(/\r?\n/g, '<br />') + '</p>'; } // Remove the nodes each(dom.select('div.mcePaste'), function(n) { dom.remove(n); }); // Restore the old selection if (or) sel.setRng(or); process({content : h}); // Unblock events ones we got the contents dom.unbind(ed.getDoc(), 'mousedown', block); dom.unbind(ed.getDoc(), 'keydown', block); }, 0); } } // Check if we should use the new auto process method if (getParam(ed, "paste_auto_cleanup_on_paste")) { // Is it's Opera or older FF use key handler if (tinymce.isOpera || /Firefox\/2/.test(navigator.userAgent)) { ed.onKeyDown.addToTop(function(ed, e) { if (((tinymce.isMac ? e.metaKey : e.ctrlKey) && e.keyCode == 86) || (e.shiftKey && e.keyCode == 45)) grabContent(e); }); } else { // Grab contents on paste event on Gecko and WebKit ed.onPaste.addToTop(function(ed, e) { return grabContent(e); }); } } ed.onInit.add(function() { ed.controlManager.setActive("pastetext", ed.pasteAsPlainText); // Block all drag/drop events if (getParam(ed, "paste_block_drop")) { ed.dom.bind(ed.getBody(), ['dragend', 'dragover', 'draggesture', 'dragdrop', 'drop', 'drag'], function(e) { e.preventDefault(); e.stopPropagation(); return false; }); } }); // Add legacy support t._legacySupport(); }, getInfo : function() { return { longname : 'Paste text/word', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/paste', version : tinymce.majorVersion + "." + tinymce.minorVersion }; }, _preProcess : function(pl, o) { var ed = this.editor, h = o.content, grep = tinymce.grep, explode = tinymce.explode, trim = tinymce.trim, len, stripClass; //console.log('Before preprocess:' + o.content); function process(items) { each(items, function(v) { // Remove or replace if (v.constructor == RegExp) h = h.replace(v, ''); else h = h.replace(v[0], v[1]); }); } if (ed.settings.paste_enable_default_filters == false) { return; } // IE9 adds BRs before/after block elements when contents is pasted from word or for example another browser if (tinymce.isIE && document.documentMode >= 9) { // IE9 adds BRs before/after block elements when contents is pasted from word or for example another browser process([[/(?:<br>&nbsp;[\s\r\n]+|<br>)*(<\/?(h[1-6r]|p|div|address|pre|form|table|tbody|thead|tfoot|th|tr|td|li|ol|ul|caption|blockquote|center|dl|dt|dd|dir|fieldset)[^>]*>)(?:<br>&nbsp;[\s\r\n]+|<br>)*/g, '$1']]); // IE9 also adds an extra BR element for each soft-linefeed and it also adds a BR for each word wrap break process([ [/<br><br>/g, '<BR><BR>'], // Replace multiple BR elements with uppercase BR to keep them intact [/<br>/g, ' '], // Replace single br elements with space since they are word wrap BR:s [/<BR><BR>/g, '<br>'] // Replace back the double brs but into a single BR ]); } // Detect Word content and process it more aggressive if (/class="?Mso|style="[^"]*\bmso-|w:WordDocument/i.test(h) || o.wordContent) { o.wordContent = true; // Mark the pasted contents as word specific content //console.log('Word contents detected.'); // Process away some basic content process([ /^\s*(&nbsp;)+/gi, // &nbsp; entities at the start of contents /(&nbsp;|<br[^>]*>)+\s*$/gi // &nbsp; entities at the end of contents ]); if (getParam(ed, "paste_convert_headers_to_strong")) { h = h.replace(/<p [^>]*class="?MsoHeading"?[^>]*>(.*?)<\/p>/gi, "<p><strong>$1</strong></p>"); } if (getParam(ed, "paste_convert_middot_lists")) { process([ [/<!--\[if !supportLists\]-->/gi, '$&__MCE_ITEM__'], // Convert supportLists to a list item marker [/(<span[^>]+(?:mso-list:|:\s*symbol)[^>]+>)/gi, '$1__MCE_ITEM__'], // Convert mso-list and symbol spans to item markers [/(<p[^>]+(?:MsoListParagraph)[^>]+>)/gi, '$1__MCE_ITEM__'] // Convert mso-list and symbol paragraphs to item markers (FF) ]); } process([ // Word comments like conditional comments etc /<!--[\s\S]+?-->/gi, // Remove comments, scripts (e.g., msoShowComment), XML tag, VML content, MS Office namespaced tags, and a few other tags /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|img|meta|link|style|\w:\w+)(?=[\s\/>]))[^>]*>/gi, // Convert <s> into <strike> for line-though [/<(\/?)s>/gi, "<$1strike>"], // Replace nsbp entites to char since it's easier to handle [/&nbsp;/gi, "\u00a0"] ]); // Remove bad attributes, with or without quotes, ensuring that attribute text is really inside a tag. // If JavaScript had a RegExp look-behind, we could have integrated this with the last process() array and got rid of the loop. But alas, it does not, so we cannot. do { len = h.length; h = h.replace(/(<[a-z][^>]*\s)(?:id|name|language|type|on\w+|\w+:\w+)=(?:"[^"]*"|\w+)\s?/gi, "$1"); } while (len != h.length); // Remove all spans if no styles is to be retained if (getParam(ed, "paste_retain_style_properties").replace(/^none$/i, "").length == 0) { h = h.replace(/<\/?span[^>]*>/gi, ""); } else { // We're keeping styles, so at least clean them up. // CSS Reference: http://msdn.microsoft.com/en-us/library/aa155477.aspx process([ // Convert <span style="mso-spacerun:yes">___</span> to string of alternating breaking/non-breaking spaces of same length [/<span\s+style\s*=\s*"\s*mso-spacerun\s*:\s*yes\s*;?\s*"\s*>([\s\u00a0]*)<\/span>/gi, function(str, spaces) { return (spaces.length > 0)? spaces.replace(/./, " ").slice(Math.floor(spaces.length/2)).split("").join("\u00a0") : ""; } ], // Examine all styles: delete junk, transform some, and keep the rest [/(<[a-z][^>]*)\sstyle="([^"]*)"/gi, function(str, tag, style) { var n = [], i = 0, s = explode(trim(style).replace(/&quot;/gi, "'"), ";"); // Examine each style definition within the tag's style attribute each(s, function(v) { var name, value, parts = explode(v, ":"); function ensureUnits(v) { return v + ((v !== "0") && (/\d$/.test(v)))? "px" : ""; } if (parts.length == 2) { name = parts[0].toLowerCase(); value = parts[1].toLowerCase(); // Translate certain MS Office styles into their CSS equivalents switch (name) { case "mso-padding-alt": case "mso-padding-top-alt": case "mso-padding-right-alt": case "mso-padding-bottom-alt": case "mso-padding-left-alt": case "mso-margin-alt": case "mso-margin-top-alt": case "mso-margin-right-alt": case "mso-margin-bottom-alt": case "mso-margin-left-alt": case "mso-table-layout-alt": case "mso-height": case "mso-width": case "mso-vertical-align-alt": n[i++] = name.replace(/^mso-|-alt$/g, "") + ":" + ensureUnits(value); return; case "horiz-align": n[i++] = "text-align:" + value; return; case "vert-align": n[i++] = "vertical-align:" + value; return; case "font-color": case "mso-foreground": n[i++] = "color:" + value; return; case "mso-background": case "mso-highlight": n[i++] = "background:" + value; return; case "mso-default-height": n[i++] = "min-height:" + ensureUnits(value); return; case "mso-default-width": n[i++] = "min-width:" + ensureUnits(value); return; case "mso-padding-between-alt": n[i++] = "border-collapse:separate;border-spacing:" + ensureUnits(value); return; case "text-line-through": if ((value == "single") || (value == "double")) { n[i++] = "text-decoration:line-through"; } return; case "mso-zero-height": if (value == "yes") { n[i++] = "display:none"; } return; } // Eliminate all MS Office style definitions that have no CSS equivalent by examining the first characters in the name if (/^(mso|column|font-emph|lang|layout|line-break|list-image|nav|panose|punct|row|ruby|sep|size|src|tab-|table-border|text-(?!align|decor|indent|trans)|top-bar|version|vnd|word-break)/.test(name)) { return; } // If it reached this point, it must be a valid CSS style n[i++] = name + ":" + parts[1]; // Lower-case name, but keep value case } }); // If style attribute contained any valid styles the re-write it; otherwise delete style attribute. if (i > 0) { return tag + ' style="' + n.join(';') + '"'; } else { return tag; } } ] ]); } } // Replace headers with <strong> if (getParam(ed, "paste_convert_headers_to_strong")) { process([ [/<h[1-6][^>]*>/gi, "<p><strong>"], [/<\/h[1-6][^>]*>/gi, "</strong></p>"] ]); } process([ // Copy paste from Java like Open Office will produce this junk on FF [/Version:[\d.]+\nStartHTML:\d+\nEndHTML:\d+\nStartFragment:\d+\nEndFragment:\d+/gi, ''] ]); // Class attribute options are: leave all as-is ("none"), remove all ("all"), or remove only those starting with mso ("mso"). // Note:- paste_strip_class_attributes: "none", verify_css_classes: true is also a good variation. stripClass = getParam(ed, "paste_strip_class_attributes"); if (stripClass !== "none") { function removeClasses(match, g1) { if (stripClass === "all") return ''; var cls = grep(explode(g1.replace(/^(["'])(.*)\1$/, "$2"), " "), function(v) { return (/^(?!mso)/i.test(v)); } ); return cls.length ? ' class="' + cls.join(" ") + '"' : ''; }; h = h.replace(/ class="([^"]+)"/gi, removeClasses); h = h.replace(/ class=([\-\w]+)/gi, removeClasses); } // Remove spans option if (getParam(ed, "paste_remove_spans")) { h = h.replace(/<\/?span[^>]*>/gi, ""); } //console.log('After preprocess:' + h); o.content = h; }, /** * Various post process items. */ _postProcess : function(pl, o) { var t = this, ed = t.editor, dom = ed.dom, styleProps; if (ed.settings.paste_enable_default_filters == false) { return; } if (o.wordContent) { // Remove named anchors or TOC links each(dom.select('a', o.node), function(a) { if (!a.href || a.href.indexOf('#_Toc') != -1) dom.remove(a, 1); }); if (getParam(ed, "paste_convert_middot_lists")) { t._convertLists(pl, o); } // Process styles styleProps = getParam(ed, "paste_retain_style_properties"); // retained properties // Process only if a string was specified and not equal to "all" or "*" if ((tinymce.is(styleProps, "string")) && (styleProps !== "all") && (styleProps !== "*")) { styleProps = tinymce.explode(styleProps.replace(/^none$/i, "")); // Retains some style properties each(dom.select('*', o.node), function(el) { var newStyle = {}, npc = 0, i, sp, sv; // Store a subset of the existing styles if (styleProps) { for (i = 0; i < styleProps.length; i++) { sp = styleProps[i]; sv = dom.getStyle(el, sp); if (sv) { newStyle[sp] = sv; npc++; } } } // Remove all of the existing styles dom.setAttrib(el, 'style', ''); if (styleProps && npc > 0) dom.setStyles(el, newStyle); // Add back the stored subset of styles else // Remove empty span tags that do not have class attributes if (el.nodeName == 'SPAN' && !el.className) dom.remove(el, true); }); } } // Remove all style information or only specifically on WebKit to avoid the style bug on that browser if (getParam(ed, "paste_remove_styles") || (getParam(ed, "paste_remove_styles_if_webkit") && tinymce.isWebKit)) { each(dom.select('*[style]', o.node), function(el) { el.removeAttribute('style'); el.removeAttribute('data-mce-style'); }); } else { if (tinymce.isWebKit) { // We need to compress the styles on WebKit since if you paste <img border="0" /> it will become <img border="0" style="... lots of junk ..." /> // Removing the mce_style that contains the real value will force the Serializer engine to compress the styles each(dom.select('*', o.node), function(el) { el.removeAttribute('data-mce-style'); }); } } }, /** * Converts the most common bullet and number formats in Office into a real semantic UL/LI list. */ _convertLists : function(pl, o) { var dom = pl.editor.dom, listElm, li, lastMargin = -1, margin, levels = [], lastType, html; // Convert middot lists into real semantic lists each(dom.select('p', o.node), function(p) { var sib, val = '', type, html, idx, parents; // Get text node value at beginning of paragraph for (sib = p.firstChild; sib && sib.nodeType == 3; sib = sib.nextSibling) val += sib.nodeValue; val = p.innerHTML.replace(/<\/?\w+[^>]*>/gi, '').replace(/&nbsp;/g, '\u00a0'); // Detect unordered lists look for bullets if (/^(__MCE_ITEM__)+[\u2022\u00b7\u00a7\u00d8o\u25CF]\s*\u00a0*/.test(val)) type = 'ul'; // Detect ordered lists 1., a. or ixv. if (/^__MCE_ITEM__\s*\w+\.\s*\u00a0+/.test(val)) type = 'ol'; // Check if node value matches the list pattern: o&nbsp;&nbsp; if (type) { margin = parseFloat(p.style.marginLeft || 0); if (margin > lastMargin) levels.push(margin); if (!listElm || type != lastType) { listElm = dom.create(type); dom.insertAfter(listElm, p); } else { // Nested list element if (margin > lastMargin) { listElm = li.appendChild(dom.create(type)); } else if (margin < lastMargin) { // Find parent level based on margin value idx = tinymce.inArray(levels, margin); parents = dom.getParents(listElm.parentNode, type); listElm = parents[parents.length - 1 - idx] || listElm; } } // Remove middot or number spans if they exists each(dom.select('span', p), function(span) { var html = span.innerHTML.replace(/<\/?\w+[^>]*>/gi, ''); // Remove span with the middot or the number if (type == 'ul' && /^__MCE_ITEM__[\u2022\u00b7\u00a7\u00d8o\u25CF]/.test(html)) dom.remove(span); else if (/^__MCE_ITEM__[\s\S]*\w+\.(&nbsp;|\u00a0)*\s*/.test(html)) dom.remove(span); }); html = p.innerHTML; // Remove middot/list items if (type == 'ul') html = p.innerHTML.replace(/__MCE_ITEM__/g, '').replace(/^[\u2022\u00b7\u00a7\u00d8o\u25CF]\s*(&nbsp;|\u00a0)+\s*/, ''); else html = p.innerHTML.replace(/__MCE_ITEM__/g, '').replace(/^\s*\w+\.(&nbsp;|\u00a0)+\s*/, ''); // Create li and add paragraph data into the new li li = listElm.appendChild(dom.create('li', 0, html)); dom.remove(p); lastMargin = margin; lastType = type; } else listElm = lastMargin = 0; // End list element }); // Remove any left over makers html = o.node.innerHTML; if (html.indexOf('__MCE_ITEM__') != -1) o.node.innerHTML = html.replace(/__MCE_ITEM__/g, ''); }, /** * Inserts the specified contents at the caret position. */ _insert : function(h, skip_undo) { var ed = this.editor, r = ed.selection.getRng(); // First delete the contents seems to work better on WebKit when the selection spans multiple list items or multiple table cells. if (!ed.selection.isCollapsed() && r.startContainer != r.endContainer) ed.getDoc().execCommand('Delete', false, null); ed.execCommand('mceInsertContent', false, h, {skip_undo : skip_undo}); }, /** * Instead of the old plain text method which tried to re-create a paste operation, the * new approach adds a plain text mode toggle switch that changes the behavior of paste. * This function is passed the same input that the regular paste plugin produces. * It performs additional scrubbing and produces (and inserts) the plain text. * This approach leverages all of the great existing functionality in the paste * plugin, and requires minimal changes to add the new functionality. * Speednet - June 2009 */ _insertPlainText : function(content) { var ed = this.editor, linebr = getParam(ed, "paste_text_linebreaktype"), rl = getParam(ed, "paste_text_replacements"), is = tinymce.is; function process(items) { each(items, function(v) { if (v.constructor == RegExp) content = content.replace(v, ""); else content = content.replace(v[0], v[1]); }); }; if ((typeof(content) === "string") && (content.length > 0)) { // If HTML content with line-breaking tags, then remove all cr/lf chars because only tags will break a line if (/<(?:p|br|h[1-6]|ul|ol|dl|table|t[rdh]|div|blockquote|fieldset|pre|address|center)[^>]*>/i.test(content)) { process([ /[\n\r]+/g ]); } else { // Otherwise just get rid of carriage returns (only need linefeeds) process([ /\r+/g ]); } process([ [/<\/(?:p|h[1-6]|ul|ol|dl|table|div|blockquote|fieldset|pre|address|center)>/gi, "\n\n"], // Block tags get a blank line after them [/<br[^>]*>|<\/tr>/gi, "\n"], // Single linebreak for <br /> tags and table rows [/<\/t[dh]>\s*<t[dh][^>]*>/gi, "\t"], // Table cells get tabs betweem them /<[a-z!\/?][^>]*>/gi, // Delete all remaining tags [/&nbsp;/gi, " "], // Convert non-break spaces to regular spaces (remember, *plain text*) [/(?:(?!\n)\s)*(\n+)(?:(?!\n)\s)*/gi, "$1"],// Cool little RegExp deletes whitespace around linebreak chars. [/\n{3,}/g, "\n\n"] // Max. 2 consecutive linebreaks ]); content = ed.dom.decode(tinymce.html.Entities.encodeRaw(content)); // Perform default or custom replacements if (is(rl, "array")) { process(rl); } else if (is(rl, "string")) { process(new RegExp(rl, "gi")); } // Treat paragraphs as specified in the config if (linebr == "none") { // Convert all line breaks to space process([ [/\n+/g, " "] ]); } else if (linebr == "br") { // Convert all line breaks to <br /> process([ [/\n/g, "<br />"] ]); } else if (linebr == "p") { // Convert all line breaks to <p>...</p> process([ [/\n+/g, "</p><p>"], [/^(.*<\/p>)(<p>)$/, '<p>$1'] ]); } else { // defaults to "combined" // Convert single line breaks to <br /> and double line breaks to <p>...</p> process([ [/\n\n/g, "</p><p>"], [/^(.*<\/p>)(<p>)$/, '<p>$1'], [/\n/g, "<br />"] ]); } ed.execCommand('mceInsertContent', false, content); } }, /** * This method will open the old style paste dialogs. Some users might want the old behavior but still use the new cleanup engine. */ _legacySupport : function() { var t = this, ed = t.editor; // Register command(s) for backwards compatibility ed.addCommand("mcePasteWord", function() { ed.windowManager.open({ file: t.url + "/pasteword.htm", width: parseInt(getParam(ed, "paste_dialog_width")), height: parseInt(getParam(ed, "paste_dialog_height")), inline: 1 }); }); if (getParam(ed, "paste_text_use_dialog")) { ed.addCommand("mcePasteText", function() { ed.windowManager.open({ file : t.url + "/pastetext.htm", width: parseInt(getParam(ed, "paste_dialog_width")), height: parseInt(getParam(ed, "paste_dialog_height")), inline : 1 }); }); } // Register button for backwards compatibility ed.addButton("pasteword", {title : "paste.paste_word_desc", cmd : "mcePasteWord"}); } }); // Register plugin tinymce.PluginManager.add("paste", tinymce.plugins.PastePlugin); })();
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
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { var DOM = tinymce.DOM, Event = tinymce.dom.Event, each = tinymce.each, explode = tinymce.explode; tinymce.create('tinymce.plugins.TabFocusPlugin', { init : function(ed, url) { function tabCancel(ed, e) { if (e.keyCode === 9) return Event.cancel(e); } function tabHandler(ed, e) { var x, i, f, el, v; function find(d) { el = DOM.select(':input:enabled,*[tabindex]'); function canSelectRecursive(e) { return e.nodeName==="BODY" || (e.type != 'hidden' && !(e.style.display == "none") && !(e.style.visibility == "hidden") && canSelectRecursive(e.parentNode)); } function canSelectInOldIe(el) { return el.attributes["tabIndex"].specified || el.nodeName == "INPUT" || el.nodeName == "TEXTAREA"; } function isOldIe() { return tinymce.isIE6 || tinymce.isIE7; } function canSelect(el) { return ((!isOldIe() || canSelectInOldIe(el))) && el.getAttribute("tabindex") != '-1' && canSelectRecursive(el); } each(el, function(e, i) { if (e.id == ed.id) { x = i; return false; } }); if (d > 0) { for (i = x + 1; i < el.length; i++) { if (canSelect(el[i])) return el[i]; } } else { for (i = x - 1; i >= 0; i--) { if (canSelect(el[i])) return el[i]; } } return null; } if (e.keyCode === 9) { v = explode(ed.getParam('tab_focus', ed.getParam('tabfocus_elements', ':prev,:next'))); if (v.length == 1) { v[1] = v[0]; v[0] = ':prev'; } // Find element to focus if (e.shiftKey) { if (v[0] == ':prev') el = find(-1); else el = DOM.get(v[0]); } else { if (v[1] == ':next') el = find(1); else el = DOM.get(v[1]); } if (el) { if (el.id && (ed = tinymce.get(el.id || el.name))) ed.focus(); else window.setTimeout(function() { if (!tinymce.isWebKit) window.focus(); el.focus(); }, 10); return Event.cancel(e); } } } ed.onKeyUp.add(tabCancel); if (tinymce.isGecko) { ed.onKeyPress.add(tabHandler); ed.onKeyDown.add(tabCancel); } else ed.onKeyDown.add(tabHandler); }, getInfo : function() { return { longname : 'Tabfocus', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/tabfocus', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); // Register plugin tinymce.PluginManager.add('tabfocus', tinymce.plugins.TabFocusPlugin); })();
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, closeOnClick; 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'); } }); ed.addCommand('WP_Medialib', function() { var id = ed.getParam('wp_fullscreen_editor_id') || ed.getParam('fullscreen_editor_id') || ed.id, link = tinymce.DOM.select('#wp-' + id + '-media-buttons a.thickbox'); if ( link && link[0] ) link = link[0]; else return; tb_show('', link.href); tinymce.DOM.setStyle( ['TB_overlay','TB_window','TB_load'], 'z-index', '999999' ); }); // 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 button ed.addButton('add_media', { title : 'wordpress.add_media', image : url + '/img/image.gif', cmd : 'WP_Medialib' }); // 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.select('a.thickbox').length ) ed.settings.theme_advanced_buttons1 += ',|,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) { var bodyClass = ed.getParam('body_class', ''), body = ed.getBody(); // add body classes if ( bodyClass ) bodyClass = bodyClass.split(' '); else bodyClass = []; if ( ed.getParam('directionality', '') == 'rtl' ) bodyClass.push('rtl'); if ( tinymce.isIE9 ) bodyClass.push('ie9'); else if ( tinymce.isIE8 ) bodyClass.push('ie8'); else if ( tinymce.isIE7 ) bodyClass.push('ie7'); if ( ed.id != 'wp_mce_fullscreen' && ed.id != 'mce_fullscreen' ) bodyClass.push('wp-editor'); else if ( ed.id == 'mce_fullscreen' ) bodyClass.push('mce-fullscreen'); tinymce.each( bodyClass, function(cls){ if ( cls ) ed.dom.addClass(body, cls); }); // 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); } }); // 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 ( ed.getParam('wpautop', true) && 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'), 'WP_Medialib'); 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(); }); closeOnClick = function(e){ var id; if ( e.target.id == 'mceModalBlocker' || e.target.className == 'ui-widget-overlay' ) { for ( id in ed.windowManager.windows ) { ed.windowManager.close(null, id); } } } // close popups when clicking on the background tinymce.dom.Event.remove(document.body, 'click', closeOnClick); tinymce.dom.Event.add(document.body, 'click', closeOnClick); }, 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')+'" />'; // 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
/** * 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.Directionality', { init : function(ed, url) { var t = this; t.editor = ed; ed.addCommand('mceDirectionLTR', function() { var e = ed.dom.getParent(ed.selection.getNode(), ed.dom.isBlock); if (e) { if (ed.dom.getAttrib(e, "dir") != "ltr") ed.dom.setAttrib(e, "dir", "ltr"); else ed.dom.setAttrib(e, "dir", ""); } ed.nodeChanged(); }); ed.addCommand('mceDirectionRTL', function() { var e = ed.dom.getParent(ed.selection.getNode(), ed.dom.isBlock); if (e) { if (ed.dom.getAttrib(e, "dir") != "rtl") ed.dom.setAttrib(e, "dir", "rtl"); else ed.dom.setAttrib(e, "dir", ""); } ed.nodeChanged(); }); ed.addButton('ltr', {title : 'directionality.ltr_desc', cmd : 'mceDirectionLTR'}); ed.addButton('rtl', {title : 'directionality.rtl_desc', cmd : 'mceDirectionRTL'}); ed.onNodeChange.add(t._nodeChange, t); }, getInfo : function() { return { longname : 'Directionality', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/directionality', version : tinymce.majorVersion + "." + tinymce.minorVersion }; }, // Private methods _nodeChange : function(ed, cm, n) { var dom = ed.dom, dir; n = dom.getParent(n, dom.isBlock); if (!n) { cm.setDisabled('ltr', 1); cm.setDisabled('rtl', 1); return; } dir = dom.getAttrib(n, 'dir'); cm.setActive('ltr', dir == "ltr"); cm.setDisabled('ltr', 0); cm.setActive('rtl', dir == "rtl"); cm.setDisabled('rtl', 0); } }); // Register plugin tinymce.PluginManager.add('directionality', tinymce.plugins.Directionality); })();
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, pos = tinyMCEPopup.dom.getPos(e.target); x = e.offsetX ? e.offsetX : (e.target ? e.clientX - pos.x : 0); y = e.offsetY ? e.offsetY : (e.target ? e.clientY - pos.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
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.setAttribute('name', name); 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
/** * 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("a.charmaplink", "charmapgroup"); settings ={ root: "charmapgroup", items: cells }; cells[0].tabindex=0; tinyMCEPopup.dom.addClass(cells[0], "mceFocus"); if (tinymce.isGecko) { cells[0].focus(); } else { setTimeout(function(){ cells[0].focus(); }, 100); } 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] + ' '+ tinyMCEPopup.editor.translate("advanced_dlg.charmap_usage")+'">' + 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(); 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
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', tinyMCEPopup.getParam('external_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 = typeof(l) === 'function' ? 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 }); el = ed.selection.getNode(); if (el && el.nodeName == 'IMG') { ed.dom.setAttribs(el, args); tinyMCEPopup.editor.execCommand('mceRepaint'); tinyMCEPopup.editor.focus(); } else { tinymce.each(args, function(value, name) { if (value === "") { delete args[name]; } }); ed.execCommand('mceInsertContent', false, tinyMCEPopup.editor.dom.createHTML('img', args), {skip_undo : 1}); ed.undoManager.add(); } tinyMCEPopup.close(); }, updateStyle : function() { var dom = tinyMCEPopup.dom, st, v, f = document.forms[0]; if (tinyMCEPopup.editor.settings.inline_styles) { st = tinyMCEPopup.dom.parseStyle(this.styleVal); // Handle align v = getSelectValue(f, 'align'); if (v) { if (v == 'left' || v == 'right') { st['float'] = v; delete st['vertical-align']; } else { st['vertical-align'] = v; delete st['float']; } } else { delete st['float']; delete st['vertical-align']; } // 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
/** * editor_template_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) { var DOM = tinymce.DOM, Event = tinymce.dom.Event, extend = tinymce.extend, each = tinymce.each, Cookie = tinymce.util.Cookie, lastExtID, explode = tinymce.explode; // Tell it to load theme specific language pack(s) tinymce.ThemeManager.requireLangPack('advanced'); tinymce.create('tinymce.themes.AdvancedTheme', { sizes : [8, 10, 12, 14, 18, 24, 36], // Control name lookup, format: title, command controls : { bold : ['bold_desc', 'Bold'], italic : ['italic_desc', 'Italic'], underline : ['underline_desc', 'Underline'], strikethrough : ['striketrough_desc', 'Strikethrough'], justifyleft : ['justifyleft_desc', 'JustifyLeft'], justifycenter : ['justifycenter_desc', 'JustifyCenter'], justifyright : ['justifyright_desc', 'JustifyRight'], justifyfull : ['justifyfull_desc', 'JustifyFull'], bullist : ['bullist_desc', 'InsertUnorderedList'], numlist : ['numlist_desc', 'InsertOrderedList'], outdent : ['outdent_desc', 'Outdent'], indent : ['indent_desc', 'Indent'], cut : ['cut_desc', 'Cut'], copy : ['copy_desc', 'Copy'], paste : ['paste_desc', 'Paste'], undo : ['undo_desc', 'Undo'], redo : ['redo_desc', 'Redo'], link : ['link_desc', 'mceLink'], unlink : ['unlink_desc', 'unlink'], image : ['image_desc', 'mceImage'], cleanup : ['cleanup_desc', 'mceCleanup'], help : ['help_desc', 'mceHelp'], code : ['code_desc', 'mceCodeEditor'], hr : ['hr_desc', 'InsertHorizontalRule'], removeformat : ['removeformat_desc', 'RemoveFormat'], sub : ['sub_desc', 'subscript'], sup : ['sup_desc', 'superscript'], forecolor : ['forecolor_desc', 'ForeColor'], forecolorpicker : ['forecolor_desc', 'mceForeColor'], backcolor : ['backcolor_desc', 'HiliteColor'], backcolorpicker : ['backcolor_desc', 'mceBackColor'], charmap : ['charmap_desc', 'mceCharMap'], visualaid : ['visualaid_desc', 'mceToggleVisualAid'], anchor : ['anchor_desc', 'mceInsertAnchor'], newdocument : ['newdocument_desc', 'mceNewDocument'], blockquote : ['blockquote_desc', 'mceBlockQuote'] }, stateControls : ['bold', 'italic', 'underline', 'strikethrough', 'bullist', 'numlist', 'justifyleft', 'justifycenter', 'justifyright', 'justifyfull', 'sub', 'sup', 'blockquote'], init : function(ed, url) { var t = this, s, v, o; t.editor = ed; t.url = url; t.onResolveName = new tinymce.util.Dispatcher(this); ed.forcedHighContrastMode = ed.settings.detect_highcontrast && t._isHighContrast(); ed.settings.skin = ed.forcedHighContrastMode ? 'highcontrast' : ed.settings.skin; // Default settings t.settings = s = extend({ theme_advanced_path : true, theme_advanced_toolbar_location : 'bottom', theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect", theme_advanced_buttons2 : "bullist,numlist,|,outdent,indent,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code", theme_advanced_buttons3 : "hr,removeformat,visualaid,|,sub,sup,|,charmap", theme_advanced_blockformats : "p,address,pre,h1,h2,h3,h4,h5,h6", theme_advanced_toolbar_align : "center", theme_advanced_fonts : "Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings,zapf dingbats", theme_advanced_more_colors : 1, theme_advanced_row_height : 23, theme_advanced_resize_horizontal : 1, theme_advanced_resizing_use_cookie : 1, theme_advanced_font_sizes : "1,2,3,4,5,6,7", theme_advanced_font_selector : "span", theme_advanced_show_current_color: 0, readonly : ed.settings.readonly }, ed.settings); // Setup default font_size_style_values if (!s.font_size_style_values) s.font_size_style_values = "8pt,10pt,12pt,14pt,18pt,24pt,36pt"; if (tinymce.is(s.theme_advanced_font_sizes, 'string')) { s.font_size_style_values = tinymce.explode(s.font_size_style_values); s.font_size_classes = tinymce.explode(s.font_size_classes || ''); // Parse string value o = {}; ed.settings.theme_advanced_font_sizes = s.theme_advanced_font_sizes; each(ed.getParam('theme_advanced_font_sizes', '', 'hash'), function(v, k) { var cl; if (k == v && v >= 1 && v <= 7) { k = v + ' (' + t.sizes[v - 1] + 'pt)'; cl = s.font_size_classes[v - 1]; v = s.font_size_style_values[v - 1] || (t.sizes[v - 1] + 'pt'); } if (/^\s*\./.test(v)) cl = v.replace(/\./g, ''); o[k] = cl ? {'class' : cl} : {fontSize : v}; }); s.theme_advanced_font_sizes = o; } if ((v = s.theme_advanced_path_location) && v != 'none') s.theme_advanced_statusbar_location = s.theme_advanced_path_location; if (s.theme_advanced_statusbar_location == 'none') s.theme_advanced_statusbar_location = 0; if (ed.settings.content_css !== false) ed.contentCSS.push(ed.baseURI.toAbsolute(url + "/skins/" + ed.settings.skin + "/content.css")); // Init editor ed.onInit.add(function() { if (!ed.settings.readonly) { ed.onNodeChange.add(t._nodeChanged, t); ed.onKeyUp.add(t._updateUndoStatus, t); ed.onMouseUp.add(t._updateUndoStatus, t); ed.dom.bind(ed.dom.getRoot(), 'dragend', function() { t._updateUndoStatus(ed); }); } }); ed.onSetProgressState.add(function(ed, b, ti) { var co, id = ed.id, tb; if (b) { t.progressTimer = setTimeout(function() { co = ed.getContainer(); co = co.insertBefore(DOM.create('DIV', {style : 'position:relative'}), co.firstChild); tb = DOM.get(ed.id + '_tbl'); DOM.add(co, 'div', {id : id + '_blocker', 'class' : 'mceBlocker', style : {width : tb.clientWidth + 2, height : tb.clientHeight + 2}}); DOM.add(co, 'div', {id : id + '_progress', 'class' : 'mceProgress', style : {left : tb.clientWidth / 2, top : tb.clientHeight / 2}}); }, ti || 0); } else { DOM.remove(id + '_blocker'); DOM.remove(id + '_progress'); clearTimeout(t.progressTimer); } }); DOM.loadCSS(s.editor_css ? ed.documentBaseURI.toAbsolute(s.editor_css) : url + "/skins/" + ed.settings.skin + "/ui.css"); if (s.skin_variant) DOM.loadCSS(url + "/skins/" + ed.settings.skin + "/ui_" + s.skin_variant + ".css"); }, _isHighContrast : function() { var actualColor, div = DOM.add(DOM.getRoot(), 'div', {'style': 'background-color: rgb(171,239,86);'}); actualColor = (DOM.getStyle(div, 'background-color', true) + '').toLowerCase().replace(/ /g, ''); DOM.remove(div); return actualColor != 'rgb(171,239,86)' && actualColor != '#abef56'; }, createControl : function(n, cf) { var cd, c; if (c = cf.createControl(n)) return c; switch (n) { case "styleselect": return this._createStyleSelect(); case "formatselect": return this._createBlockFormats(); case "fontselect": return this._createFontSelect(); case "fontsizeselect": return this._createFontSizeSelect(); case "forecolor": return this._createForeColorMenu(); case "backcolor": return this._createBackColorMenu(); } if ((cd = this.controls[n])) return cf.createButton(n, {title : "advanced." + cd[0], cmd : cd[1], ui : cd[2], value : cd[3]}); }, execCommand : function(cmd, ui, val) { var f = this['_' + cmd]; if (f) { f.call(this, ui, val); return true; } return false; }, _importClasses : function(e) { var ed = this.editor, ctrl = ed.controlManager.get('styleselect'); if (ctrl.getLength() == 0) { each(ed.dom.getClasses(), function(o, idx) { var name = 'style_' + idx; ed.formatter.register(name, { inline : 'span', attributes : {'class' : o['class']}, selector : '*' }); ctrl.add(o['class'], name); }); } }, _createStyleSelect : function(n) { var t = this, ed = t.editor, ctrlMan = ed.controlManager, ctrl; // Setup style select box ctrl = ctrlMan.createListBox('styleselect', { title : 'advanced.style_select', onselect : function(name) { var matches, formatNames = []; each(ctrl.items, function(item) { formatNames.push(item.value); }); ed.focus(); ed.undoManager.add(); // Toggle off the current format matches = ed.formatter.matchAll(formatNames); if (!name || matches[0] == name) { if (matches[0]) ed.formatter.remove(matches[0]); } else ed.formatter.apply(name); ed.undoManager.add(); ed.nodeChanged(); return false; // No auto select } }); // Handle specified format ed.onInit.add(function() { var counter = 0, formats = ed.getParam('style_formats'); if (formats) { each(formats, function(fmt) { var name, keys = 0; each(fmt, function() {keys++;}); if (keys > 1) { name = fmt.name = fmt.name || 'style_' + (counter++); ed.formatter.register(name, fmt); ctrl.add(fmt.title, name); } else ctrl.add(fmt.title); }); } else { each(ed.getParam('theme_advanced_styles', '', 'hash'), function(val, key) { var name; if (val) { name = 'style_' + (counter++); ed.formatter.register(name, { inline : 'span', classes : val, selector : '*' }); ctrl.add(t.editor.translate(key), name); } }); } }); // Auto import classes if the ctrl box is empty if (ctrl.getLength() == 0) { ctrl.onPostRender.add(function(ed, n) { if (!ctrl.NativeListBox) { Event.add(n.id + '_text', 'focus', t._importClasses, t); Event.add(n.id + '_text', 'mousedown', t._importClasses, t); Event.add(n.id + '_open', 'focus', t._importClasses, t); Event.add(n.id + '_open', 'mousedown', t._importClasses, t); } else Event.add(n.id, 'focus', t._importClasses, t); }); } return ctrl; }, _createFontSelect : function() { var c, t = this, ed = t.editor; c = ed.controlManager.createListBox('fontselect', { title : 'advanced.fontdefault', onselect : function(v) { var cur = c.items[c.selectedIndex]; if (!v && cur) { ed.execCommand('FontName', false, cur.value); return; } ed.execCommand('FontName', false, v); // Fake selection, execCommand will fire a nodeChange and update the selection c.select(function(sv) { return v == sv; }); if (cur && cur.value == v) { c.select(null); } return false; // No auto select } }); if (c) { each(ed.getParam('theme_advanced_fonts', t.settings.theme_advanced_fonts, 'hash'), function(v, k) { c.add(ed.translate(k), v, {style : v.indexOf('dings') == -1 ? 'font-family:' + v : ''}); }); } return c; }, _createFontSizeSelect : function() { var t = this, ed = t.editor, c, i = 0, cl = []; c = ed.controlManager.createListBox('fontsizeselect', {title : 'advanced.font_size', onselect : function(v) { var cur = c.items[c.selectedIndex]; if (!v && cur) { cur = cur.value; if (cur['class']) { ed.formatter.toggle('fontsize_class', {value : cur['class']}); ed.undoManager.add(); ed.nodeChanged(); } else { ed.execCommand('FontSize', false, cur.fontSize); } return; } if (v['class']) { ed.focus(); ed.undoManager.add(); ed.formatter.toggle('fontsize_class', {value : v['class']}); ed.undoManager.add(); ed.nodeChanged(); } else ed.execCommand('FontSize', false, v.fontSize); // Fake selection, execCommand will fire a nodeChange and update the selection c.select(function(sv) { return v == sv; }); if (cur && (cur.value.fontSize == v.fontSize || cur.value['class'] && cur.value['class'] == v['class'])) { c.select(null); } return false; // No auto select }}); if (c) { each(t.settings.theme_advanced_font_sizes, function(v, k) { var fz = v.fontSize; if (fz >= 1 && fz <= 7) fz = t.sizes[parseInt(fz) - 1] + 'pt'; c.add(k, v, {'style' : 'font-size:' + fz, 'class' : 'mceFontSize' + (i++) + (' ' + (v['class'] || ''))}); }); } return c; }, _createBlockFormats : function() { var c, fmts = { p : 'advanced.paragraph', address : 'advanced.address', pre : 'advanced.pre', h1 : 'advanced.h1', h2 : 'advanced.h2', h3 : 'advanced.h3', h4 : 'advanced.h4', h5 : 'advanced.h5', h6 : 'advanced.h6', div : 'advanced.div', blockquote : 'advanced.blockquote', code : 'advanced.code', dt : 'advanced.dt', dd : 'advanced.dd', samp : 'advanced.samp' }, t = this; c = t.editor.controlManager.createListBox('formatselect', {title : 'advanced.block', onselect : function(v) { t.editor.execCommand('FormatBlock', false, v); return false; }}); if (c) { each(t.editor.getParam('theme_advanced_blockformats', t.settings.theme_advanced_blockformats, 'hash'), function(v, k) { c.add(t.editor.translate(k != v ? k : fmts[v]), v, {'class' : 'mce_formatPreview mce_' + v}); }); } return c; }, _createForeColorMenu : function() { var c, t = this, s = t.settings, o = {}, v; if (s.theme_advanced_more_colors) { o.more_colors_func = function() { t._mceColorPicker(0, { color : c.value, func : function(co) { c.setColor(co); } }); }; } if (v = s.theme_advanced_text_colors) o.colors = v; if (s.theme_advanced_default_foreground_color) o.default_color = s.theme_advanced_default_foreground_color; o.title = 'advanced.forecolor_desc'; o.cmd = 'ForeColor'; o.scope = this; c = t.editor.controlManager.createColorSplitButton('forecolor', o); return c; }, _createBackColorMenu : function() { var c, t = this, s = t.settings, o = {}, v; if (s.theme_advanced_more_colors) { o.more_colors_func = function() { t._mceColorPicker(0, { color : c.value, func : function(co) { c.setColor(co); } }); }; } if (v = s.theme_advanced_background_colors) o.colors = v; if (s.theme_advanced_default_background_color) o.default_color = s.theme_advanced_default_background_color; o.title = 'advanced.backcolor_desc'; o.cmd = 'HiliteColor'; o.scope = this; c = t.editor.controlManager.createColorSplitButton('backcolor', o); return c; }, renderUI : function(o) { var n, ic, tb, t = this, ed = t.editor, s = t.settings, sc, p, nl; if (ed.settings) { ed.settings.aria_label = s.aria_label + ed.getLang('advanced.help_shortcut'); } // TODO: ACC Should have an aria-describedby attribute which is user-configurable to describe what this field is actually for. // Maybe actually inherit it from the original textara? n = p = DOM.create('span', {role : 'application', 'aria-labelledby' : ed.id + '_voice', id : ed.id + '_parent', 'class' : 'mceEditor ' + ed.settings.skin + 'Skin' + (s.skin_variant ? ' ' + ed.settings.skin + 'Skin' + t._ufirst(s.skin_variant) : '')}); DOM.add(n, 'span', {'class': 'mceVoiceLabel', 'style': 'display:none;', id: ed.id + '_voice'}, s.aria_label); if (!DOM.boxModel) n = DOM.add(n, 'div', {'class' : 'mceOldBoxModel'}); n = sc = DOM.add(n, 'table', {role : "presentation", id : ed.id + '_tbl', 'class' : 'mceLayout', cellSpacing : 0, cellPadding : 0}); n = tb = DOM.add(n, 'tbody'); switch ((s.theme_advanced_layout_manager || '').toLowerCase()) { case "rowlayout": ic = t._rowLayout(s, tb, o); break; case "customlayout": ic = ed.execCallback("theme_advanced_custom_layout", s, tb, o, p); break; default: ic = t._simpleLayout(s, tb, o, p); } n = o.targetNode; // Add classes to first and last TRs nl = sc.rows; DOM.addClass(nl[0], 'mceFirst'); DOM.addClass(nl[nl.length - 1], 'mceLast'); // Add classes to first and last TDs each(DOM.select('tr', tb), function(n) { DOM.addClass(n.firstChild, 'mceFirst'); DOM.addClass(n.childNodes[n.childNodes.length - 1], 'mceLast'); }); if (DOM.get(s.theme_advanced_toolbar_container)) DOM.get(s.theme_advanced_toolbar_container).appendChild(p); else DOM.insertAfter(p, n); Event.add(ed.id + '_path_row', 'click', function(e) { e = e.target; if (e.nodeName == 'A') { t._sel(e.className.replace(/^.*mcePath_([0-9]+).*$/, '$1')); return Event.cancel(e); } }); /* if (DOM.get(ed.id + '_path_row')) { Event.add(ed.id + '_tbl', 'mouseover', function(e) { var re; e = e.target; if (e.nodeName == 'SPAN' && DOM.hasClass(e.parentNode, 'mceButton')) { re = DOM.get(ed.id + '_path_row'); t.lastPath = re.innerHTML; DOM.setHTML(re, e.parentNode.title); } }); Event.add(ed.id + '_tbl', 'mouseout', function(e) { if (t.lastPath) { DOM.setHTML(ed.id + '_path_row', t.lastPath); t.lastPath = 0; } }); } */ if (!ed.getParam('accessibility_focus')) Event.add(DOM.add(p, 'a', {href : '#'}, '<!-- IE -->'), 'focus', function() {tinyMCE.get(ed.id).focus();}); if (s.theme_advanced_toolbar_location == 'external') o.deltaHeight = 0; t.deltaHeight = o.deltaHeight; o.targetNode = null; ed.onKeyDown.add(function(ed, evt) { var DOM_VK_F10 = 121, DOM_VK_F11 = 122; if (evt.altKey) { if (evt.keyCode === DOM_VK_F10) { // Make sure focus is given to toolbar in Safari. // We can't do this in IE as it prevents giving focus to toolbar when editor is in a frame if (tinymce.isWebKit) { window.focus(); } t.toolbarGroup.focus(); return Event.cancel(evt); } else if (evt.keyCode === DOM_VK_F11) { DOM.get(ed.id + '_path_row').focus(); return Event.cancel(evt); } } }); // alt+0 is the UK recommended shortcut for accessing the list of access controls. ed.addShortcut('alt+0', '', 'mceShortcuts', t); return { iframeContainer : ic, editorContainer : ed.id + '_parent', sizeContainer : sc, deltaHeight : o.deltaHeight }; }, getInfo : function() { return { longname : 'Advanced theme', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', version : tinymce.majorVersion + "." + tinymce.minorVersion } }, resizeBy : function(dw, dh) { var e = DOM.get(this.editor.id + '_ifr'); this.resizeTo(e.clientWidth + dw, e.clientHeight + dh); }, resizeTo : function(w, h, store) { var ed = this.editor, s = this.settings, e = DOM.get(ed.id + '_tbl'), ifr = DOM.get(ed.id + '_ifr'); // Boundery fix box w = Math.max(s.theme_advanced_resizing_min_width || 100, w); h = Math.max(s.theme_advanced_resizing_min_height || 100, h); w = Math.min(s.theme_advanced_resizing_max_width || 0xFFFF, w); h = Math.min(s.theme_advanced_resizing_max_height || 0xFFFF, h); // Resize iframe and container DOM.setStyle(e, 'height', ''); DOM.setStyle(ifr, 'height', h); if (s.theme_advanced_resize_horizontal) { DOM.setStyle(e, 'width', ''); DOM.setStyle(ifr, 'width', w); // Make sure that the size is never smaller than the over all ui if (w < e.clientWidth) { w = e.clientWidth; DOM.setStyle(ifr, 'width', e.clientWidth); } } // Store away the size if (store && s.theme_advanced_resizing_use_cookie) { Cookie.setHash("TinyMCE_" + ed.id + "_size", { cw : w, ch : h }); } }, destroy : function() { var id = this.editor.id; Event.clear(id + '_resize'); Event.clear(id + '_path_row'); Event.clear(id + '_external_close'); }, // Internal functions _simpleLayout : function(s, tb, o, p) { var t = this, ed = t.editor, lo = s.theme_advanced_toolbar_location, sl = s.theme_advanced_statusbar_location, n, ic, etb, c; if (s.readonly) { n = DOM.add(tb, 'tr'); n = ic = DOM.add(n, 'td', {'class' : 'mceIframeContainer'}); return ic; } // Create toolbar container at top if (lo == 'top') t._addToolbars(tb, o); // Create external toolbar if (lo == 'external') { n = c = DOM.create('div', {style : 'position:relative'}); n = DOM.add(n, 'div', {id : ed.id + '_external', 'class' : 'mceExternalToolbar'}); DOM.add(n, 'a', {id : ed.id + '_external_close', href : 'javascript:;', 'class' : 'mceExternalClose'}); n = DOM.add(n, 'table', {id : ed.id + '_tblext', cellSpacing : 0, cellPadding : 0}); etb = DOM.add(n, 'tbody'); if (p.firstChild.className == 'mceOldBoxModel') p.firstChild.appendChild(c); else p.insertBefore(c, p.firstChild); t._addToolbars(etb, o); ed.onMouseUp.add(function() { var e = DOM.get(ed.id + '_external'); DOM.show(e); DOM.hide(lastExtID); var f = Event.add(ed.id + '_external_close', 'click', function() { DOM.hide(ed.id + '_external'); Event.remove(ed.id + '_external_close', 'click', f); }); DOM.show(e); DOM.setStyle(e, 'top', 0 - DOM.getRect(ed.id + '_tblext').h - 1); // Fixes IE rendering bug DOM.hide(e); DOM.show(e); e.style.filter = ''; lastExtID = ed.id + '_external'; e = null; }); } if (sl == 'top') t._addStatusBar(tb, o); // Create iframe container if (!s.theme_advanced_toolbar_container) { n = DOM.add(tb, 'tr'); n = ic = DOM.add(n, 'td', {'class' : 'mceIframeContainer'}); } // Create toolbar container at bottom if (lo == 'bottom') t._addToolbars(tb, o); if (sl == 'bottom') t._addStatusBar(tb, o); return ic; }, _rowLayout : function(s, tb, o) { var t = this, ed = t.editor, dc, da, cf = ed.controlManager, n, ic, to, a; dc = s.theme_advanced_containers_default_class || ''; da = s.theme_advanced_containers_default_align || 'center'; each(explode(s.theme_advanced_containers || ''), function(c, i) { var v = s['theme_advanced_container_' + c] || ''; switch (c.toLowerCase()) { case 'mceeditor': n = DOM.add(tb, 'tr'); n = ic = DOM.add(n, 'td', {'class' : 'mceIframeContainer'}); break; case 'mceelementpath': t._addStatusBar(tb, o); break; default: a = (s['theme_advanced_container_' + c + '_align'] || da).toLowerCase(); a = 'mce' + t._ufirst(a); n = DOM.add(DOM.add(tb, 'tr'), 'td', { 'class' : 'mceToolbar ' + (s['theme_advanced_container_' + c + '_class'] || dc) + ' ' + a || da }); to = cf.createToolbar("toolbar" + i); t._addControls(v, to); DOM.setHTML(n, to.renderHTML()); o.deltaHeight -= s.theme_advanced_row_height; } }); return ic; }, _addControls : function(v, tb) { var t = this, s = t.settings, di, cf = t.editor.controlManager; if (s.theme_advanced_disable && !t._disabled) { di = {}; each(explode(s.theme_advanced_disable), function(v) { di[v] = 1; }); t._disabled = di; } else di = t._disabled; each(explode(v), function(n) { var c; if (di && di[n]) return; // Compatiblity with 2.x if (n == 'tablecontrols') { each(["table","|","row_props","cell_props","|","row_before","row_after","delete_row","|","col_before","col_after","delete_col","|","split_cells","merge_cells"], function(n) { n = t.createControl(n, cf); if (n) tb.add(n); }); return; } c = t.createControl(n, cf); if (c) tb.add(c); }); }, _addToolbars : function(c, o) { var t = this, i, tb, ed = t.editor, s = t.settings, v, cf = ed.controlManager, di, n, h = [], a, toolbarGroup; toolbarGroup = cf.createToolbarGroup('toolbargroup', { 'name': ed.getLang('advanced.toolbar'), 'tab_focus_toolbar':ed.getParam('theme_advanced_tab_focus_toolbar') }); t.toolbarGroup = toolbarGroup; a = s.theme_advanced_toolbar_align.toLowerCase(); a = 'mce' + t._ufirst(a); n = DOM.add(DOM.add(c, 'tr', {role: 'presentation'}), 'td', {'class' : 'mceToolbar ' + a, "role":"presentation"}); // Create toolbar and add the controls for (i=1; (v = s['theme_advanced_buttons' + i]); i++) { tb = cf.createToolbar("toolbar" + i, {'class' : 'mceToolbarRow' + i}); if (s['theme_advanced_buttons' + i + '_add']) v += ',' + s['theme_advanced_buttons' + i + '_add']; if (s['theme_advanced_buttons' + i + '_add_before']) v = s['theme_advanced_buttons' + i + '_add_before'] + ',' + v; t._addControls(v, tb); toolbarGroup.add(tb); o.deltaHeight -= s.theme_advanced_row_height; } h.push(toolbarGroup.renderHTML()); h.push(DOM.createHTML('a', {href : '#', accesskey : 'z', title : ed.getLang("advanced.toolbar_focus"), onfocus : 'tinyMCE.getInstanceById(\'' + ed.id + '\').focus();'}, '<!-- IE -->')); DOM.setHTML(n, h.join('')); }, _addStatusBar : function(tb, o) { var n, t = this, ed = t.editor, s = t.settings, r, mf, me, td; n = DOM.add(tb, 'tr'); n = td = DOM.add(n, 'td', {'class' : 'mceStatusbar'}); n = DOM.add(n, 'div', {id : ed.id + '_path_row', 'role': 'group', 'aria-labelledby': ed.id + '_path_voice'}); if (s.theme_advanced_path) { DOM.add(n, 'span', {id: ed.id + '_path_voice'}, ed.translate('advanced.path')); DOM.add(n, 'span', {}, ': '); } else { DOM.add(n, 'span', {}, '&#160;'); } if (s.theme_advanced_resizing) { DOM.add(td, 'a', {id : ed.id + '_resize', href : 'javascript:;', onclick : "return false;", 'class' : 'mceResize', tabIndex:"-1"}); if (s.theme_advanced_resizing_use_cookie) { ed.onPostRender.add(function() { var o = Cookie.getHash("TinyMCE_" + ed.id + "_size"), c = DOM.get(ed.id + '_tbl'); if (!o) return; t.resizeTo(o.cw, o.ch); }); } ed.onPostRender.add(function() { Event.add(ed.id + '_resize', 'click', function(e) { e.preventDefault(); }); Event.add(ed.id + '_resize', 'mousedown', function(e) { var mouseMoveHandler1, mouseMoveHandler2, mouseUpHandler1, mouseUpHandler2, startX, startY, startWidth, startHeight, width, height, ifrElm; function resizeOnMove(e) { e.preventDefault(); width = startWidth + (e.screenX - startX); height = startHeight + (e.screenY - startY); t.resizeTo(width, height); }; function endResize(e) { // Stop listening Event.remove(DOM.doc, 'mousemove', mouseMoveHandler1); Event.remove(ed.getDoc(), 'mousemove', mouseMoveHandler2); Event.remove(DOM.doc, 'mouseup', mouseUpHandler1); Event.remove(ed.getDoc(), 'mouseup', mouseUpHandler2); width = startWidth + (e.screenX - startX); height = startHeight + (e.screenY - startY); t.resizeTo(width, height, true); }; e.preventDefault(); // Get the current rect size startX = e.screenX; startY = e.screenY; ifrElm = DOM.get(t.editor.id + '_ifr'); startWidth = width = ifrElm.clientWidth; startHeight = height = ifrElm.clientHeight; // Register envent handlers mouseMoveHandler1 = Event.add(DOM.doc, 'mousemove', resizeOnMove); mouseMoveHandler2 = Event.add(ed.getDoc(), 'mousemove', resizeOnMove); mouseUpHandler1 = Event.add(DOM.doc, 'mouseup', endResize); mouseUpHandler2 = Event.add(ed.getDoc(), 'mouseup', endResize); }); }); } o.deltaHeight -= 21; n = tb = null; }, _updateUndoStatus : function(ed) { var cm = ed.controlManager, um = ed.undoManager; cm.setDisabled('undo', !um.hasUndo() && !um.typing); cm.setDisabled('redo', !um.hasRedo()); }, _nodeChanged : function(ed, cm, n, co, ob) { var t = this, p, de = 0, v, c, s = t.settings, cl, fz, fn, fc, bc, formatNames, matches; tinymce.each(t.stateControls, function(c) { cm.setActive(c, ed.queryCommandState(t.controls[c][1])); }); function getParent(name) { var i, parents = ob.parents, func = name; if (typeof(name) == 'string') { func = function(node) { return node.nodeName == name; }; } for (i = 0; i < parents.length; i++) { if (func(parents[i])) return parents[i]; } }; cm.setActive('visualaid', ed.hasVisual); t._updateUndoStatus(ed); cm.setDisabled('outdent', !ed.queryCommandState('Outdent')); p = getParent('A'); if (c = cm.get('link')) { if (!p || !p.name) { c.setDisabled(!p && co); c.setActive(!!p); } } if (c = cm.get('unlink')) { c.setDisabled(!p && co); c.setActive(!!p && !p.name); } if (c = cm.get('anchor')) { c.setActive(!co && !!p && p.name); } p = getParent('IMG'); if (c = cm.get('image')) c.setActive(!co && !!p && n.className.indexOf('mceItem') == -1); if (c = cm.get('styleselect')) { t._importClasses(); formatNames = []; each(c.items, function(item) { formatNames.push(item.value); }); matches = ed.formatter.matchAll(formatNames); c.select(matches[0]); } if (c = cm.get('formatselect')) { p = getParent(DOM.isBlock); if (p) c.select(p.nodeName.toLowerCase()); } // Find out current fontSize, fontFamily and fontClass getParent(function(n) { if (n.nodeName === 'SPAN') { if (!cl && n.className) cl = n.className; } if (ed.dom.is(n, s.theme_advanced_font_selector)) { if (!fz && n.style.fontSize) fz = n.style.fontSize; if (!fn && n.style.fontFamily) fn = n.style.fontFamily.replace(/[\"\']+/g, '').replace(/^([^,]+).*/, '$1').toLowerCase(); if (!fc && n.style.color) fc = n.style.color; if (!bc && n.style.backgroundColor) bc = n.style.backgroundColor; } return false; }); if (c = cm.get('fontselect')) { c.select(function(v) { return v.replace(/^([^,]+).*/, '$1').toLowerCase() == fn; }); } // Select font size if (c = cm.get('fontsizeselect')) { // Use computed style if (s.theme_advanced_runtime_fontsize && !fz && !cl) fz = ed.dom.getStyle(n, 'fontSize', true); c.select(function(v) { if (v.fontSize && v.fontSize === fz) return true; if (v['class'] && v['class'] === cl) return true; }); } if (s.theme_advanced_show_current_color) { function updateColor(controlId, color) { if (c = cm.get(controlId)) { if (!color) color = c.settings.default_color; if (color !== c.value) { c.displayColor(color); } } } updateColor('forecolor', fc); updateColor('backcolor', bc); } if (s.theme_advanced_show_current_color) { function updateColor(controlId, color) { if (c = cm.get(controlId)) { if (!color) color = c.settings.default_color; if (color !== c.value) { c.displayColor(color); } } }; updateColor('forecolor', fc); updateColor('backcolor', bc); } if (s.theme_advanced_path && s.theme_advanced_statusbar_location) { p = DOM.get(ed.id + '_path') || DOM.add(ed.id + '_path_row', 'span', {id : ed.id + '_path'}); if (t.statusKeyboardNavigation) { t.statusKeyboardNavigation.destroy(); t.statusKeyboardNavigation = null; } DOM.setHTML(p, ''); getParent(function(n) { var na = n.nodeName.toLowerCase(), u, pi, ti = ''; // Ignore non element and bogus/hidden elements if (n.nodeType != 1 || na === 'br' || n.getAttribute('data-mce-bogus') || DOM.hasClass(n, 'mceItemHidden') || DOM.hasClass(n, 'mceItemRemoved')) return; // Handle prefix if (tinymce.isIE && n.scopeName !== 'HTML') na = n.scopeName + ':' + na; // Remove internal prefix na = na.replace(/mce\:/g, ''); // Handle node name switch (na) { case 'b': na = 'strong'; break; case 'i': na = 'em'; break; case 'img': if (v = DOM.getAttrib(n, 'src')) ti += 'src: ' + v + ' '; break; case 'a': if (v = DOM.getAttrib(n, 'name')) { ti += 'name: ' + v + ' '; na += '#' + v; } if (v = DOM.getAttrib(n, 'href')) ti += 'href: ' + v + ' '; break; case 'font': if (v = DOM.getAttrib(n, 'face')) ti += 'font: ' + v + ' '; if (v = DOM.getAttrib(n, 'size')) ti += 'size: ' + v + ' '; if (v = DOM.getAttrib(n, 'color')) ti += 'color: ' + v + ' '; break; case 'span': if (v = DOM.getAttrib(n, 'style')) ti += 'style: ' + v + ' '; break; } if (v = DOM.getAttrib(n, 'id')) ti += 'id: ' + v + ' '; if (v = n.className) { v = v.replace(/\b\s*(webkit|mce|Apple-)\w+\s*\b/g, '') if (v) { ti += 'class: ' + v + ' '; if (DOM.isBlock(n) || na == 'img' || na == 'span') na += '.' + v; } } na = na.replace(/(html:)/g, ''); na = {name : na, node : n, title : ti}; t.onResolveName.dispatch(t, na); ti = na.title; na = na.name; //u = "javascript:tinymce.EditorManager.get('" + ed.id + "').theme._sel('" + (de++) + "');"; pi = DOM.create('a', {'href' : "javascript:;", role: 'button', onmousedown : "return false;", title : ti, 'class' : 'mcePath_' + (de++)}, na); if (p.hasChildNodes()) { p.insertBefore(DOM.create('span', {'aria-hidden': 'true'}, '\u00a0\u00bb '), p.firstChild); p.insertBefore(pi, p.firstChild); } else p.appendChild(pi); }, ed.getBody()); if (DOM.select('a', p).length > 0) { t.statusKeyboardNavigation = new tinymce.ui.KeyboardNavigation({ root: ed.id + "_path_row", items: DOM.select('a', p), excludeFromTabOrder: true, onCancel: function() { ed.focus(); } }, DOM); } } }, // Commands gets called by execCommand _sel : function(v) { this.editor.execCommand('mceSelectNodeDepth', false, v); }, _mceInsertAnchor : function(ui, v) { var ed = this.editor; ed.windowManager.open({ url : this.url + '/anchor.htm', width : 320 + parseInt(ed.getLang('advanced.anchor_delta_width', 0)), height : 90 + parseInt(ed.getLang('advanced.anchor_delta_height', 0)), inline : true }, { theme_url : this.url }); }, _mceCharMap : function() { var ed = this.editor; ed.windowManager.open({ url : this.url + '/charmap.htm', width : 550 + parseInt(ed.getLang('advanced.charmap_delta_width', 0)), height : 265 + parseInt(ed.getLang('advanced.charmap_delta_height', 0)), inline : true }, { theme_url : this.url }); }, _mceHelp : function() { var ed = this.editor; ed.windowManager.open({ url : this.url + '/about.htm', width : 480, height : 380, inline : true }, { theme_url : this.url }); }, _mceShortcuts : function() { var ed = this.editor; ed.windowManager.open({ url: this.url + '/shortcuts.htm', width: 480, height: 380, inline: true }, { theme_url: this.url }); }, _mceColorPicker : function(u, v) { var ed = this.editor; v = v || {}; ed.windowManager.open({ url : this.url + '/color_picker.htm', width : 375 + parseInt(ed.getLang('advanced.colorpicker_delta_width', 0)), height : 250 + parseInt(ed.getLang('advanced.colorpicker_delta_height', 0)), close_previous : false, inline : true }, { input_color : v.color, func : v.func, theme_url : this.url }); }, _mceCodeEditor : function(ui, val) { var ed = this.editor; ed.windowManager.open({ url : this.url + '/source_editor.htm', width : parseInt(ed.getParam("theme_advanced_source_editor_width", 720)), height : parseInt(ed.getParam("theme_advanced_source_editor_height", 580)), inline : true, resizable : true, maximizable : true }, { theme_url : this.url }); }, _mceImage : function(ui, val) { var ed = this.editor; // Internal image object like a flash placeholder if (ed.dom.getAttrib(ed.selection.getNode(), 'class').indexOf('mceItem') != -1) return; ed.windowManager.open({ url : this.url + '/image.htm', width : 355 + parseInt(ed.getLang('advanced.image_delta_width', 0)), height : 275 + parseInt(ed.getLang('advanced.image_delta_height', 0)), inline : true }, { theme_url : this.url }); }, _mceLink : function(ui, val) { var ed = this.editor; ed.windowManager.open({ url : this.url + '/link.htm', width : 310 + parseInt(ed.getLang('advanced.link_delta_width', 0)), height : 200 + parseInt(ed.getLang('advanced.link_delta_height', 0)), inline : true }, { theme_url : this.url }); }, _mceNewDocument : function() { var ed = this.editor; ed.windowManager.confirm('advanced.newdocument', function(s) { if (s) ed.execCommand('mceSetContent', false, ''); }); }, _mceForeColor : function() { var t = this; this._mceColorPicker(0, { color: t.fgColor, func : function(co) { t.fgColor = co; t.editor.execCommand('ForeColor', false, co); } }); }, _mceBackColor : function() { var t = this; this._mceColorPicker(0, { color: t.bgColor, func : function(co) { t.bgColor = co; t.editor.execCommand('HiliteColor', false, co); } }); }, _ufirst : function(s) { return s.substring(0, 1).toUpperCase() + s.substring(1); } }); tinymce.ThemeManager.add('advanced', tinymce.themes.AdvancedTheme); }(tinymce));
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 r6 // 2011.02.26 // jQuery 1.5.1+ * <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(at)cherne(dot)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]); }; // A private function for handling mouse 'hovering' var handleHover = function(e) { // copy objects to be passed into t (required for event object to be passed in IE) var ev = jQuery.extend({},e); var ob = this; // cancel hoverIntent timer if it exists if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); } // if e.type == "mouseenter" if (e.type == "mouseenter") { // set "previous" X and Y position based on initial entry point pX = ev.pageX; pY = ev.pageY; // update "current" X and Y position based on mousemove $(ob).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 == "mouseleave" } 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.bind('mouseenter',handleHover).bind('mouseleave',handleHover); }; })(jQuery);
JavaScript
if ( typeof wp === 'undefined' ) var wp = {}; (function( exports, $ ){ var api = wp.customize, Loader; $.extend( $.support, { history: !! ( window.history && history.pushState ), hashchange: ('onhashchange' in window) && (document.documentMode === undefined || document.documentMode > 7) }); Loader = $.extend( {}, api.Events, { initialize: function() { this.body = $( document.body ); // Ensure the loader is supported. // Check for settings, postMessage support, and whether we require CORS support. if ( ! Loader.settings || ! $.support.postMessage || ( ! $.support.cors && Loader.settings.isCrossDomain ) ) { return; } this.window = $( window ); this.element = $( '<div id="customize-container" />' ).appendTo( this.body ); this.bind( 'open', this.overlay.show ); this.bind( 'close', this.overlay.hide ); $('#wpbody').on( 'click', '.load-customize', function( event ) { event.preventDefault(); // Load the theme. Loader.open( $(this).attr('href') ); }); // Add navigation listeners. if ( $.support.history ) this.window.on( 'popstate', Loader.popstate ); if ( $.support.hashchange ) { this.window.on( 'hashchange', Loader.hashchange ); this.window.triggerHandler( 'hashchange' ); } }, popstate: function( e ) { var state = e.originalEvent.state; if ( state && state.customize ) Loader.open( state.customize ); else if ( Loader.active ) Loader.close(); }, hashchange: function( e ) { var hash = window.location.toString().split('#')[1]; if ( hash && 0 === hash.indexOf( 'wp_customize=on' ) ) Loader.open( Loader.settings.url + '?' + hash ); if ( ! hash && ! $.support.history ) Loader.close(); }, open: function( src ) { var hash; if ( this.active ) return; // Load the full page on mobile devices. if ( Loader.settings.browser.mobile ) return window.location = src; this.active = true; this.body.addClass('customize-loading'); this.iframe = $( '<iframe />', { src: src }).appendTo( this.element ); this.iframe.one( 'load', this.loaded ); // Create a postMessage connection with the iframe. this.messenger = new api.Messenger({ url: src, channel: 'loader', targetWindow: this.iframe[0].contentWindow }); // Wait for the connection from the iframe before sending any postMessage events. this.messenger.bind( 'ready', function() { Loader.messenger.send( 'back' ); }); this.messenger.bind( 'close', function() { if ( $.support.history ) history.back(); else if ( $.support.hashchange ) window.location.hash = ''; else Loader.close(); }); this.messenger.bind( 'activated', function( location ) { if ( location ) window.location = location; }); hash = src.split('?')[1]; // Ensure we don't call pushState if the user hit the forward button. if ( $.support.history && window.location.href !== src ) history.pushState( { customize: src }, '', src ); else if ( ! $.support.history && $.support.hashchange && hash ) window.location.hash = 'wp_customize=on&' + hash; this.trigger( 'open' ); }, opened: function() { Loader.body.addClass( 'customize-active full-overlay-active' ); }, close: function() { if ( ! this.active ) return; this.active = false; this.trigger( 'close' ); }, closed: function() { Loader.iframe.remove(); Loader.messenger.destroy(); Loader.iframe = null; Loader.messenger = null; Loader.body.removeClass( 'customize-active full-overlay-active' ).removeClass( 'customize-loading' ); }, loaded: function() { Loader.body.removeClass('customize-loading'); }, overlay: { show: function() { this.element.fadeIn( 200, Loader.opened ); }, hide: function() { this.element.fadeOut( 200, Loader.closed ); } } }); $( function() { Loader.settings = _wpCustomizeLoaderSettings; Loader.initialize(); }); // Expose the API to the world. api.Loader = Loader; })( wp, jQuery );
JavaScript
/*! * 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
/*! * 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
(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
(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
/****************************************************************************************************************************** * @ 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) { // WP: not needed with newer jQuery // event = jQuery.event.fix(event); // jQuery event normalization. var element = event.target; // @ TextNode -> nodeType == 3 // WP: not needed with newer jQuery // 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. // WP: needed for all browsers // 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
/* * 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
var autosave, autosaveLast = '', autosavePeriodical, autosaveOldMessage = '', autosaveDelayPreview = false, notSaved = true, blockSave = false, fullscreen, autosaveLockRelease = true; 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); autosaveLockRelease = false; }); $('input[type="submit"], a.submitdelete', '#submitpost').click(function(){ blockSave = true; window.onbeforeunload = null; $(':button, :submit', '#submitpost').each(function(){ var t = $(this); if ( t.hasClass('button-primary') ) t.addClass('button-primary-disabled'); else t.addClass('button-disabled'); }); if ( $(this).attr('id') == 'publish' ) $('#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; } }; $(window).unload( function(e) { if ( ! autosaveLockRelease ) return; // unload fires (twice) on removing the Thickbox iframe. Make sure we process only the main document unload. if ( e.target && e.target.nodeName != '#document' ) return; $.ajax({ type: 'POST', url: ajaxurl, async: false, data: { action: 'wp-remove-post-lock', _wpnonce: $('#_wpnonce').val(), post_ID: $('#post_ID').val(), active_post_lock: $('#active_post_lock').val() } }); } ); // preview $('#post-preview').click(function(){ if ( $('#auto_draft').val() == '1' && notSaved ) { autosaveDelayPreview = true; autosave(); return false; } doPreview(); return false; }); doPreview = function() { $('input#wp-preview').val('dopreview'); $('form#post').attr('target', 'wp-preview').submit().attr('target', ''); /* * Workaround for WebKit bug preventing a form submitting twice to the same action. * https://bugs.webkit.org/show_bug.cgi?id=28633 */ if ( $.browser.safari ) { $('form#post').attr('action', function(index, value) { return value + '?t=' + new Date().getTime(); }); } $('input#wp-preview').val(''); } // This code is meant to allow tabbing from Title to Post 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() {}; autosaveLockRelease = false; res = { errors: true }; } if ( sup['active-post-lock'] ) { jQuery('#active_post_lock').val( sup['active-post-lock'] ); } if ( sup['alert'] ) { jQuery('#autosave-alert').remove(); jQuery('#titlediv').after('<div id="autosave-alert" class="error below-h2"><p>' + sup['alert'] + '</p></div>'); } jQuery.each(sup, function(selector, value) { if ( selector.match(/^replace-/) ) { jQuery('#'+selector.replace('replace-', '')).val(value); } }); } // if no errors: add slug UI if ( !res.errors ) { postID = parseInt( res.responses[0].id, 10 ); if ( !isNaN(postID) && postID > 0 ) { autosave_update_slug(postID); } } } if ( message ) { // update autosave message jQuery('.autosave-message').html(message); } else if ( autosaveOldMessage && res ) { jQuery('.autosave-message').html( autosaveOldMessage ); } return res; } // called when autosaving pre-existing post function autosave_saved(response) { blockSave = false; autosave_parse_response(response); // parse the ajax response autosave_enable_buttons(); // re-enable disabled form buttons } // called when autosaving new post function autosave_saved_new(response) { blockSave = false; var res = autosave_parse_response(response), postID; if ( res && res.responses.length && !res.errors ) { // An ID is sent only for real auto-saves, not for autosave=0 "keepalive" saves postID = parseInt( res.responses[0].id, 10 ); if ( !isNaN(postID) && postID > 0 ) { notSaved = false; jQuery('#auto_draft').val('0'); // No longer an auto-draft } autosave_enable_buttons(); if ( autosaveDelayPreview ) { autosaveDelayPreview = false; doPreview(); } } else { autosave_enable_buttons(); // re-enable disabled form buttons } } function autosave_update_slug(post_id) { // create slug area only if not already there if ( 'undefined' != makeSlugeditClickable && jQuery.isFunction(makeSlugeditClickable) && !jQuery('#edit-slug-box > *').size() ) { jQuery.post( ajaxurl, { action: 'sample-permalink', post_id: post_id, new_title: fullscreen && fullscreen.settings.visible ? jQuery('#wp-fullscreen-title').val() : jQuery('#title').val(), samplepermalinknonce: jQuery('#samplepermalinknonce').val() }, function(data) { if ( data !== '-1' ) { jQuery('#edit-slug-box').html(data); makeSlugeditClickable(); } } ); } } function autosave_loading() { jQuery('.autosave-message').html(autosaveL10n.savingText); } function autosave_enable_buttons() { // delay that a bit to avoid some rare collisions while the DOM is being updated. setTimeout(function(){ jQuery(':button, :submit', '#submitpost').removeAttr('disabled'); jQuery('.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
/** * 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
var wpLink; (function($){ var inputs = {}, rivers = {}, ed, River, Query; wpLink = { timeToTriggerRiver: 150, minRiverAJAXDuration: 200, riverBottomThreshold: 5, keySensitivity: 100, lastSearch: '', textarea: '', init : function() { inputs.dialog = $('#wp-link'); inputs.submit = $('#wp-link-submit'); // URL inputs.url = $('#url-field'); inputs.nonce = $('#_ajax_linking_nonce'); // Secondary options inputs.title = $('#link-title-field'); // Advanced Options inputs.openInNewTab = $('#link-target-checkbox'); inputs.search = $('#search-field'); // Build Rivers rivers.search = new River( $('#search-results') ); rivers.recent = new River( $('#most-recent-results') ); rivers.elements = $('.query-results', inputs.dialog); // Bind event handlers inputs.dialog.keydown( wpLink.keydown ); inputs.dialog.keyup( wpLink.keyup ); inputs.submit.click( function(e){ e.preventDefault(); wpLink.update(); }); $('#wp-link-cancel').click( function(e){ e.preventDefault(); wpLink.close(); }); $('#internal-toggle').click( wpLink.toggleInternalLinking ); rivers.elements.bind('river-select', wpLink.updateFields ); inputs.search.keyup( wpLink.searchInternalLinks ); inputs.dialog.bind('wpdialogrefresh', wpLink.refresh); inputs.dialog.bind('wpdialogbeforeopen', wpLink.beforeOpen); inputs.dialog.bind('wpdialogclose', wpLink.onClose); }, beforeOpen : function() { wpLink.range = null; if ( ! wpLink.isMCE() && document.selection ) { wpLink.textarea.focus(); wpLink.range = document.selection.createRange(); } }, open : function() { if ( !wpActiveEditor ) return; this.textarea = $('#'+wpActiveEditor).get(0); // Initialize the dialog if necessary (html mode). if ( ! inputs.dialog.data('wpdialog') ) { inputs.dialog.wpdialog({ title: wpLinkL10n.title, width: 480, height: 'auto', modal: true, dialogClass: 'wp-dialog', zIndex: 300000 }); } inputs.dialog.wpdialog('open'); }, isMCE : function() { return tinyMCEPopup && ( ed = tinyMCEPopup.editor ) && ! ed.isHidden(); }, refresh : function() { // Refresh rivers (clear links, check visibility) rivers.search.refresh(); rivers.recent.refresh(); if ( wpLink.isMCE() ) wpLink.mceRefresh(); else wpLink.setDefaultValues(); // Focus the URL field and highlight its contents. // If this is moved above the selection changes, // IE will show a flashing cursor over the dialog. inputs.url.focus()[0].select(); // Load the most recent results if this is the first time opening the panel. if ( ! rivers.recent.ul.children().length ) rivers.recent.ajax(); }, mceRefresh : function() { var e; ed = tinyMCEPopup.editor; tinyMCEPopup.restoreSelection(); // If link exists, select proper values. if ( e = ed.dom.getParent(ed.selection.getNode(), 'A') ) { // Set URL and description. inputs.url.val( ed.dom.getAttrib(e, 'href') ); inputs.title.val( ed.dom.getAttrib(e, 'title') ); // Set open in new tab. if ( "_blank" == ed.dom.getAttrib(e, 'target') ) inputs.openInNewTab.prop('checked', true); // Update save prompt. inputs.submit.val( wpLinkL10n.update ); // If there's no link, set the default values. } else { wpLink.setDefaultValues(); } tinyMCEPopup.storeSelection(); }, close : function() { if ( wpLink.isMCE() ) tinyMCEPopup.close(); else inputs.dialog.wpdialog('close'); }, onClose: function() { if ( ! wpLink.isMCE() ) { wpLink.textarea.focus(); if ( wpLink.range ) { wpLink.range.moveToBookmark( wpLink.range.getBookmark() ); wpLink.range.select(); } } }, getAttrs : function() { return { href : inputs.url.val(), title : inputs.title.val(), target : inputs.openInNewTab.prop('checked') ? '_blank' : '' }; }, update : function() { if ( wpLink.isMCE() ) wpLink.mceUpdate(); else wpLink.htmlUpdate(); }, htmlUpdate : function() { var attrs, html, begin, end, cursor, textarea = wpLink.textarea; if ( ! textarea ) return; attrs = wpLink.getAttrs(); // If there's no href, return. if ( ! attrs.href || attrs.href == 'http://' ) return; // Build HTML html = '<a href="' + attrs.href + '"'; if ( attrs.title ) html += ' title="' + attrs.title + '"'; if ( attrs.target ) html += ' target="' + attrs.target + '"'; html += '>'; // Insert HTML if ( document.selection && wpLink.range ) { // IE // Note: If no text is selected, IE will not place the cursor // inside the closing tag. textarea.focus(); wpLink.range.text = html + wpLink.range.text + '</a>'; wpLink.range.moveToBookmark( wpLink.range.getBookmark() ); wpLink.range.select(); wpLink.range = null; } else if ( typeof textarea.selectionStart !== 'undefined' ) { // W3C begin = textarea.selectionStart; end = textarea.selectionEnd; selection = textarea.value.substring( begin, end ); html = html + selection + '</a>'; cursor = begin + html.length; // If no next is selected, place the cursor inside the closing tag. if ( begin == end ) cursor -= '</a>'.length; textarea.value = textarea.value.substring( 0, begin ) + html + textarea.value.substring( end, textarea.value.length ); // Update cursor position textarea.selectionStart = textarea.selectionEnd = cursor; } wpLink.close(); textarea.focus(); }, mceUpdate : function() { var ed = tinyMCEPopup.editor, attrs = wpLink.getAttrs(), e, b; tinyMCEPopup.restoreSelection(); e = ed.dom.getParent(ed.selection.getNode(), 'A'); // If the values are empty, unlink and return if ( ! attrs.href || attrs.href == 'http://' ) { if ( e ) { tinyMCEPopup.execCommand("mceBeginUndoLevel"); b = ed.selection.getBookmark(); ed.dom.remove(e, 1); ed.selection.moveToBookmark(b); tinyMCEPopup.execCommand("mceEndUndoLevel"); wpLink.close(); } return; } tinyMCEPopup.execCommand("mceBeginUndoLevel"); if (e == null) { ed.getDoc().execCommand("unlink", false, null); tinyMCEPopup.execCommand("mceInsertLink", false, "#mce_temp_url#", {skip_undo : 1}); tinymce.each(ed.dom.select("a"), function(n) { if (ed.dom.getAttrib(n, 'href') == '#mce_temp_url#') { e = n; ed.dom.setAttribs(e, attrs); } }); // Sometimes WebKit lets a user create a link where // they shouldn't be able to. In this case, CreateLink // injects "#mce_temp_url#" into their content. Fix it. if ( $(e).text() == '#mce_temp_url#' ) { ed.dom.remove(e); e = null; } } else { ed.dom.setAttribs(e, attrs); } // Don't move caret if selection was image if ( e && (e.childNodes.length != 1 || e.firstChild.nodeName != 'IMG') ) { ed.focus(); ed.selection.select(e); ed.selection.collapse(0); tinyMCEPopup.storeSelection(); } tinyMCEPopup.execCommand("mceEndUndoLevel"); wpLink.close(); }, updateFields : function( e, li, originalEvent ) { inputs.url.val( li.children('.item-permalink').val() ); inputs.title.val( li.hasClass('no-title') ? '' : li.children('.item-title').text() ); if ( originalEvent && originalEvent.type == "click" ) inputs.url.focus(); }, setDefaultValues : function() { // Set URL and description to defaults. // Leave the new tab setting as-is. inputs.url.val('http://'); inputs.title.val(''); // Update save prompt. inputs.submit.val( wpLinkL10n.save ); }, searchInternalLinks : function() { var t = $(this), waiting, search = t.val(); if ( search.length > 2 ) { rivers.recent.hide(); rivers.search.show(); // Don't search if the keypress didn't change the title. if ( wpLink.lastSearch == search ) return; wpLink.lastSearch = search; waiting = t.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' : inputs.nonce.val() }; if ( this.search ) query.search = this.search; this.querying = true; $.post( ajaxurl, query, function(r) { self.page++; self.querying = false; self.allLoaded = !r; callback( r, query ); }, "json" ); } }); $(document).ready( wpLink.init ); })(jQuery);
JavaScript
(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
/** * Pointer jQuery widget. */ (function($){ var identifier = 0, zindex = 9999; $.widget("wp.pointer", { options: { pointerClass: 'wp-pointer', pointerWidth: 320, content: function( respond, event, t ) { return $(this).text(); }, buttons: function( event, t ) { var close = ( wpPointerL10n ) ? wpPointerL10n.dismiss : 'Dismiss', button = $('<a class="close" href="#">' + close + '</a>'); return button.bind( 'click.pointer', function(e) { e.preventDefault(); t.element.pointer('close'); }); }, position: 'top', show: function( event, t ) { t.pointer.show(); t.opened(); }, hide: function( event, t ) { t.pointer.hide(); t.closed(); }, document: document }, _create: function() { var positioning, family; this.content = $('<div class="wp-pointer-content"></div>'); this.arrow = $('<div class="wp-pointer-arrow"><div class="wp-pointer-arrow-inner"></div></div>'); family = this.element.parents().add( this.element ); positioning = 'absolute'; if ( family.filter(function(){ return 'fixed' === $(this).css('position'); }).length ) positioning = 'fixed'; this.pointer = $('<div />') .append( this.content ) .append( this.arrow ) .attr('id', 'wp-pointer-' + identifier++) .addClass( this.options.pointerClass ) .css({'position': positioning, 'width': this.options.pointerWidth+'px', 'display': 'none'}) .appendTo( this.options.document.body ); }, _setOption: function( key, value ) { var o = this.options, tip = this.pointer; // Handle document transfer if ( key === "document" && value !== o.document ) { tip.detach().appendTo( value.body ); // Handle class change } else if ( key === "pointerClass" ) { tip.removeClass( o.pointerClass ).addClass( value ); } // Call super method. $.Widget.prototype._setOption.apply( this, arguments ); // Reposition automatically if ( key === "position" ) { this.reposition(); // Update content automatically if pointer is open } else if ( key === "content" && this.active ) { this.update(); } }, destroy: function() { this.pointer.remove(); $.Widget.prototype.destroy.call( this ); }, widget: function() { return this.pointer; }, update: function( event ) { var self = this, o = this.options, dfd = $.Deferred(), content; if ( o.disabled ) return; dfd.done( function( content ) { self._update( event, content ); }) // Either o.content is a string... if ( typeof o.content === 'string' ) { content = o.content; // ...or o.content is a callback. } else { content = o.content.call( this.element[0], dfd.resolve, event, this._handoff() ); } // If content is set, then complete the update. if ( content ) dfd.resolve( content ); return dfd.promise(); }, /** * Update is separated into two functions to allow events to defer * updating the pointer (e.g. fetch content with ajax, etc). */ _update: function( event, content ) { var buttons, o = this.options; if ( ! content ) return; this.pointer.stop(); // Kill any animations on the pointer. this.content.html( content ); buttons = o.buttons.call( this.element[0], event, this._handoff() ); if ( buttons ) { buttons.wrap('<div class="wp-pointer-buttons" />').parent().appendTo( this.content ); } this.reposition(); }, reposition: function() { var position; if ( this.options.disabled ) return; position = this._processPosition( this.options.position ); // Reposition pointer. this.pointer.css({ top: 0, left: 0, zIndex: zindex++ // Increment the z-index so that it shows above other opened pointers. }).show().position($.extend({ of: this.element, collision: 'fit none' }, position )); // the object comes before this.options.position so the user can override position.of. this.repoint(); }, repoint: function() { var o = this.options, edge; if ( o.disabled ) return; edge = ( typeof o.position == 'string' ) ? o.position : o.position.edge; // Remove arrow classes. this.pointer[0].className = this.pointer[0].className.replace( /wp-pointer-[^\s'"]*/, '' ); // Add arrow class. this.pointer.addClass( 'wp-pointer-' + edge ); }, _processPosition: function( position ) { var opposite = { top: 'bottom', bottom: 'top', left: 'right', right: 'left' }, result; // If the position object is a string, it is shorthand for position.edge. if ( typeof position == 'string' ) { result = { edge: position + '' }; } else { result = $.extend( {}, position ); } if ( ! result.edge ) return result; if ( result.edge == 'top' || result.edge == 'bottom' ) { result.align = result.align || 'left'; result.at = result.at || result.align + ' ' + opposite[ result.edge ]; result.my = result.my || result.align + ' ' + result.edge; } else { result.align = result.align || 'top'; result.at = result.at || opposite[ result.edge ] + ' ' + result.align; result.my = result.my || result.edge + ' ' + result.align; } return result; }, open: function( event ) { var self = this, o = this.options; if ( this.active || o.disabled || this.element.is(':hidden') ) return; this.update().done( function() { self._open( event ); }); }, _open: function( event ) { var self = this, o = this.options; if ( this.active || o.disabled || this.element.is(':hidden') ) return; this.active = true; this._trigger( "open", event, this._handoff() ); this._trigger( "show", event, this._handoff({ opened: function() { self._trigger( "opened", event, self._handoff() ); } })); }, close: function( event ) { if ( !this.active || this.options.disabled ) return; var self = this; this.active = false; this._trigger( "close", event, this._handoff() ); this._trigger( "hide", event, this._handoff({ closed: function() { self._trigger( "closed", event, self._handoff() ); } })); }, sendToTop: function( event ) { if ( this.active ) this.pointer.css( 'z-index', zindex++ ); }, toggle: function( event ) { if ( this.pointer.is(':hidden') ) this.open( event ); else this.close( event ); }, _handoff: function( extend ) { return $.extend({ pointer: this.pointer, element: this.element }, extend); } }); })(jQuery);
JavaScript
(function( exports, $ ){ var api = wp.customize, debounce; debounce = function( fn, delay, context ) { var timeout; return function() { var args = arguments; context = context || this; clearTimeout( timeout ); timeout = setTimeout( function() { timeout = null; fn.apply( context, args ); }, delay ); }; }; api.Preview = api.Messenger.extend({ /** * Requires params: * - url - the URL of preview frame */ initialize: function( params, options ) { var self = this; api.Messenger.prototype.initialize.call( this, params, options ); this.body = $( document.body ); this.body.on( 'click.preview', 'a', function( event ) { event.preventDefault(); self.send( 'scroll', 0 ); self.send( 'url', $(this).prop('href') ); }); // You cannot submit forms. // @todo: Allow form submissions by mixing $_POST data with the customize setting $_POST data. this.body.on( 'submit.preview', 'form', function( event ) { event.preventDefault(); }); this.window = $( window ); this.window.on( 'scroll.preview', debounce( function() { self.send( 'scroll', self.window.scrollTop() ); }, 200 )); this.bind( 'scroll', function( distance ) { self.window.scrollTop( distance ); }); } }); $( function() { api.settings = window._wpCustomizeSettings; if ( ! api.settings ) return; var preview, bg; preview = new api.Preview({ url: window.location.href, channel: api.settings.channel }); preview.bind( 'settings', function( values ) { $.each( values, function( id, value ) { if ( api.has( id ) ) api( id ).set( value ); else api.create( id, value ); }); }); preview.trigger( 'settings', api.settings.values ); preview.bind( 'setting', function( args ) { var value; args = args.slice(); if ( value = api( args.shift() ) ) value.set.apply( value, args ); }); preview.bind( 'sync', function( events ) { $.each( events, function( event, args ) { preview.trigger( event, args ); }); preview.send( 'synced' ); }); preview.bind( 'active', function() { if ( api.settings.nonce ) preview.send( 'nonce', api.settings.nonce ); }); preview.send( 'ready' ); /* Custom Backgrounds */ bg = $.map(['color', 'image', 'position_x', 'repeat', 'attachment'], function( prop ) { return 'background_' + prop; }); api.when.apply( api, bg ).done( function( color, image, position_x, repeat, attachment ) { var body = $(document.body), head = $('head'), style = $('#custom-background-css'), update; // If custom backgrounds are active and we can't find the // default output, bail. if ( body.hasClass('custom-background') && ! style.length ) return; update = function() { var css = ''; // The body will support custom backgrounds if either // the color or image are set. // // See get_body_class() in /wp-includes/post-template.php body.toggleClass( 'custom-background', !! ( color() || image() ) ); if ( color() ) css += 'background-color: ' + color() + ';'; if ( image() ) { css += 'background-image: url("' + image() + '");'; css += 'background-position: top ' + position_x() + ';'; css += 'background-repeat: ' + repeat() + ';'; css += 'background-position: top ' + attachment() + ';'; } // Refresh the stylesheet by removing and recreating it. style.remove(); style = $('<style type="text/css" id="custom-background-css">body.custom-background { ' + css + ' }</style>').appendTo( head ); }; $.each( arguments, function() { this.bind( update ); }); }); }); })( wp, jQuery );
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({'visibility':'visible'}); //for safari using css instead of show }; imgPreloader.src = url; }else{//code to show html var queryString = url.replace(/^[^\?]+\??/,''); var params = tb_parseQuery( queryString ); TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no 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("visibility") != "visible"){ 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").bind('tb_unload', function () { jQuery('#' + params['inlineId']).append( jQuery("#TB_ajaxContent").children() ); // move elements back when you're finished }); tb_position(); jQuery("#TB_load").remove(); jQuery("#TB_window").css({'visibility':'visible'}); }else if(url.indexOf('TB_iframe') != -1){ tb_position(); if(jQuery.browser.safari){//safari needs help because it will not fire iframe onload jQuery("#TB_load").remove(); jQuery("#TB_window").css({'visibility':'visible'}); } }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({'visibility':'visible'}); }); } } 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({'visibility':'visible'}); } function tb_remove() { jQuery("#TB_imageOff").unbind("click"); jQuery("#TB_closeWindowButton").unbind("click"); jQuery("#TB_window").fadeOut("fast",function(){jQuery('#TB_window,#TB_overlay,#TB_HideSelect').trigger("tb_unload").unbind().remove();}); jQuery("#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
(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
/** * SyntaxHighlighter * http://alexgorbatchev.com/SyntaxHighlighter * * SyntaxHighlighter is donationware. If you are using it, please donate. * http://alexgorbatchev.com/SyntaxHighlighter/donate.html * * @version * 3.0.83 (July 02 2010) * * @copyright * Copyright (C) 2004-2010 Alex Gorbatchev. * * @license * Dual licensed under the MIT and GPL licenses. */ eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('(2(){1 h=5;h.I=2(){2 n(c,a){4(1 d=0;d<c.9;d++)i[c[d]]=a}2 o(c){1 a=r.H("J"),d=3;a.K=c;a.M="L/t";a.G="t";a.u=a.v=2(){6(!d&&(!8.7||8.7=="F"||8.7=="z")){d=q;e[c]=q;a:{4(1 p y e)6(e[p]==3)B a;j&&5.C(k)}a.u=a.v=x;a.D.O(a)}};r.N.R(a)}1 f=Q,l=h.P(),i={},e={},j=3,k=x,b;5.T=2(c){k=c;j=q};4(b=0;b<f.9;b++){1 m=f[b].w?f[b]:f[b].S(/\\s+/),g=m.w();n(m,g)}4(b=0;b<l.9;b++)6(g=i[l[b].E.A]){e[g]=3;o(g)}}})();',56,56,'|var|function|false|for|SyntaxHighlighter|if|readyState|this|length|||||||||||||||||true|document||javascript|onload|onreadystatechange|pop|null|in|complete|brush|break|highlight|parentNode|params|loaded|language|createElement|autoloader|script|src|text|type|body|removeChild|findElements|arguments|appendChild|split|all'.split('|'),0,{}))
JavaScript
/* * SyntaxHighlighter shortcode plugin * by Andrew Ozz of Automattic */ // Avoid JS errors if ( typeof syntaxHLcodes == 'undefined' ) { var syntaxHLcodes = 'sourcecode'; } (function() { tinymce.create('tinymce.plugins.SyntaxHighlighterPlugin', { init : function(ed, url) { var t = this; ed.onBeforeSetContent.add(function(ed, o) { o.content = t._htmlToVisual(o.content); }); ed.onPostProcess.add(function(ed, o) { if ( o.save ) { o.content = t._visualToHtml(o.content); } }); }, getInfo : function() { return { longname : 'SyntaxHighlighter Assister', author : 'Automattic', authorurl : 'http://wordpress.com/', infourl : 'http://wordpress.org/extend/plugins/syntaxhighlighter/', version : tinymce.majorVersion + "." + tinymce.minorVersion }; }, // Private methods _visualToHtml : function(content) { content = tinymce.trim(content); // 2 <br> get converted to \n\n and are needed to preserve the next <p> content = content.replace(new RegExp('(<pre>\\s*)?(\\[(' + syntaxHLcodes + ')[^\\]]*\\][\\s\\S]*?\\[\\/\\3\\])(\\s*<\\/pre>)?', 'gi'), function(a) { a = a.replace( /<br \/>([\t ])/g, '<br \/><%%KEEPWHITESPACE%%>$1' ); return a + '<br /><br />'; }); content = content.replace(/<\/pre>(<br \/><br \/>)?<pre>/gi, '\n'); return content; }, _htmlToVisual : function(content) { content = tinymce.trim(content); content = content.replace(new RegExp('(<p>\\s*)?(<pre>\\s*)?(\\[(' + syntaxHLcodes + ')[^\\]]*\\][\\s\\S]*?\\[\\/\\4\\])(\\s*<\\/pre>)?(\\s*<\\/p>)?', 'gi'), '<pre>$3</pre>'); content = content.replace(/<\/pre><pre>/gi, '\n'); // Remove anonymous, empty paragraphs. content = content.replace(/<p>(\s|&nbsp;)*<\/p>/mg, ''); // Look for <p> <br> in the [tag]s, replace with <br /> content = content.replace(new RegExp('\\[(' + syntaxHLcodes + ')[^\\]]*\\][\\s\\S]+?\\[\\/\\1\\]', 'gi'), function(a) { return a.replace(/<br ?\/?>[\r\n]*/g, '<br />').replace(/<\/?p( [^>]*)?>[\r\n]*/g, '<br />'); }); return content; } }); // Register plugin tinymce.PluginManager.add('syntaxhighlighter', tinymce.plugins.SyntaxHighlighterPlugin); })(); var syntaxHLlast = 0; function pre_wpautop2(content) { var d = new Date(), time = d.getTime(); if ( time - syntaxHLlast < 500 ) return content; syntaxHLlast = time; content = content.replace(new RegExp('<pre>\\s*\\[(' + syntaxHLcodes + ')', 'gi'), '[$1'); content = content.replace(new RegExp('\\[\\/(' + syntaxHLcodes + ')\\]\\s*<\\/pre>', 'gi'), '[/$1]'); content = this._pre_wpautop(content); content = content.replace(new RegExp('\\[(' + syntaxHLcodes + ')[^\\]]*\\][\\s\\S]+?\\[\\/\\1\\]', 'gi'), function(a) { return a.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&').replace(/<%%KEEPWHITESPACE%%>/g, ''); }); return content; } function wpautop2(content) { // js htmlspecialchars content = content.replace(new RegExp('\\[(' + syntaxHLcodes + ')[^\\]]*\\][\\s\\S]+?\\[\\/\\1\\]', 'gi'), function(a) { return a.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); }); return this._wpautop(content); } switchEditors._pre_wpautop = switchEditors.pre_wpautop; switchEditors._wpautop = switchEditors.wpautop; switchEditors.pre_wpautop = pre_wpautop2; switchEditors.wpautop = wpautop2;
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
( function( $ ){ wp.customize( 'blogname', function( value ) { value.bind( function( to ) { $( '#site-title a' ).html( to ); } ); } ); wp.customize( 'blogdescription', function( value ) { value.bind( function( to ) { $( '#site-description' ).html( to ); } ); } ); } )( 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
/* Themolio JavaScript */ jQuery(document).ready(function() { jQuery('.entry-content *:last-child').addClass('last'); jQuery('.comment-content *:last-child').addClass('last'); jQuery('.pingback-content *:last-child').addClass('last'); jQuery('.comments-write-link a').click(function() { jQuery('.commentlist').toggle(); }); });
JavaScript
jQuery(document).ready(function() { jQuery('.main-menu ul li').has('ul').addClass('hasDownChild'); jQuery('.main-menu ul ul li').has('ul').addClass('hasRightChild'); jQuery('.main-menu ul li').hover(function() { jQuery(this).find('ul:first').css({visibility:"visible",display:"none"}).fadeIn(300); }, function() { jQuery(this).find('ul:first').hide(); }); });
JavaScript
jQuery(document).ready(function() { //Loading current tab using cookie if(getCookie("currtab") != "" && getCookie("currtab") != null) { jQuery('.nav-tab').removeClass('nav-tab-active'); var currtab = getCookie("currtab"); jQuery('#' + currtab).addClass('nav-tab-active'); var currsection = currtab.replace('nav-tab-','settings-'); jQuery('.settings-section').hide(); jQuery('#' + currsection).show(); } //Animating tab jQuery('.nav-tab').click(function() { var clickedId = jQuery(this).attr("id"); var currentId = jQuery('.nav-tab-active').attr("id"); if(clickedId != currentId) { var clickedSectionId = clickedId.replace('nav-tab-','settings-'); var currentSectionId = jQuery('.current-section').attr("id"); jQuery('.settings-section').hide(); jQuery('#' + currentSectionId).removeClass('current-section'); jQuery('#' + clickedSectionId).slideDown(500); jQuery('#' + clickedSectionId).addClass('current-section'); jQuery('#' + currentId).removeClass('nav-tab-active'); jQuery('#' + clickedId).addClass('nav-tab-active'); } }); //Upload image script var formfieldID; jQuery('.image_upload').click(function() { var btnId = jQuery(this).attr("id"); formfieldID = btnId.replace("_upload",""); tb_show('', 'media-upload.php?type=image&amp;TB_iframe=true'); return false; }); window.send_to_editor = function(html) { imgurl = jQuery('img',html).attr('src'); jQuery('#' + formfieldID).val(imgurl); tb_remove(); } //Font size increment/decrement jQuery('#font_size_incr_btn').click(function() { var fontsize = parseFloat(jQuery('#font_size').val()); fontsize = fontsize + 1.5; jQuery('#font_size').val(fontsize); }); jQuery('#font_size_decr_btn').click(function() { var fontsize = parseFloat(jQuery('#font_size').val()); fontsize = fontsize - 1.5; if(fontsize < 0) fontsize = 83.3; jQuery('#font_size').val(fontsize); }); //Setting cookie to remember last tab jQuery('#settings-submit').click(function() { var currentTabId = jQuery('.nav-tab-active').attr("id"); setCookie("currtab",currentTabId,3); }); }); function confirmAction() { var confirmation = confirm("Do you want to delete your settings and restore to default settings ?"); return confirmation; } function setCookie(name,value,secs) { if (secs) { var date = new Date(); date.setTime(date.getTime()+(secs*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/"; } function getCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; }
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 }, settingsEastAsia : { count : /[\u3100-\u312F\u31A0-\u31BF\u4E00-\u9FCF\u3400-\u4DBF\uF900-\uFAFF\u2F00-\u2FDF\u2E80-\u2EFF\u31C0-\u31EF\u2FF0-\u2FFF\u1100-\u11FF\uA960-\uA97F\uD780-\uD7FF\u3130-\u318F\uFFA0-\uFFDC\uAC00-\uD7AF\u3040-\u309F\u30A0-\u30FF\u31F0-\u31FF\uFF65-\uFF9F\u3190-\u319F\uA4D0-\uA4FF\uA000-\uA48F\uA490-\uA4CF]/g }, block : 0, wc : function(tx) { var t = this, w = $('.word-count'), tc = 0; if ( t.block ) return; t.block = 1; setTimeout( function() { if ( tx ) { // remove generally useless stuff first tx = tx.replace( t.settings.strip, ' ' ).replace( /&nbsp;|&#160;/gi, ' ' ); // count east asia chars tx = tx.replace( t.settingsEastAsia.count, function(){ tc++; return ''; } ); // count remaining western characters tx = tx.replace( t.settings.clean, '' ); tx.replace( t.settings.count, function(){ tc++; return ''; } ); } w.html(tc.toString()); setTimeout( function() { t.block = 0; }, 2000 ); }, 1 ); } } $(document).bind( 'wpcountwords', function(e, txt) { wpWordCount.wc(txt); }); }(jQuery));
JavaScript
$(function(){$.widget("primeui.puibasemenu",{options:{popup:false,trigger:null,my:"left top",at:"left bottom",triggerEvent:"click"},_create:function(){if(this.options.popup){this._initPopup() }},_initPopup:function(){var a=this; this.element.closest(".pui-menu").addClass("pui-menu-dynamic pui-shadow").appendTo(document.body); this.positionConfig={my:this.options.my,at:this.options.at,of:this.options.trigger}; this.options.trigger.on(this.options.triggerEvent+".pui-menu",function(b){if(a.element.is(":visible")){a.hide() }else{a.show() }b.preventDefault() }); $(document.body).on("click.pui-menu",function(d){var b=a.element.closest(".pui-menu"); if(b.is(":hidden")){return }var c=$(d.target); if(c.is(a.options.trigger.get(0))||a.options.trigger.has(c).length>0){return }var f=b.offset(); if(d.pageX<f.left||d.pageX>f.left+b.width()||d.pageY<f.top||d.pageY>f.top+b.height()){a.hide(d) }}); $(window).on("resize.pui-menu",function(){if(a.element.closest(".pui-menu").is(":visible")){a.align() }}) },show:function(){this.align(); this.element.closest(".pui-menu").css("z-index",++PUI.zindex).show() },hide:function(){this.element.closest(".pui-menu").fadeOut("fast") },align:function(){this.element.closest(".pui-menu").css({left:"",top:""}).position(this.positionConfig) }}) }); $(function(){$.widget("primeui.puimenu",$.primeui.puibasemenu,{options:{},_create:function(){this.element.addClass("pui-menu-list ui-helper-reset").wrap('<div class="pui-menu ui-widget ui-widget-content ui-corner-all ui-helper-clearfix" />'); this.element.children("li").each(function(){var c=$(this); if(c.children("h3").length>0){c.addClass("ui-widget-header ui-corner-all") }else{c.addClass("pui-menuitem ui-widget ui-corner-all"); var a=c.children("a"),b=a.data("icon"); a.addClass("pui-menuitem-link ui-corner-all").contents().wrap('<span class="ui-menuitem-text" />'); if(b){a.prepend('<span class="pui-menuitem-icon ui-icon '+b+'"></span>') }}}); this.menuitemLinks=this.element.find(".pui-menuitem-link:not(.ui-state-disabled)"); this._bindEvents(); this._super() },_bindEvents:function(){var a=this; this.menuitemLinks.on("mouseenter.pui-menu",function(b){$(this).addClass("ui-state-hover") }).on("mouseleave.pui-menu",function(b){$(this).removeClass("ui-state-hover") }); if(this.options.popup){this.menuitemLinks.on("click.pui-menu",function(){a.hide() }) }}}) }); $(function(){$.widget("primeui.puibreadcrumb",{_create:function(){this.element.wrap('<div class="pui-breadcrumb ui-module ui-widget ui-widget-header ui-helper-clearfix ui-corner-all" role="menu">'); this.element.children("li").each(function(b){var c=$(this); c.attr("role","menuitem"); var a=c.children("a"); a.addClass("pui-menuitem-link ui-corner-all").contents().wrap('<span class="ui-menuitem-text" />'); if(b>0){c.before('<li class="pui-breadcrumb-chevron ui-icon ui-icon-triangle-1-e"></li>') }else{a.addClass("ui-icon ui-icon-home") }}) }}) }); $(function(){$.widget("primeui.puitieredmenu",$.primeui.puibasemenu,{options:{autoDisplay:true},_create:function(){this._render(); this.links=this.element.find(".pui-menuitem-link:not(.ui-state-disabled)"); this._bindEvents(); this._super() },_render:function(){this.element.addClass("pui-menu-list ui-helper-reset").wrap('<div class="pui-tieredmenu pui-menu ui-widget ui-widget-content ui-corner-all ui-helper-clearfix" />'); this.element.parent().uniqueId(); this.options.id=this.element.parent().attr("id"); this.element.find("li").each(function(){var c=$(this),a=c.children("a"),b=a.data("icon"); a.addClass("pui-menuitem-link ui-corner-all").contents().wrap('<span class="ui-menuitem-text" />'); if(b){a.prepend('<span class="pui-menuitem-icon ui-icon '+b+'"></span>') }c.addClass("pui-menuitem ui-widget ui-corner-all"); if(c.children("ul").length>0){c.addClass("pui-menu-parent"); c.children("ul").addClass("ui-widget-content pui-menu-list ui-corner-all ui-helper-clearfix pui-menu-child pui-shadow"); a.prepend('<span class="ui-icon ui-icon-triangle-1-e"></span>') }}) },_bindEvents:function(){this._bindItemEvents(); this._bindDocumentHandler() },_bindItemEvents:function(){var a=this; this.links.on("mouseenter.pui-menu",function(){var b=$(this),d=b.parent(),c=a.options.autoDisplay; var e=d.siblings(".pui-menuitem-active"); if(e.length===1){a._deactivate(e) }if(c||a.active){if(d.hasClass("pui-menuitem-active")){a._reactivate(d) }else{a._activate(d) }}else{a._highlight(d) }}); if(this.options.autoDisplay===false){this.rootLinks=this.element.find("> .pui-menuitem > .pui-menuitem-link"); this.rootLinks.data("primeui-tieredmenu-rootlink",this.options.id).find("*").data("primeui-tieredmenu-rootlink",this.options.id); this.rootLinks.on("click.pui-menu",function(f){var c=$(this),d=c.parent(),b=d.children("ul.pui-menu-child"); if(b.length===1){if(b.is(":visible")){a.active=false; a._deactivate(d) }else{a.active=true; a._highlight(d); a._showSubmenu(d,b) }}}) }this.element.parent().find("ul.pui-menu-list").on("mouseleave.pui-menu",function(b){if(a.activeitem){a._deactivate(a.activeitem) }b.stopPropagation() }) },_bindDocumentHandler:function(){var a=this; $(document.body).on("click.pui-menu",function(c){var b=$(c.target); if(b.data("primeui-tieredmenu-rootlink")===a.options.id){return }a.active=false; a.element.find("li.pui-menuitem-active").each(function(){a._deactivate($(this),true) }) }) },_deactivate:function(b,a){this.activeitem=null; b.children("a.pui-menuitem-link").removeClass("ui-state-hover"); b.removeClass("pui-menuitem-active"); if(a){b.children("ul.pui-menu-child:visible").fadeOut("fast") }else{b.children("ul.pui-menu-child:visible").hide() }},_activate:function(b){this._highlight(b); var a=b.children("ul.pui-menu-child"); if(a.length===1){this._showSubmenu(b,a) }},_reactivate:function(d){this.activeitem=d; var c=d.children("ul.pui-menu-child"),b=c.children("li.pui-menuitem-active:first"),a=this; if(b.length===1){a._deactivate(b) }},_highlight:function(a){this.activeitem=a; a.children("a.pui-menuitem-link").addClass("ui-state-hover"); a.addClass("pui-menuitem-active") },_showSubmenu:function(b,a){a.css({left:b.outerWidth(),top:0,"z-index":++PUI.zindex}); a.show() }}) }); $(function(){$.widget("primeui.puimenubar",$.primeui.puitieredmenu,{options:{autoDisplay:true},_create:function(){this._super(); this.element.parent().removeClass("pui-tieredmenu").addClass("pui-menubar") },_showSubmenu:function(e,c){var d=$(window),b=null,a={"z-index":++PUI.zindex}; if(e.parent().hasClass("pui-menu-child")){a.left=e.outerWidth(); a.top=0; b=e.offset().top-d.scrollTop() }else{a.left=0; a.top=e.outerHeight(); b=e.offset().top+a.top-d.scrollTop() }c.css("height","auto"); if((b+c.outerHeight())>d.height()){a.overflow="auto"; a.height=d.height()-(b+20) }c.css(a).show() }}) }); $(function(){$.widget("primeui.puislidemenu",$.primeui.puibasemenu,{_create:function(){this._render(); this.rootList=this.element; this.content=this.element.parent(); this.wrapper=this.content.parent(); this.container=this.wrapper.parent(); this.submenus=this.container.find("ul.pui-menu-list"); this.links=this.element.find("a.pui-menuitem-link:not(.ui-state-disabled)"); this.backward=this.wrapper.children("div.pui-slidemenu-backward"); this.stack=[]; this.jqWidth=this.container.width(); if(!this.element.hasClass("pui-menu-dynamic")){this._applyDimensions() }this._super(); this._bindEvents() },_render:function(){this.element.addClass("pui-menu-list ui-helper-reset").wrap('<div class="pui-menu pui-slidemenu ui-widget ui-widget-content ui-corner-all ui-helper-clearfix"/>').wrap('<div class="pui-slidemenu-wrapper" />').after('<div class="pui-slidemenu-backward ui-widget-header ui-corner-all ui-helper-clearfix">\n <span class="ui-icon ui-icon-triangle-1-w"></span>Back</div>').wrap('<div class="pui-slidemenu-content" />'); this.element.parent().uniqueId(); this.options.id=this.element.parent().attr("id"); this.element.find("li").each(function(){var c=$(this),a=c.children("a"),b=a.data("icon"); a.addClass("pui-menuitem-link ui-corner-all").contents().wrap('<span class="ui-menuitem-text" />'); if(b){a.prepend('<span class="pui-menuitem-icon ui-icon '+b+'"></span>') }c.addClass("pui-menuitem ui-widget ui-corner-all"); if(c.children("ul").length>0){c.addClass("pui-menu-parent"); c.children("ul").addClass("ui-widget-content pui-menu-list ui-corner-all ui-helper-clearfix pui-menu-child ui-shadow"); a.prepend('<span class="ui-icon ui-icon-triangle-1-e"></span>') }}) },_bindEvents:function(){var a=this; this.links.on("mouseenter.pui-menu",function(){$(this).addClass("ui-state-hover") }).on("mouseleave.pui-menu",function(){$(this).removeClass("ui-state-hover") }).on("click.pui-menu",function(){var c=$(this),b=c.next(); if(b.length==1){a._forward(b) }}); this.backward.on("click.pui-menu",function(){a._back() }) },_forward:function(b){var c=this; this._push(b); var a=-1*(this._depth()*this.jqWidth); b.show().css({left:this.jqWidth}); this.rootList.animate({left:a},500,"easeInOutCirc",function(){if(c.backward.is(":hidden")){c.backward.fadeIn("fast") }}) },_back:function(){var c=this,b=this._pop(),d=this._depth(); var a=-1*(d*this.jqWidth); this.rootList.animate({left:a},500,"easeInOutCirc",function(){b.hide(); if(d===0){c.backward.fadeOut("fast") }}) },_push:function(a){this.stack.push(a) },_pop:function(){return this.stack.pop() },_last:function(){return this.stack[this.stack.length-1] },_depth:function(){return this.stack.length },_applyDimensions:function(){this.submenus.width(this.container.width()); this.wrapper.height(this.rootList.outerHeight(true)+this.backward.outerHeight(true)); this.content.height(this.rootList.outerHeight(true)); this.rendered=true },show:function(){this.align(); this.container.css("z-index",++PUI.zindex).show(); if(!this.rendered){this._applyDimensions() }}}) }); $(function(){$.widget("primeui.puicontextmenu",$.primeui.puitieredmenu,{options:{autoDisplay:true,target:null,event:"contextmenu"},_create:function(){this._super(); this.element.parent().removeClass("pui-tieredmenu").addClass("pui-contextmenu pui-menu-dynamic pui-shadow"); var a=this; this.options.target=this.options.target||$(document); if(!this.element.parent().parent().is(document.body)){this.element.parent().appendTo("body") }this.options.target.on(this.options.event+".pui-contextmenu",function(b){a.show(b) }) },_bindItemEvents:function(){this._super(); var a=this; this.links.bind("click",function(){a._hide() }) },_bindDocumentHandler:function(){var a=this; $(document.body).bind("click.pui-contextmenu",function(b){if(a.element.parent().is(":hidden")){return }a._hide() }) },show:function(g){$(document.body).children(".pui-contextmenu:visible").hide(); var f=$(window),d=g.pageX,c=g.pageY,b=this.element.parent().outerWidth(),a=this.element.parent().outerHeight(); if((d+b)>(f.width())+f.scrollLeft()){d=d-b }if((c+a)>(f.height()+f.scrollTop())){c=c-a }if(this.options.beforeShow){this.options.beforeShow.call(this) }this.element.parent().css({left:d,top:c,"z-index":++PUI.zindex}).show(); g.preventDefault(); g.stopPropagation() },_hide:function(){var a=this; this.element.parent().find("li.pui-menuitem-active").each(function(){a._deactivate($(this),true) }); this.element.parent().fadeOut("fast") },isVisible:function(){return this.element.parent().is(":visible") },getTarget:function(){return this.jqTarget }}) });
JavaScript
$(function(){$.widget("primeui.puilightbox",{options:{iframeWidth:640,iframeHeight:480,iframe:false},_create:function(){this.options.mode=this.options.iframe?"iframe":(this.element.children("div").length==1)?"inline":"image"; var a='<div class="pui-lightbox ui-widget ui-helper-hidden ui-corner-all pui-shadow">'; a+='<div class="pui-lightbox-content-wrapper">'; a+='<a class="ui-state-default pui-lightbox-nav-left ui-corner-right ui-helper-hidden"><span class="ui-icon ui-icon-carat-1-w">go</span></a>'; a+='<div class="pui-lightbox-content ui-corner-all"></div>'; a+='<a class="ui-state-default pui-lightbox-nav-right ui-corner-left ui-helper-hidden"><span class="ui-icon ui-icon-carat-1-e">go</span></a>'; a+="</div>"; a+='<div class="pui-lightbox-caption ui-widget-header"><span class="pui-lightbox-caption-text"></span>'; a+='<a class="pui-lightbox-close ui-corner-all" href="#"><span class="ui-icon ui-icon-closethick"></span></a><div style="clear:both" /></div>'; a+="</div>"; this.panel=$(a).appendTo(document.body); this.contentWrapper=this.panel.children(".pui-lightbox-content-wrapper"); this.content=this.contentWrapper.children(".pui-lightbox-content"); this.caption=this.panel.children(".pui-lightbox-caption"); this.captionText=this.caption.children(".pui-lightbox-caption-text"); this.closeIcon=this.caption.children(".pui-lightbox-close"); if(this.options.mode==="image"){this._setupImaging() }else{if(this.options.mode==="inline"){this._setupInline() }else{if(this.options.mode==="iframe"){this._setupIframe() }}}this._bindCommonEvents(); this.links.data("puilightbox-trigger",true).find("*").data("puilightbox-trigger",true); this.closeIcon.data("puilightbox-trigger",true).find("*").data("puilightbox-trigger",true) },_bindCommonEvents:function(){var a=this; this.closeIcon.hover(function(){$(this).toggleClass("ui-state-hover") }).click(function(b){a.hide(); b.preventDefault() }); $(document.body).bind("click.pui-lightbox",function(c){if(a.isHidden()){return }var b=$(c.target); if(b.data("puilightbox-trigger")){return }var d=a.panel.offset(); if(c.pageX<d.left||c.pageX>d.left+a.panel.width()||c.pageY<d.top||c.pageY>d.top+a.panel.height()){a.hide() }}); $(window).resize(function(){if(!a.isHidden()){$(document.body).children(".ui-widget-overlay").css({width:$(document).width(),height:$(document).height()}) }}) },_setupImaging:function(){var a=this; this.links=this.element.children("a"); this.content.append('<img class="ui-helper-hidden"></img>'); this.imageDisplay=this.content.children("img"); this.navigators=this.contentWrapper.children("a"); this.imageDisplay.load(function(){var d=$(this); a._scaleImage(d); var c=(a.panel.width()-d.width())/2,b=(a.panel.height()-d.height())/2; a.content.removeClass("pui-lightbox-loading").animate({width:d.width(),height:d.height()},500,function(){d.fadeIn(); a._showNavigators(); a.caption.slideDown() }); a.panel.animate({left:"+="+c,top:"+="+b},500) }); this.navigators.hover(function(){$(this).toggleClass("ui-state-hover") }).click(function(c){var d=$(this),b; a._hideNavigators(); if(d.hasClass("pui-lightbox-nav-left")){b=a.current===0?a.links.length-1:a.current-1; a.links.eq(b).trigger("click") }else{b=a.current==a.links.length-1?0:a.current+1; a.links.eq(b).trigger("click") }c.preventDefault() }); this.links.click(function(c){var b=$(this); if(a.isHidden()){a.content.addClass("pui-lightbox-loading").width(32).height(32); a.show() }else{a.imageDisplay.fadeOut(function(){$(this).css({width:"auto",height:"auto"}); a.content.addClass("pui-lightbox-loading") }); a.caption.slideUp() }window.setTimeout(function(){a.imageDisplay.attr("src",b.attr("href")); a.current=b.index(); var d=b.attr("title"); if(d){a.captionText.html(d) }},1000); c.preventDefault() }) },_scaleImage:function(g){var f=$(window),c=f.width(),b=f.height(),d=g.width(),a=g.height(),e=a/d; if(d>=c&&e<=1){d=c*0.75; a=d*e }else{if(a>=b){a=b*0.75; d=a/e }}g.css({width:d+"px",height:a+"px"}) },_setupInline:function(){this.links=this.element.children("a"); this.inline=this.element.children("div").addClass("pui-lightbox-inline"); this.inline.appendTo(this.content).show(); var a=this; this.links.click(function(b){a.show(); var c=$(this).attr("title"); if(c){a.captionText.html(c); a.caption.slideDown() }b.preventDefault() }) },_setupIframe:function(){var a=this; this.links=this.element; this.iframe=$('<iframe frameborder="0" style="width:'+this.options.iframeWidth+"px;height:"+this.options.iframeHeight+'px;border:0 none; display: block;"></iframe>').appendTo(this.content); if(this.options.iframeTitle){this.iframe.attr("title",this.options.iframeTitle) }this.element.click(function(b){if(!a.iframeLoaded){a.content.addClass("pui-lightbox-loading").css({width:a.options.iframeWidth,height:a.options.iframeHeight}); a.show(); a.iframe.on("load",function(){a.iframeLoaded=true; a.content.removeClass("pui-lightbox-loading") }).attr("src",a.element.attr("href")) }else{a.show() }var c=a.element.attr("title"); if(c){a.caption.html(c); a.caption.slideDown() }b.preventDefault() }) },show:function(){this.center(); this.panel.css("z-index",++PUI.zindex).show(); if(!this.modality){this._enableModality() }this._trigger("show") },hide:function(){this.panel.fadeOut(); this._disableModality(); this.caption.hide(); if(this.options.mode==="image"){this.imageDisplay.hide().attr("src","").removeAttr("style"); this._hideNavigators() }this._trigger("hide") },center:function(){var c=$(window),b=(c.width()/2)-(this.panel.width()/2),a=(c.height()/2)-(this.panel.height()/2); this.panel.css({left:b,top:a}) },_enableModality:function(){this.modality=$('<div class="ui-widget-overlay"></div>').css({width:$(document).width(),height:$(document).height(),"z-index":this.panel.css("z-index")-1}).appendTo(document.body) },_disableModality:function(){this.modality.remove(); this.modality=null },_showNavigators:function(){this.navigators.zIndex(this.imageDisplay.zIndex()+1).show() },_hideNavigators:function(){this.navigators.hide() },isHidden:function(){return this.panel.is(":hidden") },showURL:function(a){if(a.width){this.iframe.attr("width",a.width) }if(a.height){this.iframe.attr("height",a.height) }this.iframe.attr("src",a.src); this.show() }}) });
JavaScript
$(function(){$.widget("primeui.puilistbox",{options:{scrollHeight:200},_create:function(){this.element.wrap('<div class="pui-listbox pui-inputtext ui-widget ui-widget-content ui-corner-all"><div class="ui-helper-hidden-accessible"></div></div>'); this.container=this.element.parent().parent(); this.listContainer=$('<ul class="pui-listbox-list"></ul>').appendTo(this.container); this.options.multiple=this.element.prop("multiple"); if(this.options.data){this._populateInputFromData() }this._populateContainerFromOptions(); this._restrictHeight(); this._bindEvents() },_populateInputFromData:function(){for(var b=0; b<this.options.data.length; b++){var a=this.options.data[b]; if(a.label){this.element.append('<option value="'+a.value+'">'+a.label+"</option>") }else{this.element.append('<option value="'+a+'">'+a+"</option>") }}},_populateContainerFromOptions:function(){this.choices=this.element.children("option"); for(var b=0; b<this.choices.length; b++){var a=this.choices.eq(b),c=this.options.content?this.options.content.call(this,this.options.data[b]):a.text(); this.listContainer.append('<li class="pui-listbox-item ui-corner-all">'+c+"</li>") }this.items=this.listContainer.find(".pui-listbox-item:not(.ui-state-disabled)") },_restrictHeight:function(){if(this.container.height()>this.options.scrollHeight){this.container.height(this.options.scrollHeight) }},_bindEvents:function(){var a=this; this.items.on("mouseover.puilistbox",function(){var b=$(this); if(!b.hasClass("ui-state-highlight")){b.addClass("ui-state-hover") }}).on("mouseout.puilistbox",function(){$(this).removeClass("ui-state-hover") }).on("dblclick.puilistbox",function(b){a.element.trigger("dblclick"); PUI.clearSelection(); b.preventDefault() }).on("click.puilistbox",function(b){if(a.options.multiple){a._clickMultiple(b,$(this)) }else{a._clickSingle(b,$(this)) }}); this.element.on("focus.puilistbox",function(){a.container.addClass("ui-state-focus") }).on("blur.puilistbox",function(){a.container.removeClass("ui-state-focus") }) },_clickSingle:function(b,a){var c=this.items.filter(".ui-state-highlight"); if(a.index()!==c.index()){if(c.length){this.unselectItem(c) }this.selectItem(a); this.element.trigger("change") }this.element.trigger("click"); PUI.clearSelection(); b.preventDefault() },_clickMultiple:function(a,j){var c=this.items.filter(".ui-state-highlight"),f=(a.metaKey||a.ctrlKey),b=(!f&&c.length===1&&c.index()===j.index()); if(!a.shiftKey){if(!f){this.unselectAll() }if(f&&j.hasClass("ui-state-highlight")){this.unselectItem(j) }else{this.selectItem(j); this.cursorItem=j }}else{if(this.cursorItem){this.unselectAll(); var g=j.index(),k=this.cursorItem.index(),h=(g>k)?k:g,e=(g>k)?(g+1):(k+1); for(var d=h; d<e; d++){this.selectItem(this.items.eq(d)) }}else{this.selectItem(j); this.cursorItem=j }}if(!b){this.element.trigger("change") }this.element.trigger("click"); PUI.clearSelection(); a.preventDefault() },unselectAll:function(){this.items.removeClass("ui-state-highlight ui-state-hover"); this.choices.filter(":selected").prop("selected",false) },selectItem:function(b){var a=null; if($.type(b)==="number"){a=this.items.eq(b) }else{a=b }a.addClass("ui-state-highlight").removeClass("ui-state-hover"); this.choices.eq(a.index()).prop("selected",true); this._trigger("itemSelect",null,this.choices.eq(a.index())) },unselectItem:function(b){var a=null; if($.type(b)==="number"){a=this.items.eq(b) }else{a=b }a.removeClass("ui-state-highlight"); this.choices.eq(a.index()).prop("selected",false); this._trigger("itemUnselect",null,this.choices.eq(a.index())) },_setOption:function(a,b){$.Widget.prototype._setOption.apply(this,arguments); if(a==="data"){this.element.empty(); this.listContainer.empty(); this._populateInputFromData(); this._populateContainerFromOptions(); this._restrictHeight(); this._bindEvents() }},_unbindEvents:function(){this.items.off("mouseover.puilistbox click.puilistbox dblclick.puilistbox") },disable:function(){this._unbindEvents(); this.items.addClass("ui-state-disabled") },enable:function(){this._bindEvents(); this.items.removeClass("ui-state-disabled") }}) });
JavaScript
$(function(){var a={"{FirstPageLink}":{markup:'<span class="pui-paginator-first pui-paginator-element ui-state-default ui-corner-all"><span class="ui-icon ui-icon-seek-first">p</span></span>',create:function(c){var b=$(this.markup); if(c.options.page===0){b.addClass("ui-state-disabled") }b.on("click.puipaginator",function(){if(!$(this).hasClass("ui-state-disabled")){c.option("page",0) }}); return b },update:function(b,c){if(c.page===0){b.addClass("ui-state-disabled").removeClass("ui-state-hover ui-state-active") }else{b.removeClass("ui-state-disabled") }}},"{PreviousPageLink}":{markup:'<span class="pui-paginator-prev pui-paginator-element ui-state-default ui-corner-all"><span class="ui-icon ui-icon-seek-prev">p</span></span>',create:function(c){var b=$(this.markup); if(c.options.page===0){b.addClass("ui-state-disabled") }b.on("click.puipaginator",function(){if(!$(this).hasClass("ui-state-disabled")){c.option("page",c.options.page-1) }}); return b },update:function(b,c){if(c.page===0){b.addClass("ui-state-disabled").removeClass("ui-state-hover ui-state-active") }else{b.removeClass("ui-state-disabled") }}},"{NextPageLink}":{markup:'<span class="pui-paginator-next pui-paginator-element ui-state-default ui-corner-all"><span class="ui-icon ui-icon-seek-next">p</span></span>',create:function(c){var b=$(this.markup); if(c.options.page===(c.getPageCount()-1)){b.addClass("ui-state-disabled").removeClass("ui-state-hover ui-state-active") }b.on("click.puipaginator",function(){if(!$(this).hasClass("ui-state-disabled")){c.option("page",c.options.page+1) }}); return b },update:function(b,c){if(c.page===(c.pageCount-1)){b.addClass("ui-state-disabled").removeClass("ui-state-hover ui-state-active") }else{b.removeClass("ui-state-disabled") }}},"{LastPageLink}":{markup:'<span class="pui-paginator-last pui-paginator-element ui-state-default ui-corner-all"><span class="ui-icon ui-icon-seek-end">p</span></span>',create:function(c){var b=$(this.markup); if(c.options.page===(c.getPageCount()-1)){b.addClass("ui-state-disabled").removeClass("ui-state-hover ui-state-active") }b.on("click.puipaginator",function(){if(!$(this).hasClass("ui-state-disabled")){c.option("page",c.getPageCount()-1) }}); return b },update:function(b,c){if(c.page===(c.pageCount-1)){b.addClass("ui-state-disabled").removeClass("ui-state-hover ui-state-active") }else{b.removeClass("ui-state-disabled") }}},"{PageLinks}":{markup:'<span class="pui-paginator-pages"></span>',create:function(j){var f=$(this.markup),c=this.calculateBoundaries({page:j.options.page,pageLinks:j.options.pageLinks,pageCount:j.getPageCount()}),h=c[0],b=c[1]; for(var e=h; e<=b; e++){var g=(e+1),d=$('<span class="pui-paginator-page pui-paginator-element ui-state-default ui-corner-all">'+g+"</span>"); if(e===j.options.page){d.addClass("ui-state-active") }d.on("click.puipaginator",function(k){var i=$(this); if(!i.hasClass("ui-state-disabled")&&!i.hasClass("ui-state-active")){j.option("page",parseInt(i.text(),10)-1) }}); f.append(d) }return f },update:function(h,b){var k=h.children(),e=this.calculateBoundaries({page:b.page,pageLinks:b.pageLinks,pageCount:b.pageCount}),c=e[0],f=e[1],d=0; k.filter(".ui-state-active").removeClass("ui-state-active"); for(var j=c; j<=f; j++){var l=(j+1),g=k.eq(d); if(j===b.page){g.addClass("ui-state-active") }g.text(l); d++ }},calculateBoundaries:function(d){var e=d.page,i=d.pageLinks,c=d.pageCount,f=Math.min(i,c); var h=Math.max(0,parseInt(Math.ceil(e-((f)/2)),10)),b=Math.min(c-1,h+f-1); var g=i-(b-h+1); h=Math.max(0,h-g); return[h,b] }}}; $.widget("primeui.puipaginator",{options:{pageLinks:5,totalRecords:0,page:0,rows:0,template:"{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}"},_create:function(){this.element.addClass("pui-paginator ui-widget-header"); this.paginatorElements=[]; var b=this.options.template.split(/[ ]+/); for(var c=0; c<b.length; c++){var f=b[c],e=a[f]; if(e){var d=e.create(this); this.paginatorElements[f]=d; this.element.append(d) }}this._bindEvents() },_bindEvents:function(){this.element.find("span.pui-paginator-element").on("mouseover.puipaginator",function(){var b=$(this); if(!b.hasClass("ui-state-active")&&!b.hasClass("ui-state-disabled")){b.addClass("ui-state-hover") }}).on("mouseout.puipaginator",function(){var b=$(this); if(b.hasClass("ui-state-hover")){b.removeClass("ui-state-hover") }}) },_setOption:function(b,c){if(b==="page"){this.setPage(c) }else{$.Widget.prototype._setOption.apply(this,arguments) }},setPage:function(e,b){var c=this.getPageCount(); if(e>=0&&e<c&&this.options.page!==e){var d={first:this.options.rows*e,rows:this.options.rows,page:e,pageCount:c,pageLinks:this.options.pageLinks}; this.options.page=e; if(!b){this._trigger("paginate",null,d) }this.updateUI(d) }},updateUI:function(c){for(var b in this.paginatorElements){a[b].update(this.paginatorElements[b],c) }},getPageCount:function(){return Math.ceil(this.options.totalRecords/this.options.rows)||1 }}) });
JavaScript
$(function(){$.widget("primeui.puipicklist",{options:{effect:"fade",effectSpeed:"fast",sourceCaption:null,targetCaption:null,filter:false,filterFunction:null,filterMatchMode:"startsWith",dragdrop:true,sourceData:null,targetData:null,content:null},_create:function(){this.element.uniqueId().addClass("pui-picklist ui-widget ui-helper-clearfix"); this.inputs=this.element.children("select"); this.items=$(); this.sourceInput=this.inputs.eq(0); this.targetInput=this.inputs.eq(1); if(this.options.sourceData){this._populateInputFromData(this.sourceInput,this.options.sourceData) }if(this.options.targetData){this._populateInputFromData(this.targetInput,this.options.targetData) }this.sourceList=this._createList(this.sourceInput,"pui-picklist-source",this.options.sourceCaption,this.options.sourceData); this._createButtons(); this.targetList=this._createList(this.targetInput,"pui-picklist-target",this.options.targetCaption,this.options.targetData); if(this.options.showSourceControls){this.element.prepend(this._createListControls(this.sourceList)) }if(this.options.showTargetControls){this.element.append(this._createListControls(this.targetList)) }this._bindEvents() },_populateInputFromData:function(b,d){for(var c=0; c<d.length; c++){var a=d[c]; if(a.label){b.append('<option value="'+a.value+'">'+a.label+"</option>") }else{b.append('<option value="'+a+'">'+a+"</option>") }}},_createList:function(d,b,c,e){d.wrap('<div class="ui-helper-hidden"></div>'); var a=$('<div class="pui-picklist-listwrapper '+b+'"></div>'),f=$('<ul class="ui-widget-content pui-picklist-list pui-inputtext"></ul>'); if(this.options.filter){a.append('<div class="pui-picklist-filter-container"><input type="text" class="pui-picklist-filter" /><span class="ui-icon ui-icon-search"></span></div>'); a.find("> .pui-picklist-filter-container > input").puiinputtext() }if(c){a.append('<div class="pui-picklist-caption ui-widget-header ui-corner-tl ui-corner-tr">'+c+"</div>"); f.addClass("ui-corner-bottom") }else{f.addClass("ui-corner-all") }this._populateContainerFromOptions(d,f,e); a.append(f).appendTo(this.element); return f },_populateContainerFromOptions:function(b,h,f){var g=b.children("option"); for(var c=0; c<g.length; c++){var a=g.eq(c),e=this.options.content?this.options.content.call(this,f[c]):a.text(),d=$('<li class="pui-picklist-item ui-corner-all">'+e+"</li>").data({"item-label":a.text(),"item-value":a.val()}); this.items=this.items.add(d); h.append(d) }},_createButtons:function(){var b=this,a=$('<ul class="pui-picklist-buttons"></ul>'); a.append(this._createButton("ui-icon-arrow-1-e","pui-picklist-button-add",function(){b._add() })).append(this._createButton("ui-icon-arrowstop-1-e","pui-picklist-button-addall",function(){b._addAll() })).append(this._createButton("ui-icon-arrow-1-w","pui-picklist-button-remove",function(){b._remove() })).append(this._createButton("ui-icon-arrowstop-1-w","pui-picklist-button-removeall",function(){b._removeAll() })); this.element.append(a) },_createListControls:function(b){var c=this,a=$('<ul class="pui-picklist-buttons"></ul>'); a.append(this._createButton("ui-icon-arrow-1-n","pui-picklist-button-move-up",function(){c._moveUp(b) })).append(this._createButton("ui-icon-arrowstop-1-n","pui-picklist-button-move-top",function(){c._moveTop(b) })).append(this._createButton("ui-icon-arrow-1-s","pui-picklist-button-move-down",function(){c._moveDown(b) })).append(this._createButton("ui-icon-arrowstop-1-s","pui-picklist-button-move-bottom",function(){c._moveBottom(b) })); return a },_createButton:function(d,a,c){var b=$('<button class="'+a+'" type="button"></button>').puibutton({icon:d,click:function(){c(); $(this).removeClass("ui-state-hover ui-state-focus") }}); return b },_bindEvents:function(){var a=this; this.items.on("mouseover.puipicklist",function(c){var b=$(this); if(!b.hasClass("ui-state-highlight")){$(this).addClass("ui-state-hover") }}).on("mouseout.puipicklist",function(b){$(this).removeClass("ui-state-hover") }).on("click.puipicklist",function(d){var k=$(this),f=(d.metaKey||d.ctrlKey); if(!d.shiftKey){if(!f){a.unselectAll() }if(f&&k.hasClass("ui-state-highlight")){a.unselectItem(k) }else{a.selectItem(k); a.cursorItem=k }}else{a.unselectAll(); if(a.cursorItem&&(a.cursorItem.parent().is(k.parent()))){var g=k.index(),l=a.cursorItem.index(),j=(g>l)?l:g,c=(g>l)?(g+1):(l+1),h=k.parent(); for(var b=j; b<c; b++){a.selectItem(h.children("li.ui-picklist-item").eq(b)) }}else{a.selectItem(k); a.cursorItem=k }}}).on("dblclick.pickList",function(){var b=$(this); if($(this).closest(".pui-picklist-listwrapper").hasClass("pui-picklist-source")){a._transfer(b,a.sourceList,a.targetList,"dblclick") }else{a._transfer(b,a.targetList,a.sourceList,"dblclick") }PUI.clearSelection() }); if(this.options.filter){this._setupFilterMatcher(); this.element.find("> .pui-picklist-source > .pui-picklist-filter-container > input").on("keyup",function(b){a._filter(this.value,a.sourceList) }); this.element.find("> .pui-picklist-target > .pui-picklist-filter-container > input").on("keyup",function(b){a._filter(this.value,a.targetList) }) }if(this.options.dragdrop){this.element.find("> .pui-picklist-listwrapper > ul.pui-picklist-list").sortable({cancel:".ui-state-disabled",connectWith:"#"+this.element.attr("id")+" .pui-picklist-list",revert:true,containment:this.element,update:function(b,c){a.unselectItem(c.item); a._saveState() },receive:function(b,c){a._triggerTransferEvent(c.item,c.sender,c.item.closest("ul.pui-picklist-list"),"dragdrop") }}) }},selectItem:function(a){a.removeClass("ui-state-hover").addClass("ui-state-highlight") },unselectItem:function(a){a.removeClass("ui-state-highlight") },unselectAll:function(){var b=this.items.filter(".ui-state-highlight"); for(var a=0; a<b.length; a++){this.unselectItem(b.eq(a)) }},_add:function(){var a=this.sourceList.children("li.pui-picklist-item.ui-state-highlight"); this._transfer(a,this.sourceList,this.targetList,"command") },_addAll:function(){var a=this.sourceList.children("li.pui-picklist-item:visible:not(.ui-state-disabled)"); this._transfer(a,this.sourceList,this.targetList,"command") },_remove:function(){var a=this.targetList.children("li.pui-picklist-item.ui-state-highlight"); this._transfer(a,this.targetList,this.sourceList,"command") },_removeAll:function(){var a=this.targetList.children("li.pui-picklist-item:visible:not(.ui-state-disabled)"); this._transfer(a,this.targetList,this.sourceList,"command") },_moveUp:function(e){var f=this,d=f.options.effect,b=e.children(".ui-state-highlight"),a=b.length,c=0; b.each(function(){var g=$(this); if(!g.is(":first-child")){if(d){g.hide(f.options.effect,{},f.options.effectSpeed,function(){g.insertBefore(g.prev()).show(f.options.effect,{},f.options.effectSpeed,function(){c++; if(c===a){f._saveState() }}) }) }else{g.hide().insertBefore(g.prev()).show() }}}); if(!d){this._saveState() }},_moveTop:function(e){var f=this,d=f.options.effect,b=e.children(".ui-state-highlight"),a=b.length,c=0; e.children(".ui-state-highlight").each(function(){var g=$(this); if(!g.is(":first-child")){if(d){g.hide(f.options.effect,{},f.options.effectSpeed,function(){g.prependTo(g.parent()).show(f.options.effect,{},f.options.effectSpeed,function(){c++; if(c===a){f._saveState() }}) }) }else{g.hide().prependTo(g.parent()).show() }}}); if(!d){this._saveState() }},_moveDown:function(e){var f=this,d=f.options.effect,b=e.children(".ui-state-highlight"),a=b.length,c=0; $(e.children(".ui-state-highlight").get().reverse()).each(function(){var g=$(this); if(!g.is(":last-child")){if(d){g.hide(f.options.effect,{},f.options.effectSpeed,function(){g.insertAfter(g.next()).show(f.options.effect,{},f.options.effectSpeed,function(){c++; if(c===a){f._saveState() }}) }) }else{g.hide().insertAfter(g.next()).show() }}}); if(!d){this._saveState() }},_moveBottom:function(e){var f=this,d=f.options.effect,b=e.children(".ui-state-highlight"),a=b.length,c=0; e.children(".ui-state-highlight").each(function(){var g=$(this); if(!g.is(":last-child")){if(d){g.hide(f.options.effect,{},f.options.effectSpeed,function(){g.appendTo(g.parent()).show(f.options.effect,{},f.options.effectSpeed,function(){c++; if(c===a){f._saveState() }}) }) }else{g.hide().appendTo(g.parent()).show() }}}); if(!d){this._saveState() }},_transfer:function(b,g,f,d){var e=this,a=b.length,c=0; if(this.options.effect){b.hide(this.options.effect,{},this.options.effectSpeed,function(){var h=$(this); e.unselectItem(h); h.appendTo(f).show(e.options.effect,{},e.options.effectSpeed,function(){c++; if(c===a){e._saveState(); e._triggerTransferEvent(b,g,f,d) }}) }) }else{b.hide().removeClass("ui-state-highlight ui-state-hover").appendTo(f).show(); this._saveState(); this._triggerTransferEvent(b,g,f,d) }},_triggerTransferEvent:function(a,e,d,b){var c={}; c.items=a; c.from=e; c.to=d; c.type=b; this._trigger("transfer",null,c) },_saveState:function(){this.sourceInput.children().remove(); this.targetInput.children().remove(); this._generateItems(this.sourceList,this.sourceInput); this._generateItems(this.targetList,this.targetInput); this.cursorItem=null },_generateItems:function(b,a){b.children(".pui-picklist-item").each(function(){var d=$(this),e=d.data("item-value"),c=d.data("item-label"); a.append('<option value="'+e+'" selected="selected">'+c+"</option>") }) },_setupFilterMatcher:function(){this.filterMatchers={startsWith:this._startsWithFilter,contains:this._containsFilter,endsWith:this._endsWithFilter,custom:this.options.filterFunction}; this.filterMatcher=this.filterMatchers[this.options.filterMatchMode] },_filter:function(f,e){var g=$.trim(f).toLowerCase(),a=e.children("li.pui-picklist-item"); if(g===""){a.filter(":hidden").show() }else{for(var b=0; b<a.length; b++){var d=a.eq(b),c=d.data("item-label"); if(this.filterMatcher(c,g)){d.show() }else{d.hide() }}}},_startsWithFilter:function(b,a){return b.toLowerCase().indexOf(a)===0 },_containsFilter:function(b,a){return b.toLowerCase().indexOf(a)!==-1 },_endsWithFilter:function(b,a){return b.indexOf(a,b.length-a.length)!==-1 },_setOption:function(a,b){$.Widget.prototype._setOption.apply(this,arguments); if(a==="sourceData"){this._setOptionData(this.sourceInput,this.sourceList,this.options.sourceData) }if(a==="targetData"){this._setOptionData(this.targetInput,this.targetList,this.options.targetData) }},_setOptionData:function(a,c,b){a.empty(); c.empty(); this._populateInputFromData(a,b); this._populateContainerFromOptions(a,c,b); this._bindEvents() },_unbindEvents:function(){this.items.off("mouseover.puipicklist mouseout.puipicklist click.puipicklist dblclick.pickList") },disable:function(){this._unbindEvents(); this.items.addClass("ui-state-disabled"); this.element.find(".pui-picklist-buttons > button").each(function(a,b){$(b).puibutton("disable") }) },enable:function(){this._bindEvents(); this.items.removeClass("ui-state-disabled"); this.element.find(".pui-picklist-buttons > button").each(function(a,b){$(b).puibutton("enable") }) }}) });
JavaScript
$(function(){$.widget("primeui.puirating",{options:{stars:5,cancel:true},_create:function(){var b=this.element; b.wrap("<div />"); this.container=b.parent(); this.container.addClass("pui-rating"); var d=b.val(),e=d===""?null:parseInt(d,10); if(this.options.cancel){this.container.append('<div class="pui-rating-cancel"><a></a></div>') }for(var c=0; c<this.options.stars; c++){var a=(e>c)?"pui-rating-star pui-rating-star-on":"pui-rating-star"; this.container.append('<div class="'+a+'"><a></a></div>') }this.stars=this.container.children(".pui-rating-star"); if(b.prop("disabled")){this.container.addClass("ui-state-disabled") }else{if(!b.prop("readonly")){this._bindEvents() }}},_bindEvents:function(){var a=this; this.stars.click(function(){var b=a.stars.index(this)+1; a.setValue(b) }); this.container.children(".pui-rating-cancel").hover(function(){$(this).toggleClass("pui-rating-cancel-hover") }).click(function(){a.cancel() }) },cancel:function(){this.element.val(""); this.stars.filter(".pui-rating-star-on").removeClass("pui-rating-star-on"); this._trigger("cancel",null) },getValue:function(){var a=this.element.val(); return a===""?null:parseInt(a,10) },setValue:function(b){this.element.val(b); this.stars.removeClass("pui-rating-star-on"); for(var a=0; a<b; a++){this.stars.eq(a).addClass("pui-rating-star-on") }this._trigger("rate",null,b) },enable:function(){this.container.removeClass("ui-state-disabled"); this._bindEvents() },disable:function(){this.container.addClass("ui-state-disabled"); this._unbindEvents() },_unbindEvents:function(){this.stars.off("click"); this.container.children(".pui-rating-cancel").off("hover click") }}) });
JavaScript
$(function(){$.widget("primeui.puicheckbox",{_create:function(){this.element.wrap('<div class="pui-chkbox ui-widget"><div class="ui-helper-hidden-accessible"></div></div>'); this.container=this.element.parent().parent(); this.box=$('<div class="pui-chkbox-box ui-widget ui-corner-all ui-state-default">').appendTo(this.container); this.icon=$('<span class="pui-chkbox-icon pui-c"></span>').appendTo(this.box); this.disabled=this.element.prop("disabled"); this.label=$('label[for="'+this.element.attr("id")+'"]'); if(this.isChecked()){this.box.addClass("ui-state-active"); this.icon.addClass("ui-icon ui-icon-check") }if(this.disabled){this.box.addClass("ui-state-disabled") }else{this._bindEvents() }},_bindEvents:function(){var a=this; this.box.on("mouseover.puicheckbox",function(){if(!a.isChecked()){a.box.addClass("ui-state-hover") }}).on("mouseout.puicheckbox",function(){a.box.removeClass("ui-state-hover") }).on("click.puicheckbox",function(){a.toggle() }); this.element.focus(function(){if(a.isChecked()){a.box.removeClass("ui-state-active") }a.box.addClass("ui-state-focus") }).blur(function(){if(a.isChecked()){a.box.addClass("ui-state-active") }a.box.removeClass("ui-state-focus") }).keydown(function(c){var b=$.ui.keyCode; if(c.which==b.SPACE){c.preventDefault() }}).keyup(function(c){var b=$.ui.keyCode; if(c.which==b.SPACE){a.toggle(true); c.preventDefault() }}); this.label.on("click.puicheckbox",function(b){a.toggle(); b.preventDefault() }) },toggle:function(a){if(this.isChecked()){this.uncheck(a) }else{this.check(a) }this._trigger("change",null,this.isChecked()) },isChecked:function(){return this.element.prop("checked") },check:function(b,a){if(!this.isChecked()){this.element.prop("checked",true); this.icon.addClass("ui-icon ui-icon-check"); if(!b){this.box.addClass("ui-state-active") }if(!a){this.element.trigger("change") }}},uncheck:function(){if(this.isChecked()){this.element.prop("checked",false); this.box.removeClass("ui-state-active"); this.icon.removeClass("ui-icon ui-icon-check"); this.element.trigger("change") }},_unbindEvents:function(){this.box.off(); this.element.off("focus blur keydown keyup"); this.label.off() },disable:function(){this.box.prop("disabled",true); this.box.attr("aria-disabled",true); this.box.addClass("ui-state-disabled").removeClass("ui-state-hover"); this._unbindEvents() },enable:function(){this.box.prop("disabled",false); this.box.attr("aria-disabled",false); this.box.removeClass("ui-state-disabled"); this._bindEvents() }}) });
JavaScript
$(function(){$.widget("primeui.puigalleria",{options:{panelWidth:600,panelHeight:400,frameWidth:60,frameHeight:40,activeIndex:0,showFilmstrip:true,autoPlay:true,transitionInterval:4000,effect:"fade",effectSpeed:250,effectOptions:{},showCaption:true,customContent:false},_create:function(){this.element.addClass("pui-galleria ui-widget ui-widget-content ui-corner-all"); this.panelWrapper=this.element.children("ul"); this.panelWrapper.addClass("pui-galleria-panel-wrapper"); this.panels=this.panelWrapper.children("li"); this.panels.addClass("pui-galleria-panel ui-helper-hidden"); this.element.width(this.options.panelWidth); this.panelWrapper.width(this.options.panelWidth).height(this.options.panelHeight); this.panels.width(this.options.panelWidth).height(this.options.panelHeight); if(this.options.showFilmstrip){this._renderStrip(); this._bindEvents() }if(this.options.customContent){this.panels.children("img").remove(); this.panels.children("div").addClass("pui-galleria-panel-content") }var a=this.panels.eq(this.options.activeIndex); a.removeClass("ui-helper-hidden"); if(this.options.showCaption){this._showCaption(a) }this.element.css("visibility","visible"); if(this.options.autoPlay){this.startSlideshow() }},_renderStrip:function(){var a='style="width:'+this.options.frameWidth+"px;height:"+this.options.frameHeight+'px;"'; this.stripWrapper=$('<div class="pui-galleria-filmstrip-wrapper"></div>').width(this.element.width()-50).height(this.options.frameHeight).appendTo(this.element); this.strip=$('<ul class="pui-galleria-filmstrip"></div>').appendTo(this.stripWrapper); for(var c=0; c<this.panels.length; c++){var e=this.panels.eq(c).children("img"),b=(c==this.options.activeIndex)?"pui-galleria-frame pui-galleria-frame-active":"pui-galleria-frame",d='<li class="'+b+'" '+a+'><div class="pui-galleria-frame-content" '+a+'><img src="'+e.attr("src")+'" class="pui-galleria-frame-image" '+a+"/></div></li>"; this.strip.append(d) }this.frames=this.strip.children("li.pui-galleria-frame"); this.element.append('<div class="pui-galleria-nav-prev ui-icon ui-icon-circle-triangle-w" style="bottom:'+(this.options.frameHeight/2)+'px"></div><div class="pui-galleria-nav-next ui-icon ui-icon-circle-triangle-e" style="bottom:'+(this.options.frameHeight/2)+'px"></div>'); if(this.options.showCaption){this.caption=$('<div class="pui-galleria-caption"></div>').css({bottom:this.stripWrapper.outerHeight(true),width:this.panelWrapper.width()}).appendTo(this.element) }},_bindEvents:function(){var a=this; this.element.children("div.pui-galleria-nav-prev").on("click.puigalleria",function(){if(a.slideshowActive){a.stopSlideshow() }if(!a.isAnimating()){a.prev() }}); this.element.children("div.pui-galleria-nav-next").on("click.puigalleria",function(){if(a.slideshowActive){a.stopSlideshow() }if(!a.isAnimating()){a.next() }}); this.strip.children("li.pui-galleria-frame").on("click.puigalleria",function(){if(a.slideshowActive){a.stopSlideshow() }a.select($(this).index(),false) }) },startSlideshow:function(){var a=this; this.interval=window.setInterval(function(){a.next() },this.options.transitionInterval); this.slideshowActive=true },stopSlideshow:function(){window.clearInterval(this.interval); this.slideshowActive=false },isSlideshowActive:function(){return this.slideshowActive },select:function(g,j){if(g!==this.options.activeIndex){if(this.options.showCaption){this._hideCaption() }var a=this.panels.eq(this.options.activeIndex),b=this.panels.eq(g); a.hide(this.options.effect,this.options.effectOptions,this.options.effectSpeed); b.show(this.options.effect,this.options.effectOptions,this.options.effectSpeed); if(this.options.showFilmstrip){var c=this.frames.eq(this.options.activeIndex),e=this.frames.eq(g); c.removeClass("pui-galleria-frame-active").css("opacity",""); e.animate({opacity:1},this.options.effectSpeed,null,function(){$(this).addClass("pui-galleria-frame-active") }); if((j===undefined||j===true)){var h=e.position().left,k=this.options.frameWidth+parseInt(e.css("margin-right"),10),i=this.strip.position().left,d=h+i,f=d+this.options.frameWidth; if(f>this.stripWrapper.width()){this.strip.animate({left:"-="+k},this.options.effectSpeed,"easeInOutCirc") }else{if(d<0){this.strip.animate({left:"+="+k},this.options.effectSpeed,"easeInOutCirc") }}}}if(this.options.showCaption){this._showCaption(b) }this.options.activeIndex=g }},_hideCaption:function(){this.caption.slideUp(this.options.effectSpeed) },_showCaption:function(a){var b=a.children("img"); this.caption.html("<h4>"+b.attr("title")+"</h4><p>"+b.attr("alt")+"</p>").slideDown(this.options.effectSpeed) },prev:function(){if(this.options.activeIndex!==0){this.select(this.options.activeIndex-1) }},next:function(){if(this.options.activeIndex!==(this.panels.length-1)){this.select(this.options.activeIndex+1) }else{this.select(0,false); this.strip.animate({left:0},this.options.effectSpeed,"easeInOutCirc") }},isAnimating:function(){return this.strip.is(":animated") }}) });
JavaScript
$(function(){$.widget("primeui.puigrowl",{options:{sticky:false,life:3000},_create:function(){var a=this.element; a.addClass("pui-growl ui-widget").appendTo(document.body) },show:function(a){var b=this; this.clear(); $.each(a,function(c,d){b._renderMessage(d) }) },clear:function(){this.element.children("div.pui-growl-item-container").remove() },_renderMessage:function(c){var a='<div class="pui-growl-item-container ui-state-highlight ui-corner-all ui-helper-hidden" aria-live="polite">'; a+='<div class="pui-growl-item pui-shadow">'; a+='<div class="pui-growl-icon-close ui-icon ui-icon-closethick" style="display:none"></div>'; a+='<span class="pui-growl-image pui-growl-image-'+c.severity+'" />'; a+='<div class="pui-growl-message">'; a+='<span class="pui-growl-title">'+c.summary+"</span>"; a+="<p>"+(c.detail||"")+"</p>"; a+='</div><div style="clear: both;"></div></div></div>'; var b=$(a); this._bindMessageEvents(b); b.appendTo(this.element).fadeIn() },_removeMessage:function(a){a.fadeTo("normal",0,function(){a.slideUp("normal","easeInOutCirc",function(){a.remove() }) }) },_bindMessageEvents:function(a){var c=this,b=this.options.sticky; a.on("mouseover.puigrowl",function(){var d=$(this); if(!d.is(":animated")){d.find("div.pui-growl-icon-close:first").show() }}).on("mouseout.puigrowl",function(){$(this).find("div.pui-growl-icon-close:first").hide() }); a.find("div.pui-growl-icon-close").on("click.puigrowl",function(){c._removeMessage(a); if(!b){window.clearTimeout(a.data("timeout")) }}); if(!b){this._setRemovalTimeout(a) }},_setRemovalTimeout:function(a){var c=this; var b=window.setTimeout(function(){c._removeMessage(a) },this.options.life); a.data("timeout",b) }}) });
JavaScript
$(function(){$.widget("primeui.puiinputtextarea",{options:{autoResize:false,autoComplete:false,maxlength:null,counter:null,counterTemplate:"{0}",minQueryLength:3,queryDelay:700},_create:function(){var a=this; this.element.puiinputtext(); if(this.options.autoResize){this.options.rowsDefault=this.element.attr("rows"); this.options.colsDefault=this.element.attr("cols"); this.element.addClass("pui-inputtextarea-resizable"); this.element.keyup(function(){a._resize() }).focus(function(){a._resize() }).blur(function(){a._resize() }) }if(this.options.maxlength){this.element.keyup(function(d){var c=a.element.val(),b=c.length; if(b>a.options.maxlength){a.element.val(c.substr(0,a.options.maxlength)) }if(a.options.counter){a._updateCounter() }}) }if(this.options.counter){this._updateCounter() }if(this.options.autoComplete){this._initAutoComplete() }},_updateCounter:function(){var d=this.element.val(),c=d.length; if(this.options.counter){var b=this.options.maxlength-c,a=this.options.counterTemplate.replace("{0}",b); this.options.counter.text(a) }},_resize:function(){var d=0,a=this.element.val().split("\n"); for(var b=a.length-1; b>=0; --b){d+=Math.floor((a[b].length/this.options.colsDefault)+1) }var c=(d>=this.options.rowsDefault)?(d+1):this.options.rowsDefault; this.element.attr("rows",c) },_initAutoComplete:function(){var b='<div id="'+this.id+'_panel" class="pui-autocomplete-panel ui-widget-content ui-corner-all ui-helper-hidden ui-shadow"></div>',c=this; this.panel=$(b).appendTo(document.body); this.element.keyup(function(g){var f=$.ui.keyCode; switch(g.which){case f.UP:case f.LEFT:case f.DOWN:case f.RIGHT:case f.ENTER:case f.NUMPAD_ENTER:case f.TAB:case f.SPACE:case f.CONTROL:case f.ALT:case f.ESCAPE:case 224:break; default:var d=c._extractQuery(); if(d&&d.length>=c.options.minQueryLength){if(c.timeout){c._clearTimeout(c.timeout) }c.timeout=window.setTimeout(function(){c.search(d) },c.options.queryDelay) }break }}).keydown(function(j){var d=c.panel.is(":visible"),i=$.ui.keyCode,h; switch(j.which){case i.UP:case i.LEFT:if(d){h=c.items.filter(".ui-state-highlight"); var g=h.length===0?c.items.eq(0):h.prev(); if(g.length==1){h.removeClass("ui-state-highlight"); g.addClass("ui-state-highlight"); if(c.options.scrollHeight){PUI.scrollInView(c.panel,g) }}j.preventDefault() }else{c._clearTimeout() }break; case i.DOWN:case i.RIGHT:if(d){h=c.items.filter(".ui-state-highlight"); var f=h.length===0?_self.items.eq(0):h.next(); if(f.length==1){h.removeClass("ui-state-highlight"); f.addClass("ui-state-highlight"); if(c.options.scrollHeight){PUI.scrollInView(c.panel,f) }}j.preventDefault() }else{c._clearTimeout() }break; case i.ENTER:case i.NUMPAD_ENTER:if(d){c.items.filter(".ui-state-highlight").trigger("click"); j.preventDefault() }else{c._clearTimeout() }break; case i.SPACE:case i.CONTROL:case i.ALT:case i.BACKSPACE:case i.ESCAPE:case 224:c._clearTimeout(); if(d){c._hide() }break; case i.TAB:c._clearTimeout(); if(d){c.items.filter(".ui-state-highlight").trigger("click"); c._hide() }break }}); $(document.body).bind("mousedown.puiinputtextarea",function(d){if(c.panel.is(":hidden")){return }var f=c.panel.offset(); if(d.target===c.element.get(0)){return }if(d.pageX<f.left||d.pageX>f.left+c.panel.width()||d.pageY<f.top||d.pageY>f.top+c.panel.height()){c._hide() }}); var a="resize."+this.id; $(window).unbind(a).bind(a,function(){if(c.panel.is(":visible")){c._hide() }}) },_bindDynamicEvents:function(){var a=this; this.items.bind("mouseover",function(){var b=$(this); if(!b.hasClass("ui-state-highlight")){a.items.filter(".ui-state-highlight").removeClass("ui-state-highlight"); b.addClass("ui-state-highlight") }}).bind("click",function(d){var c=$(this),e=c.attr("data-item-value"),b=e.substring(a.query.length); a.element.focus(); a.element.insertText(b,a.element.getSelection().start,true); a._hide(); a._trigger("itemselect",d,c) }) },_clearTimeout:function(){if(this.timeout){window.clearTimeout(this.timeout) }this.timeout=null },_extractQuery:function(){var b=this.element.getSelection().end,a=/\S+$/.exec(this.element.get(0).value.slice(0,b)),c=a?a[0]:null; return c },search:function(b){this.query=b; var a={query:b}; if(this.options.completeSource){this.options.completeSource.call(this,a,this._handleResponse) }},_handleResponse:function(c){this.panel.html(""); var d=$('<ul class="pui-autocomplete-items pui-autocomplete-list ui-widget-content ui-widget ui-corner-all ui-helper-reset"></ul>'); for(var a=0; a<c.length; a++){var b=$('<li class="pui-autocomplete-item pui-autocomplete-list-item ui-corner-all"></li>'); b.attr("data-item-value",c[a].value); b.text(c[a].label); d.append(b) }this.panel.append(d).show(); this.items=this.panel.find(".pui-autocomplete-item"); this._bindDynamicEvents(); if(this.items.length>0){this.items.eq(0).addClass("ui-state-highlight"); if(this.options.scrollHeight&&this.panel.height()>this.options.scrollHeight){this.panel.height(this.options.scrollHeight) }if(this.panel.is(":hidden")){this._show() }else{this._alignPanel() }}else{this.panel.hide() }},_alignPanel:function(){var b=this.element.getCaretPosition(),a=this.element.offset(); this.panel.css({left:a.left+b.left,top:a.top+b.top,width:this.element.innerWidth()}) },_show:function(){this._alignPanel(); this.panel.show() },_hide:function(){this.panel.hide() },disable:function(){this.element.puiinputtext("disable") },enable:function(){this.element.puiinputtext("enable") }}) });
JavaScript
$(function(){$.widget("primeui.puiinputtext",{_create:function(){var a=this.element,b=a.prop("disabled"); a.addClass("pui-inputtext ui-widget ui-state-default ui-corner-all"); if(b){a.addClass("ui-state-disabled") }else{this._enableMouseEffects() }a.attr("role","textbox").attr("aria-disabled",b).attr("aria-readonly",a.prop("readonly")).attr("aria-multiline",a.is("textarea")) },_destroy:function(){},_enableMouseEffects:function(){var a=this.element; a.hover(function(){a.toggleClass("ui-state-hover") }).focus(function(){a.addClass("ui-state-focus") }).blur(function(){a.removeClass("ui-state-focus") }) },_disableMouseEffects:function(){var a=this.element; a.off("mouseenter mouseleave focus blur") },disable:function(){this.element.prop("disabled",true); this.element.attr("aria-disabled",true); this.element.addClass("ui-state-disabled"); this.element.removeClass("ui-state-focus ui-state-hover"); this._disableMouseEffects() },enable:function(){this.element.prop("disabled",false); this.element.attr("aria-disabled",false); this.element.removeClass("ui-state-disabled"); this._enableMouseEffects() }}) });
JavaScript
$(function(){$.widget("primeui.puidatatable",{options:{columns:null,datasource:null,paginator:null,selectionMode:null,rowSelect:null,rowUnselect:null,caption:null,sortField:null,sortOrder:null,keepSelectionInLazyMode:false,scrollable:false},_create:function(){this.id=this.element.attr("id"); if(!this.id){this.id=this.element.uniqueId().attr("id") }this.element.addClass("pui-datatable ui-widget"); if(this.options.scrollable){this._createScrollableDatatable() }else{this._createRegularDatatable() }if(this.options.datasource){if($.isArray(this.options.datasource)){this.data=this.options.datasource; this._initialize() }else{if($.type(this.options.datasource)==="function"){if(this.options.lazy){this.options.datasource.call(this,this._onDataInit,{first:0,sortField:this.options.sortField,sortOrder:this.options.sortOrder}) }else{this.options.datasource.call(this,this._onDataInit) }}}}},_createRegularDatatable:function(){this.tableWrapper=$('<div class="pui-datatable-tablewrapper" />').appendTo(this.element); this.table=$("<table><thead></thead><tbody></tbody></table>").appendTo(this.tableWrapper); this.thead=this.table.children("thead"); this.tbody=this.table.children("tbody").addClass("pui-datatable-data") },_createScrollableDatatable:function(){var a=this; this.element.append('<div class="ui-widget-header pui-datatable-scrollable-header"><div class="pui-datatable-scrollable-header-box"><table><thead></thead></table></div></div>').append('<div class="pui-datatable-scrollable-body"><table><colgroup></colgroup><tbody></tbody></table></div></div>'); this.thead=this.element.find("> .pui-datatable-scrollable-header thead"); this.tbody=this.element.find("> .pui-datatable-scrollable-body tbody"); this.colgroup=this.tbody.prev(); if(this.options.columns){$.each(this.options.columns,function(c,b){$("<col></col>").appendTo(a.colgroup) }) }},_initialize:function(){var a=this; if(this.options.columns){$.each(this.options.columns,function(c,b){var d=$('<th class="ui-state-default"></th>').data("field",b.field).appendTo(a.thead); if(b.headerClass){d.addClass(b.headerClass) }if(b.headerStyle){d.attr("style",b.headerStyle) }if(b.headerText){d.text(b.headerText) }if(b.sortable){d.addClass("pui-sortable-column").data("order",0).append('<span class="pui-sortable-column-icon ui-icon ui-icon-carat-2-n-s"></span>') }}) }if(this.options.caption){this.element.prepend('<div class="pui-datatable-caption ui-widget-header">'+this.options.caption+"</div>") }if(this.options.paginator){this.options.paginator.paginate=function(b,c){a.paginate() }; this.options.paginator.totalRecords=this.options.paginator.totalRecords||this.data.length; this.paginator=$("<div></div>").insertAfter(this.tableWrapper).puipaginator(this.options.paginator) }if(this._isSortingEnabled()){this._initSorting() }if(this.options.selectionMode){this._initSelection() }if(this.options.sortField&&this.options.sortOrder){this._indicateInitialSortColumn(); this.sort(this.options.sortField,this.options.sortOrder) }else{this._renderData() }if(this.options.scrollable){this._initScrolling() }},_indicateInitialSortColumn:function(){var a=this.thead.children("th.pui-sortable-column"),b=this; $.each(a,function(c,d){var f=$(d),e=f.data(); if(b.options.sortField===e.field){var g=f.children(".pui-sortable-column-icon"); f.data("order",b.options.sortOrder).removeClass("ui-state-hover").addClass("ui-state-active"); if(b.options.sortOrder===-1){g.removeClass("ui-icon-triangle-1-n").addClass("ui-icon-triangle-1-s") }else{if(b.options.sortOrder===1){g.removeClass("ui-icon-triangle-1-s").addClass("ui-icon-triangle-1-n") }}}}) },_onDataInit:function(a){this.data=a; if(!this.data){this.data=[] }this._initialize() },_onDataUpdate:function(a){this.data=a; if(!this.data){this.data=[] }this._renderData() },_onLazyLoad:function(a){this.data=a; if(!this.data){this.data=[] }this._renderData() },_initSorting:function(){var b=this,a=this.thead.children("th.pui-sortable-column"); a.on("mouseover.puidatatable",function(){var c=$(this); if(!c.hasClass("ui-state-active")){c.addClass("ui-state-hover") }}).on("mouseout.puidatatable",function(){var c=$(this); if(!c.hasClass("ui-state-active")){c.removeClass("ui-state-hover") }}).on("click.puidatatable",function(){var f=$(this),d=f.data("field"),c=f.data("order"),e=(c===0)?1:(c*-1),g=f.children(".pui-sortable-column-icon"); f.siblings().filter(".ui-state-active").data("order",0).removeClass("ui-state-active").children("span.pui-sortable-column-icon").removeClass("ui-icon-triangle-1-n ui-icon-triangle-1-s"); b.options.sortField=d; b.options.sortOrder=e; b.sort(d,e); f.data("order",e).removeClass("ui-state-hover").addClass("ui-state-active"); if(e===-1){g.removeClass("ui-icon-triangle-1-n").addClass("ui-icon-triangle-1-s") }else{if(e===1){g.removeClass("ui-icon-triangle-1-s").addClass("ui-icon-triangle-1-n") }}}) },paginate:function(){if(this.options.lazy){if(this.options.selectionMode&&!this.options.keepSelectionInLazyMode){this.selection=[] }this.options.datasource.call(this,this._onLazyLoad,this._createStateMeta()) }else{this._renderData() }},sort:function(b,a){if(this.options.selectionMode){this.selection=[] }if(this.options.lazy){this.options.datasource.call(this,this._onLazyLoad,this._createStateMeta()) }else{this.data.sort(function(d,g){var f=d[b],e=g[b],c=(f<e)?-1:(f>e)?1:0; return(a*c) }); if(this.options.selectionMode){this.selection=[] }if(this.paginator){this.paginator.puipaginator("option","page",0) }this._renderData() }},sortByField:function(d,c){var f=d.name.toLowerCase(); var e=c.name.toLowerCase(); return((f<e)?-1:((f>e)?1:0)) },_renderData:function(){if(this.data){this.tbody.html(""); var l=this._getFirst(),e=this.options.lazy?0:l,n=this._getRows(); for(var d=e; d<(e+n); d++){var b=this.data[d]; if(b){var m=$('<tr class="ui-widget-content" />').appendTo(this.tbody),g=(d%2===0)?"pui-datatable-even":"pui-datatable-odd",h=d; m.addClass(g); if(this.options.lazy){h+=l }if(this.options.selectionMode&&PUI.inArray(this.selection,h)){m.addClass("ui-state-highlight") }for(var c=0; c<this.options.columns.length; c++){var a=$("<td />").appendTo(m),k=this.options.columns[c]; if(k.bodyClass){a.addClass(k.bodyClass) }if(k.bodyStyle){a.attr("style",k.bodyStyle) }if(k.content){var f=k.content.call(this,b); if($.type(f)==="string"){a.html(f) }else{a.append(f) }}else{a.text(b[k.field]) }}}}}},_getFirst:function(){if(this.paginator){var b=this.paginator.puipaginator("option","page"),a=this.paginator.puipaginator("option","rows"); return(b*a) }else{return 0 }},_getRows:function(){return this.paginator?this.paginator.puipaginator("option","rows"):this.data.length },_isSortingEnabled:function(){var b=this.options.columns; if(b){for(var a=0; a<b.length; a++){if(b[a].sortable){return true }}}return false },_initSelection:function(){var a=this; this.selection=[]; this.rowSelector="#"+this.id+" tbody.pui-datatable-data > tr.ui-widget-content:not(.ui-datatable-empty-message)"; if(this._isMultipleSelection()){this.originRowIndex=0; this.cursorIndex=null }$(document).off("mouseover.puidatatable mouseout.puidatatable click.puidatatable",this.rowSelector).on("mouseover.datatable",this.rowSelector,null,function(){var b=$(this); if(!b.hasClass("ui-state-highlight")){b.addClass("ui-state-hover") }}).on("mouseout.datatable",this.rowSelector,null,function(){var b=$(this); if(!b.hasClass("ui-state-highlight")){b.removeClass("ui-state-hover") }}).on("click.datatable",this.rowSelector,null,function(b){a._onRowClick(b,this) }) },_onRowClick:function(f,e){if(!$(f.target).is(":input,:button,a")){var h=$(e),d=h.hasClass("ui-state-highlight"),g=f.metaKey||f.ctrlKey,b=f.shiftKey; if(d&&g){this.unselectRow(h) }else{if(this._isSingleSelection()||(this._isMultipleSelection()&&!g&&!b)){if(this._isMultipleSelection()){var c=this.getSelection(); for(var a=0; a<c.length; a++){this._trigger("rowUnselect",null,c[a]) }}this.unselectAllRows() }this.selectRow(h,false,f) }PUI.clearSelection() }},_isSingleSelection:function(){return this.options.selectionMode==="single" },_isMultipleSelection:function(){return this.options.selectionMode==="multiple" },unselectAllRows:function(){this.tbody.children("tr.ui-state-highlight").removeClass("ui-state-highlight").attr("aria-selected",false); this.selection=[] },unselectRow:function(b,a){var c=this._getRowIndex(b); b.removeClass("ui-state-highlight").attr("aria-selected",false); this._removeSelection(c); if(!a){this._trigger("rowUnselect",null,this.data[c]) }},selectRow:function(d,a,b){var e=this._getRowIndex(d),c=this.data[e]; d.removeClass("ui-state-hover").addClass("ui-state-highlight").attr("aria-selected",true); this._addSelection(e); if(!a){if(this.options.lazy){c=this.data[e-this._getFirst()] }this._trigger("rowSelect",b,c) }},getSelection:function(){var c=this.options.lazy?this._getFirst():0,b=[]; for(var a=0; a<this.selection.length; a++){if(this.data.length>this.selection[a]-c&&this.selection[a]-c>0){b.push(this.data[this.selection[a]-c]) }}return b },_removeSelection:function(a){this.selection=$.grep(this.selection,function(b){return b!==a }) },_addSelection:function(a){if(!this._isSelected(a)){this.selection.push(a) }},_isSelected:function(a){return PUI.inArray(this.selection,a) },_getRowIndex:function(b){var a=b.index(); return this.options.paginator?this._getFirst()+a:a },_createStateMeta:function(){var a={first:this._getFirst(),rows:this._getRows(),sortField:this.options.sortField,sortOrder:this.options.sortOrder}; return a },_updateDatasource:function(a){this.options.datasource=a; this.reset(); if($.isArray(this.options.datasource)){this.data=this.options.datasource; this._renderData() }else{if($.type(this.options.datasource)==="function"){if(this.options.lazy){this.options.datasource.call(this,this._onDataUpdate,{first:0,sortField:this.options.sortField,sortorder:this.options.sortOrder}) }else{this.options.datasource.call(this,this._onDataUpdate) }}}},_setOption:function(a,b){if(a==="datasource"){this._updateDatasource(b) }else{$.Widget.prototype._setOption.apply(this,arguments) }},reset:function(){if(this.options.selectionMode){this.selection=[] }if(this.paginator){this.paginator.puipaginator("setPage",0,true) }this.thead.children("th.pui-sortable-column").data("order",0).filter(".ui-state-active").removeClass("ui-state-active").children("span.pui-sortable-column-icon").removeClass("ui-icon-triangle-1-n ui-icon-triangle-1-s") },_initScrolling:function(){this.scrollHeader=this.element.children(".pui-datatable-scrollable-header"); this.scrollBody=this.element.children(".pui-datatable-scrollable-body"); this.scrollHeaderBox=this.scrollHeader.children("div.pui-datatable-scrollable-header-box"); this.headerTable=this.scrollHeaderBox.children("table"); this.bodyTable=this.scrollBody.children("table"); this.percentageScrollHeight=this.options.scrollHeight&&(this.options.scrollHeight.indexOf("%")!==-1); this.percentageScrollWidth=this.options.scrollWidth&&(this.options.scrollWidth.indexOf("%")!==-1); var c=this,b=this.getScrollbarWidth()+"px"; if(this.options.scrollHeight){this.scrollBody.height(this.options.scrollHeight); this.scrollHeaderBox.css("margin-right",b); if(this.percentageScrollHeight){this.adjustScrollHeight() }}this.fixColumnWidths(); if(this.options.scrollWidth){if(this.percentageScrollWidth){this.adjustScrollWidth() }else{this.setScrollWidth(this.options.scrollWidth) }}this.scrollBody.on("scroll.dataTable",function(){var d=c.scrollBody.scrollLeft(); c.scrollHeaderBox.css("margin-left",-d) }); this.scrollHeader.on("scroll.dataTable",function(){c.scrollHeader.scrollLeft(0) }); var a="resize."+this.id; $(window).unbind(a).bind(a,function(){if(c.element.is(":visible")){if(c.percentageScrollHeight){c.adjustScrollHeight() }if(c.percentageScrollWidth){c.adjustScrollWidth() }}}) },adjustScrollHeight:function(){var c=this.element.parent().innerHeight()*(parseInt(this.options.scrollHeight)/100),e=this.element.children(".pui-datatable-caption").outerHeight(true),b=this.scrollHeader.outerHeight(true),d=this.paginator?this.paginator.getContainerHeight(true):0,a=(c-(b+d+e)); this.scrollBody.height(a) },adjustScrollWidth:function(){var a=parseInt((this.element.parent().innerWidth()*(parseInt(this.options.scrollWidth)/100))); this.setScrollWidth(a) },setScrollWidth:function(a){this.scrollHeader.width(a); this.scrollBody.css("margin-right",0).width(a); this.element.width(a) },getScrollbarWidth:function(){if(!this.scrollbarWidth){this.scrollbarWidth=PUI.browser.webkit?"15":PUI.calculateScrollbarWidth() }return this.scrollbarWidth },fixColumnWidths:function(){var a=this; if(!this.columnWidthsFixed){if(this.options.scrollable){this.thead.children("th").each(function(){var f=$(this),c=f.index(),e=f.width(),b=f.innerWidth(),d=b+1; f.width(e); a.colgroup.children().eq(c).width(d) }) }else{this.element.find("> .pui-datatable-tablewrapper > table > thead > tr > th").each(function(){var b=$(this); b.width(b.width()) }) }this.columnWidthsFixed=true }}}) });
JavaScript
$(function(){$.widget("primeui.puiterminal",{options:{welcomeMessage:"",prompt:"prime $",handler:null},_create:function(){this.element.addClass("pui-terminal ui-widget ui-widget-content ui-corner-all").append("<div>"+this.options.welcomeMessage+"</div>").append('<div class="pui-terminal-content"></div>').append('<div><span class="pui-terminal-prompt">'+this.options.prompt+'</span><input type="text" class="pui-terminal-input" autocomplete="off"></div>'); this.promptContainer=this.element.find("> div:last-child > span.pui-terminal-prompt"); this.content=this.element.children(".pui-terminal-content"); this.input=this.promptContainer.next(); this.commands=[]; this.commandIndex=0; this._bindEvents() },_bindEvents:function(){var a=this; this.input.on("keydown.terminal",function(c){var b=$.ui.keyCode; switch(c.which){case b.UP:if(a.commandIndex>0){a.input.val(a.commands[--a.commandIndex]) }c.preventDefault(); break; case b.DOWN:if(a.commandIndex<(a.commands.length-1)){a.input.val(a.commands[++a.commandIndex]) }else{a.commandIndex=a.commands.length; a.input.val("") }c.preventDefault(); break; case b.ENTER:case b.NUMPAD_ENTER:a._processCommand(); c.preventDefault(); break }}) },_processCommand:function(){var a=this.input.val(); this.commands.push(); this.commandIndex++; if(this.options.handler&&$.type(this.options.handler)==="function"){this.options.handler.call(this,a,this._updateContent) }},_updateContent:function(a){var b=$("<div></div>"); b.append("<span>"+this.options.prompt+'</span><span class="pui-terminal-command">'+this.input.val()+"</span>").append("<div>"+a+"</div>").appendTo(this.content); this.input.val(""); this.element.scrollTop(this.content.height()) },clear:function(){this.content.html(""); this.input.val("") }}) });
JavaScript
$(function(){$.widget("primeui.puibutton",{options:{value:null,icon:null,iconPos:"left",click:null},_create:function(){var b=this.element,d=b.text(),e=this.options.value||(d===""?"pui-button":d),c=b.prop("disabled"),a=null; if(this.options.icon){a=(e==="pui-button")?"pui-button-icon-only":"pui-button-text-icon-"+this.options.iconPos }else{a="pui-button-text-only" }if(c){a+=" ui-state-disabled" }this.element.addClass("pui-button ui-widget ui-state-default ui-corner-all "+a).text(""); if(this.options.icon){this.element.append('<span class="pui-button-icon-'+this.options.iconPos+" ui-icon "+this.options.icon+'" />') }this.element.append('<span class="pui-button-text">'+e+"</span>"); b.attr("role","button").attr("aria-disabled",c); if(!c){this._bindEvents() }},_bindEvents:function(){var a=this.element,b=this; a.on("mouseover.puibutton",function(){if(!a.prop("disabled")){a.addClass("ui-state-hover") }}).on("mouseout.puibutton",function(){$(this).removeClass("ui-state-active ui-state-hover") }).on("mousedown.puibutton",function(){if(!a.hasClass("ui-state-disabled")){a.addClass("ui-state-active").removeClass("ui-state-hover") }}).on("mouseup.puibutton",function(c){a.removeClass("ui-state-active").addClass("ui-state-hover"); b._trigger("click",c) }).on("focus.puibutton",function(){a.addClass("ui-state-focus") }).on("blur.puibutton",function(){a.removeClass("ui-state-focus") }).on("keydown.puibutton",function(c){if(c.keyCode==$.ui.keyCode.SPACE||c.keyCode==$.ui.keyCode.ENTER||c.keyCode==$.ui.keyCode.NUMPAD_ENTER){a.addClass("ui-state-active") }}).on("keyup.puibutton",function(){a.removeClass("ui-state-active") }); return this },_unbindEvents:function(){this.element.off("mouseover.puibutton mouseout.puibutton mousedown.puibutton mouseup.puibutton focus.puibutton blur.puibutton keydown.puibutton keyup.puibutton") },disable:function(){this._unbindEvents(); this.element.attr({disabled:"disabled","aria-disabled":true}).addClass("ui-state-disabled") },enable:function(){this._bindEvents(); this.element.removeAttr("disabled").attr("aria-disabled",false).removeClass("ui-state-disabled") }}) });
JavaScript
$(function(){$.widget("primeui.puipassword",{options:{promptLabel:"Please enter a password",weakLabel:"Weak",goodLabel:"Medium",strongLabel:"Strong",inline:false},_create:function(){this.element.puiinputtext().addClass("pui-password"); if(!this.element.prop(":disabled")){var a='<div class="pui-password-panel ui-widget ui-state-highlight ui-corner-all ui-helper-hidden">'; a+='<div class="pui-password-meter" style="background-position:0pt 0pt">&nbsp;</div>'; a+='<div class="pui-password-info">'+this.options.promptLabel+"</div>"; a+="</div>"; this.panel=$(a).insertAfter(this.element); this.meter=this.panel.children("div.pui-password-meter"); this.infoText=this.panel.children("div.pui-password-info"); if(this.options.inline){this.panel.addClass("pui-password-panel-inline") }else{this.panel.addClass("pui-password-panel-overlay").appendTo("body") }this._bindEvents() }},_destroy:function(){this.panel.remove() },_bindEvents:function(){var b=this; this.element.on("focus.puipassword",function(){b.show() }).on("blur.puipassword",function(){b.hide() }).on("keyup.puipassword",function(){var e=b.element.val(),c=null,d=null; if(e.length===0){c=b.options.promptLabel; d="0px 0px" }else{var f=b._testStrength(b.element.val()); if(f<30){c=b.options.weakLabel; d="0px -10px" }else{if(f>=30&&f<80){c=b.options.goodLabel; d="0px -20px" }else{if(f>=80){c=b.options.strongLabel; d="0px -30px" }}}}b.meter.css("background-position",d); b.infoText.text(c) }); if(!this.options.inline){var a="resize."+this.element.attr("id"); $(window).unbind(a).bind(a,function(){if(b.panel.is(":visible")){b.align() }}) }},_unbindEvents:function(){this.element.off("focus.puipassword blur.puipassword keyup.puipassword") },_testStrength:function(d){var b=0,c=0,a=this; c=d.match("[0-9]"); b+=a._normalize(c?c.length:1/4,1)*25; c=d.match("[a-zA-Z]"); b+=a._normalize(c?c.length:1/2,3)*10; c=d.match("[!@#$%^&*?_~.,;=]"); b+=a._normalize(c?c.length:1/6,1)*35; c=d.match("[A-Z]"); b+=a._normalize(c?c.length:1/6,1)*30; b*=d.length/8; return b>100?100:b },_normalize:function(a,c){var b=a-c; if(b<=0){return a/c }else{return 1+0.5*(a/(a+c/4)) }},align:function(){this.panel.css({left:"",top:"","z-index":++PUI.zindex}).position({my:"left top",at:"right top",of:this.element}) },show:function(){if(!this.options.inline){this.align(); this.panel.fadeIn() }else{this.panel.slideDown() }},hide:function(){if(this.options.inline){this.panel.slideUp() }else{this.panel.fadeOut() }},disable:function(){this.element.puiinputtext("disable"); this._unbindEvents() },enable:function(){this.element.puiinputtext("enable"); this._bindEvents() }}) });
JavaScript
$(function(){$.widget("primeui.puipanel",{options:{toggleable:false,toggleDuration:"normal",toggleOrientation:"vertical",collapsed:false,closable:false,closeDuration:"normal"},_create:function(){this.element.addClass("pui-panel ui-widget ui-widget-content ui-corner-all").contents().wrapAll('<div class="pui-panel-content ui-widget-content" />'); var c=this.element.attr("title"); if(c){this.element.prepend('<div class="pui-panel-titlebar ui-widget-header ui-helper-clearfix ui-corner-all"><span class="ui-panel-title">'+c+"</span></div>").removeAttr("title") }this.header=this.element.children("div.pui-panel-titlebar"); this.title=this.header.children("span.ui-panel-title"); this.content=this.element.children("div.pui-panel-content"); var b=this; if(this.options.closable){this.closer=$('<a class="pui-panel-titlebar-icon ui-corner-all ui-state-default" href="#"><span class="ui-icon ui-icon-closethick"></span></a>').appendTo(this.header).on("click.puipanel",function(d){b.close(); d.preventDefault() }) }if(this.options.toggleable){var a=this.options.collapsed?"ui-icon-plusthick":"ui-icon-minusthick"; this.toggler=$('<a class="pui-panel-titlebar-icon ui-corner-all ui-state-default" href="#"><span class="ui-icon '+a+'"></span></a>').appendTo(this.header).on("click.puipanel",function(d){b.toggle(); d.preventDefault() }); if(this.options.collapsed){this.content.hide() }}this._bindEvents() },_bindEvents:function(){this.header.find("a.pui-panel-titlebar-icon").on("hover.puipanel",function(){$(this).toggleClass("ui-state-hover") }) },close:function(){var a=this; this._trigger("beforeClose",null); this.element.fadeOut(this.options.closeDuration,function(){a._trigger("afterClose",null) }) },toggle:function(){if(this.options.collapsed){this.expand() }else{this.collapse() }},expand:function(){this.toggler.children("span.ui-icon").removeClass("ui-icon-plusthick").addClass("ui-icon-minusthick"); if(this.options.toggleOrientation==="vertical"){this._slideDown() }else{if(this.options.toggleOrientation==="horizontal"){this._slideRight() }}},collapse:function(){this.toggler.children("span.ui-icon").removeClass("ui-icon-minusthick").addClass("ui-icon-plusthick"); if(this.options.toggleOrientation==="vertical"){this._slideUp() }else{if(this.options.toggleOrientation==="horizontal"){this._slideLeft() }}},_slideUp:function(){var a=this; this._trigger("beforeCollapse"); this.content.slideUp(this.options.toggleDuration,"easeInOutCirc",function(){a._trigger("afterCollapse"); a.options.collapsed=!a.options.collapsed }) },_slideDown:function(){var a=this; this._trigger("beforeExpand"); this.content.slideDown(this.options.toggleDuration,"easeInOutCirc",function(){a._trigger("afterExpand"); a.options.collapsed=!a.options.collapsed }) },_slideLeft:function(){var a=this; this.originalWidth=this.element.width(); this.title.hide(); this.toggler.hide(); this.content.hide(); this.element.animate({width:"42px"},this.options.toggleSpeed,"easeInOutCirc",function(){a.toggler.show(); a.element.addClass("pui-panel-collapsed-h"); a.options.collapsed=!a.options.collapsed }) },_slideRight:function(){var b=this,a=this.originalWidth||"100%"; this.toggler.hide(); this.element.animate({width:a},this.options.toggleSpeed,"easeInOutCirc",function(){b.element.removeClass("pui-panel-collapsed-h"); b.title.show(); b.toggler.show(); b.options.collapsed=!b.options.collapsed; b.content.css({visibility:"visible",display:"block",height:"auto"}) }) }}) });
JavaScript
$(function(){$.widget("primeui.puitooltip",{options:{showEvent:"mouseover",hideEvent:"mouseout",showEffect:"fade",hideEffect:null,showEffectSpeed:"normal",hideEffectSpeed:"normal",my:"left top",at:"right bottom",showDelay:150},_create:function(){this.options.showEvent=this.options.showEvent+".puitooltip"; this.options.hideEvent=this.options.hideEvent+".puitooltip"; if(this.element.get(0)===document){this._bindGlobal() }else{this._bindTarget() }},_bindGlobal:function(){this.container=$('<div class="pui-tooltip pui-tooltip-global ui-widget ui-widget-content ui-corner-all pui-shadow" />').appendTo(document.body); this.globalSelector="a,:input,:button,img"; var b=this; $(document).off(this.options.showEvent+" "+this.options.hideEvent,this.globalSelector).on(this.options.showEvent,this.globalSelector,null,function(){var c=$(this),d=c.attr("title"); if(d){b.container.text(d); b.globalTitle=d; b.target=c; c.attr("title",""); b.show() }}).on(this.options.hideEvent,this.globalSelector,null,function(){var c=$(this); if(b.globalTitle){b.container.hide(); c.attr("title",b.globalTitle); b.globalTitle=null; b.target=null }}); var a="resize.puitooltip"; $(window).unbind(a).bind(a,function(){if(b.container.is(":visible")){b._align() }}) },_bindTarget:function(){this.container=$('<div class="pui-tooltip ui-widget ui-widget-content ui-corner-all pui-shadow" />').appendTo(document.body); var b=this; this.element.off(this.options.showEvent+" "+this.options.hideEvent).on(this.options.showEvent,function(){b.show() }).on(this.options.hideEvent,function(){b.hide() }); this.container.html(this.options.content); this.element.removeAttr("title"); this.target=this.element; var a="resize."+this.element.attr("id"); $(window).unbind(a).bind(a,function(){if(b.container.is(":visible")){b._align() }}) },_align:function(){this.container.css({left:"",top:"","z-index":++PUI.zindex}).position({my:this.options.my,at:this.options.at,of:this.target}) },show:function(){var a=this; this.timeout=window.setTimeout(function(){a._align(); a.container.show(a.options.showEffect,{},a.options.showEffectSpeed) },this.options.showDelay) },hide:function(){window.clearTimeout(this.timeout); this.container.hide(this.options.hideEffect,{},this.options.hideEffectSpeed,function(){$(this).css("z-index","") }) }}) });
JavaScript
$(function(){$.widget("primeui.puitreetable",{options:{nodes:null,lazy:false,selectionMode:null},_create:function(){this.id=this.element.attr("id"); if(!this.id){this.id=this.element.uniqueId().attr("id") }this.element.addClass("pui-treetable ui-widget"); this.tableWrapper=$('<div class="pui-treetable-tablewrapper" />').appendTo(this.element); this.table=$("<table><thead></thead><tbody></tbody></table>").appendTo(this.tableWrapper); this.thead=this.table.children("thead"); this.tbody=this.table.children("tbody").addClass("pui-treetable-data"); var a=this; if(this.options.columns){$.each(this.options.columns,function(c,b){var d=$('<th class="ui-state-default"></th>').data("field",b.field).appendTo(a.thead); if(b.headerClass){d.addClass(b.headerClass) }if(b.headerStyle){d.attr("style",b.headerStyle) }if(b.headerText){d.text(b.headerText) }}) }if(this.options.header){this.element.prepend('<div class="pui-treetable-header ui-widget-header ui-corner-top">'+this.options.header+"</div>") }if(this.options.footer){this.element.append('<div class="pui-treetable-footer ui-widget-header ui-corner-bottom">'+this.options.footer+"</div>") }if($.isArray(this.options.nodes)){this._renderNodes(this.options.nodes,null,true) }else{if($.type(this.options.nodes)==="function"){this.options.nodes.call(this,{},this._initData) }else{throw"Unsupported type. nodes option can be either an array or a function" }}this._bindEvents() },_initData:function(a){this._renderNodes(a,null,true) },_renderNodes:function(a,r,l){for(var h=0; h<a.length; h++){var d=a[h],c=d.data,n=this.options.lazy?d.leaf:!(d.children&&d.children.length),q=$('<tr class="ui-widget-content"></tr>'),g=r?r.data("depth")+1:0,o=r?r.data("rowkey"):null,b=o?o+"_"+h:h.toString(); q.data({depth:g,rowkey:b,parentrowkey:o,puidata:c,}); if(!l){q.addClass("ui-helper-hidden") }for(var f=0; f<this.options.columns.length; f++){var e=$("<td />").appendTo(q),p=this.options.columns[f]; if(p.bodyClass){e.addClass(p.bodyClass) }if(p.bodyStyle){e.attr("style",p.bodyStyle) }if(f===0){var k=$('<span class="pui-treetable-toggler ui-icon ui-icon-triangle-1-e ui-c"></span>'); k.css("margin-left",g*16+"px"); if(n){k.css("visibility","hidden") }k.appendTo(e) }if(p.content){var m=p.content.call(this,c); if($.type(m)==="string"){e.text(m) }else{e.append(m) }}else{e.append(c[p.field]) }}if(r){q.insertAfter(r) }else{q.appendTo(this.tbody) }if(!n){this._renderNodes(d.children,q,d.expanded) }}},_bindEvents:function(){var c=this,a="> tr > td:first-child > .pui-treetable-toggler"; this.tbody.off("click.puitreetable",a).on("click.puitreetable",a,null,function(f){var d=$(this),g=d.closest("tr"); if(!g.data("processing")){g.data("processing",true); if(d.hasClass("ui-icon-triangle-1-e")){c.expandNode(g) }else{c.collapseNode(g) }}}); if(this.options.selectionMode){this.selection=[]; var b="> tr"; this.tbody.off("mouseover.puitreetable mouseout.puitreetable click.puitreetable",b).on("mouseover.puitreetable",b,null,function(f){var d=$(this); if(!d.hasClass("ui-state-highlight")){d.addClass("ui-state-hover") }}).on("mouseout.puitreetable",b,null,function(f){var d=$(this); if(!d.hasClass("ui-state-highlight")){d.removeClass("ui-state-hover") }}).on("click.puitreetable",b,null,function(d){c.onRowClick(d,$(this)) }) }},expandNode:function(a){this._trigger("beforeExpand",null,{node:a,data:a.data("puidata")}); if(this.options.lazy&&!a.data("puiloaded")){this.options.nodes.call(this,{node:a,data:a.data("puidata")},this._handleNodeData) }else{this._showNodeChildren(a,false); this._trigger("afterExpand",null,{node:a,data:a.data("puidata")}) }},_handleNodeData:function(b,a){this._renderNodes(b,a,true); this._showNodeChildren(a,false); a.data("puiloaded",true); this._trigger("afterExpand",null,{node:a,data:a.data("puidata")}) },_showNodeChildren:function(d,c){if(!c){d.data("expanded",true).attr("aria-expanded",true).find(".pui-treetable-toggler:first").addClass("ui-icon-triangle-1-s").removeClass("ui-icon-triangle-1-e") }var b=this._getChildren(d); for(var a=0; a<b.length; a++){var e=b[a]; e.removeClass("ui-helper-hidden"); if(e.data("expanded")){this._showNodeChildren(e,true) }}d.data("processing",false) },collapseNode:function(a){this._trigger("beforeCollapse",null,{node:a,data:a.data("puidata")}); this._hideNodeChildren(a,false); a.data("processing",false); this._trigger("afterCollapse",null,{node:a,data:a.data("puidata")}) },_hideNodeChildren:function(d,c){if(!c){d.data("expanded",false).attr("aria-expanded",false).find(".pui-treetable-toggler:first").addClass("ui-icon-triangle-1-e").removeClass("ui-icon-triangle-1-s") }var b=this._getChildren(d); for(var a=0; a<b.length; a++){var e=b[a]; e.addClass("ui-helper-hidden"); if(e.data("expanded")){this._hideNodeChildren(e,true) }}},onRowClick:function(b,d){if($(b.target).is("td,span:not(.ui-c)")){var a=d.hasClass("ui-state-highlight"),c=b.metaKey||b.ctrlKey; if(a&&c){this.unselectNode(d) }else{if(this.isSingleSelection()||(this.isMultipleSelection()&&!c)){this.unselectAllNodes() }this.selectNode(d) }PUI.clearSelection() }},selectNode:function(b,a){b.removeClass("ui-state-hover").addClass("ui-state-highlight").attr("aria-selected",true); if(!a){this._trigger("nodeSelect",{},{node:b,data:b.data("puidata")}) }},unselectNode:function(b,a){b.removeClass("ui-state-highlight").attr("aria-selected",false); if(!a){this._trigger("nodeUnselect",{},{node:b,data:b.data("puidata")}) }},unselectAllNodes:function(){var b=this.tbody.children("tr.ui-state-highlight"); for(var a=0; a<b.length; a++){this.unselectNode(b.eq(a),true) }},isSingleSelection:function(){return this.options.selectionMode==="single" },isMultipleSelection:function(){return this.options.selectionMode==="multiple" },_getChildren:function(f){var c=f.data("rowkey"),g=f.nextAll(),e=[]; for(var d=0; d<g.length; d++){var a=g.eq(d),b=a.data("parentrowkey"); if(b===c){e.push(a) }}return e }}) });
JavaScript
var PUI={zindex:1000,scrollInView:function(b,e){var h=parseFloat(b.css("borderTopWidth"))||0,d=parseFloat(b.css("paddingTop"))||0,f=e.offset().top-b.offset().top-h-d,a=b.scrollTop(),c=b.height(),g=e.outerHeight(true); if(f<0){b.scrollTop(a+f) }else{if((f+g)>c){b.scrollTop(a+f-c+g) }}},isIE:function(a){return(this.browser.msie&&parseInt(this.browser.version,10)===a) },escapeRegExp:function(a){return a.replace(/([.?*+^$[\]\\(){}|-])/g,"\\$1") },escapeHTML:function(a){return a.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;") },clearSelection:function(){if(window.getSelection){if(window.getSelection().empty){window.getSelection().empty() }else{if(window.getSelection().removeAllRanges){window.getSelection().removeAllRanges() }}}else{if(document.selection&&document.selection.empty){document.selection.empty() }}},inArray:function(a,c){for(var b=0; b<a.length; b++){if(a[b]===c){return true }}return false },calculateScrollbarWidth:function(){if(!this.scrollbarWidth){if(this.browser.msie){var c=$('<textarea cols="10" rows="2"></textarea>').css({position:"absolute",top:-1000,left:-1000}).appendTo("body"),b=$('<textarea cols="10" rows="2" style="overflow: hidden;"></textarea>').css({position:"absolute",top:-1000,left:-1000}).appendTo("body"); this.scrollbarWidth=c.width()-b.width(); c.add(b).remove() }else{var a=$("<div />").css({width:100,height:100,overflow:"auto",position:"absolute",top:-1000,left:-1000}).prependTo("body").append("<div />").find("div").css({width:"100%",height:200}); this.scrollbarWidth=100-a.width(); a.parent().remove() }}return this.scrollbarWidth },resolveUserAgent:function(c){var d=c.toLowerCase(),b=/(chrome)[ \/]([\w.]+)/.exec(d)||/(webkit)[ \/]([\w.]+)/.exec(d)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(d)||/(msie) ([\w.]+)/.exec(d)||c.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(d)||[],e={browser:b[1]||"",version:b[2]||"0"},a={}; if(e.browser){a[e.browser]=true; a.version=e.version }if(a.chrome){a.webkit=true }else{if(a.webkit){a.safari=true }}this.browser=a }}; PUI.resolveUserAgent(navigator.userAgent);
JavaScript
$(function(){$.widget("primeui.puiprogressbar",{options:{value:0,labelTemplate:"{value}%",complete:null,easing:"easeInOutCirc",effectSpeed:"normal",showLabel:true},_create:function(){this.element.addClass("pui-progressbar ui-widget ui-widget-content ui-corner-all").append('<div class="pui-progressbar-value ui-widget-header ui-corner-all"></div>').append('<div class="pui-progressbar-label"></div>'); this.jqValue=this.element.children(".pui-progressbar-value"); this.jqLabel=this.element.children(".pui-progressbar-label"); if(this.options.value!==0){this._setValue(this.options.value,false) }this.enableARIA() },_setValue:function(d,b){var c=(b===undefined||b)?true:false; if(d>=0&&d<=100){if(d===0){this.jqValue.hide().css("width","0%").removeClass("ui-corner-right"); this.jqLabel.hide() }else{if(c){this.jqValue.show().animate({width:d+"%"},this.options.effectSpeed,this.options.easing) }else{this.jqValue.show().css("width",d+"%") }if(this.options.labelTemplate&&this.options.showLabel){var a=this.options.labelTemplate.replace(/{value}/gi,d); this.jqLabel.html(a).show() }if(d===100){this._trigger("complete") }}this.options.value=d; this.element.attr("aria-valuenow",d) }},_getValue:function(){return this.options.value },enableARIA:function(){this.element.attr("role","progressbar").attr("aria-valuemin",0).attr("aria-valuenow",this.options.value).attr("aria-valuemax",100) },_setOption:function(a,b){if(a==="value"){this._setValue(b) }$.Widget.prototype._setOption.apply(this,arguments) },_destroy:function(){}}) });
JavaScript
$(function(){$.widget("primeui.puidropdown",{options:{effect:"fade",effectSpeed:"normal",filter:false,filterMatchMode:"startsWith",caseSensitiveFilter:false,filterFunction:null,data:null,content:null,scrollHeight:200},_create:function(){if(this.options.data){for(var c=0; c<this.options.data.length; c++){var a=this.options.data[c]; if(a.label){this.element.append('<option value="'+a.value+'">'+a.label+"</option>") }else{this.element.append('<option value="'+a+'">'+a+"</option>") }}}this.element.wrap('<div class="pui-dropdown ui-widget ui-state-default ui-corner-all ui-helper-clearfix" />').wrap('<div class="ui-helper-hidden-accessible" />'); this.container=this.element.closest(".pui-dropdown"); this.focusElementContainer=$('<div class="ui-helper-hidden-accessible"><input type="text" /></div>').appendTo(this.container); this.focusElement=this.focusElementContainer.children("input"); this.label=this.options.editable?$('<input type="text" class="pui-dropdown-label pui-inputtext ui-corner-all"">'):$('<label class="pui-dropdown-label pui-inputtext ui-corner-all"/>'); this.label.appendTo(this.container); this.menuIcon=$('<div class="pui-dropdown-trigger ui-state-default ui-corner-right"><span class="ui-icon ui-icon-triangle-1-s"></span></div>').appendTo(this.container); this.panel=$('<div class="pui-dropdown-panel ui-widget-content ui-corner-all ui-helper-hidden pui-shadow" />').appendTo(document.body); this.itemsWrapper=$('<div class="pui-dropdown-items-wrapper" />').appendTo(this.panel); this.itemsContainer=$('<ul class="pui-dropdown-items pui-dropdown-list ui-widget-content ui-widget ui-corner-all ui-helper-reset"></ul>').appendTo(this.itemsWrapper); this.disabled=this.element.prop("disabled"); this.choices=this.element.children("option"); this.optGroupsSize=this.itemsContainer.children("li.puiselectonemenu-item-group").length; if(this.options.filter){this.filterContainer=$('<div class="pui-dropdown-filter-container" />').prependTo(this.panel); this.filterInput=$('<input type="text" autocomplete="off" class="pui-dropdown-filter pui-inputtext ui-widget ui-state-default ui-corner-all" />').appendTo(this.filterContainer); this.filterContainer.append('<span class="ui-icon ui-icon-search"></span>') }this._generateItems(); var e=this,d=this.choices.filter(":selected"); this.choices.filter(":disabled").each(function(){e.items.eq($(this).index()).addClass("ui-state-disabled") }); this.triggers=this.options.editable?this.menuIcon:this.container.children(".pui-dropdown-trigger, .pui-dropdown-label"); if(this.options.editable){var b=this.label.val(); if(b===d.text()){this._highlightItem(this.items.eq(d.index())) }else{this.items.eq(0).addClass("ui-state-highlight"); this.customInput=true; this.customInputVal=b }}else{this._highlightItem(this.items.eq(d.index())) }if(!this.disabled){this._bindEvents(); this._bindConstantEvents() }this._initDimensions() },_generateItems:function(){for(var a=0; a<this.choices.length; a++){var b=this.choices.eq(a),d=b.text(),c=this.options.content?this.options.content.call(this,this.options.data[a]):d; this.itemsContainer.append('<li data-label="'+d+'" class="pui-dropdown-item pui-dropdown-list-item ui-corner-all">'+c+"</li>") }this.items=this.itemsContainer.children(".pui-dropdown-item") },_bindEvents:function(){var a=this; this.items.filter(":not(.ui-state-disabled)").each(function(b,c){a._bindItemEvents($(c)) }); this.triggers.on("mouseenter.puidropdown",function(){if(!a.container.hasClass("ui-state-focus")){a.container.addClass("ui-state-hover"); a.menuIcon.addClass("ui-state-hover") }}).on("mouseleave.puidropdown",function(){a.container.removeClass("ui-state-hover"); a.menuIcon.removeClass("ui-state-hover") }).on("click.puidropdown",function(b){if(a.panel.is(":hidden")){a._show() }else{a._hide(); a._revert() }a.container.removeClass("ui-state-hover"); a.menuIcon.removeClass("ui-state-hover"); a.focusElement.trigger("focus.puidropdown"); b.preventDefault() }); this.focusElement.on("focus.puidropdown",function(){a.container.addClass("ui-state-focus"); a.menuIcon.addClass("ui-state-focus") }).on("blur.puidropdown",function(){a.container.removeClass("ui-state-focus"); a.menuIcon.removeClass("ui-state-focus") }); if(this.options.editable){this.label.on("change.pui-dropdown",function(){a._triggerChange(true); a.customInput=true; a.customInputVal=$(this).val(); a.items.filter(".ui-state-highlight").removeClass("ui-state-highlight"); a.items.eq(0).addClass("ui-state-highlight") }) }this._bindKeyEvents(); if(this.options.filter){this._setupFilterMatcher(); this.filterInput.puiinputtext(); this.filterInput.on("keyup.pui-dropdown",function(){a._filter($(this).val()) }) }},_bindItemEvents:function(a){var b=this; a.on("mouseover.puidropdown",function(){var c=$(this); if(!c.hasClass("ui-state-highlight")){$(this).addClass("ui-state-hover") }}).on("mouseout.puidropdown",function(){$(this).removeClass("ui-state-hover") }).on("click.puidropdown",function(){b._selectItem($(this)) }) },_bindConstantEvents:function(){var a=this; $(document.body).bind("mousedown.pui-dropdown",function(b){if(a.panel.is(":hidden")){return }var c=a.panel.offset(); if(b.target===a.label.get(0)||b.target===a.menuIcon.get(0)||b.target===a.menuIcon.children().get(0)){return }if(b.pageX<c.left||b.pageX>c.left+a.panel.width()||b.pageY<c.top||b.pageY>c.top+a.panel.height()){a._hide(); a._revert() }}); this.resizeNS="resize."+this.id; this._unbindResize(); this._bindResize() },_bindKeyEvents:function(){var a=this; this.focusElement.on("keydown.puiselectonemenu",function(h){var l=$.ui.keyCode,j=h.which,d; switch(j){case l.UP:case l.LEFT:d=a._getActiveItem(); var b=d.prevAll(":not(.ui-state-disabled,.ui-selectonemenu-item-group):first"); if(b.length==1){if(a.panel.is(":hidden")){a._selectItem(b) }else{a._highlightItem(b); PUI.scrollInView(a.itemsWrapper,b) }}h.preventDefault(); break; case l.DOWN:case l.RIGHT:d=a._getActiveItem(); var f=d.nextAll(":not(.ui-state-disabled,.ui-selectonemenu-item-group):first"); if(f.length==1){if(a.panel.is(":hidden")){if(h.altKey){a._show() }else{a._selectItem(f) }}else{a._highlightItem(f); PUI.scrollInView(a.itemsWrapper,f) }}h.preventDefault(); break; case l.ENTER:case l.NUMPAD_ENTER:if(a.panel.is(":hidden")){a._show() }else{a._selectItem(a._getActiveItem()) }h.preventDefault(); break; case l.TAB:if(a.panel.is(":visible")){a._revert(); a._hide() }break; case l.ESCAPE:if(a.panel.is(":visible")){a._revert(); a._hide() }break; default:var c=String.fromCharCode((96<=j&&j<=105)?j-48:j),i=a.items.filter(".ui-state-highlight"); var g=a._search(c,i.index()+1,a.options.length); if(!g){g=a._search(c,0,i.index()) }if(g){if(a.panel.is(":hidden")){a._selectItem(g) }else{a._highlightItem(g); PUI.scrollInView(a.itemsWrapper,g) }}break }}) },_initDimensions:function(){var b=this.element.attr("style"); if(!b||b.indexOf("width")==-1){this.container.width(this.element.outerWidth(true)+5) }else{this.container.attr("style",b) }this.label.width(this.container.width()-this.menuIcon.width()); var a=this.container.innerWidth(); if(this.panel.outerWidth()<a){this.panel.width(a) }this.element.parent().addClass("ui-helper-hidden").removeClass("ui-helper-hidden-accessible"); if(this.options.scrollHeight&&this.panel.outerHeight()>this.options.scrollHeight){this.itemsWrapper.height(this.options.scrollHeight) }},_selectItem:function(f,b){var e=this.choices.eq(this._resolveItemIndex(f)),d=this.choices.filter(":selected"),a=e.val()==d.val(),c=null; if(this.options.editable){c=(!a)||(e.text()!=this.label.val()) }else{c=!a }if(c){this._highlightItem(f); this.element.val(e.val()); this._triggerChange(); if(this.options.editable){this.customInput=false }}if(!b){this.focusElement.trigger("focus.puidropdown") }if(this.panel.is(":visible")){this._hide() }},_highlightItem:function(a){this.items.filter(".ui-state-highlight").removeClass("ui-state-highlight"); a.addClass("ui-state-highlight"); this._setLabel(a.data("label")) },_triggerChange:function(a){this.changed=false; if(this.options.change){this._trigger("change") }if(!a){this.value=this.choices.filter(":selected").val() }},_resolveItemIndex:function(a){if(this.optGroupsSize===0){return a.index() }else{return a.index()-a.prevAll("li.pui-dropdown-item-group").length }},_setLabel:function(a){if(this.options.editable){this.label.val(a) }else{if(a==="&nbsp;"){this.label.html("&nbsp;") }else{this.label.text(a) }}},_bindResize:function(){var a=this; $(window).bind(this.resizeNS,function(b){if(a.panel.is(":visible")){a._alignPanel() }}) },_unbindResize:function(){$(window).unbind(this.resizeNS) },_unbindEvents:function(){this.items.off(); this.triggers.off(); this.label.off() },_alignPanel:function(){this.panel.css({left:"",top:""}).position({my:"left top",at:"left bottom",of:this.container}) },_show:function(){this._alignPanel(); this.panel.css("z-index",++PUI.zindex); if(this.options.effect!="none"){this.panel.show(this.options.effect,{},this.options.effectSpeed) }else{this.panel.show() }this.preShowValue=this.choices.filter(":selected") },_hide:function(){this.panel.hide() },_revert:function(){if(this.options.editable&&this.customInput){this._setLabel(this.customInputVal); this.items.filter(".ui-state-active").removeClass("ui-state-active"); this.items.eq(0).addClass("ui-state-active") }else{this._highlightItem(this.items.eq(this.preShowValue.index())) }},_getActiveItem:function(){return this.items.filter(".ui-state-highlight") },_setupFilterMatcher:function(){this.filterMatchers={startsWith:this._startsWithFilter,contains:this._containsFilter,endsWith:this._endsWithFilter,custom:this.options.filterFunction}; this.filterMatcher=this.filterMatchers[this.options.filterMatchMode] },_startsWithFilter:function(b,a){return b.indexOf(a)===0 },_containsFilter:function(b,a){return b.indexOf(a)!==-1 },_endsWithFilter:function(b,a){return b.indexOf(a,b.length-a.length)!==-1 },_filter:function(e){this.initialHeight=this.initialHeight||this.itemsWrapper.height(); var f=this.options.caseSensitiveFilter?$.trim(e):$.trim(e).toLowerCase(); if(f===""){this.items.filter(":hidden").show() }else{for(var a=0; a<this.choices.length; a++){var c=this.choices.eq(a),b=this.options.caseSensitiveFilter?c.text():c.text().toLowerCase(),d=this.items.eq(a); if(this.filterMatcher(b,f)){d.show() }else{d.hide() }}}if(this.itemsContainer.height()<this.initialHeight){this.itemsWrapper.css("height","auto") }else{this.itemsWrapper.height(this.initialHeight) }},_search:function(d,e,a){for(var b=e; b<a; b++){var c=this.choices.eq(b); if(c.text().indexOf(d)===0){return this.items.eq(b) }}return null },getSelectedValue:function(){return this.element.val() },getSelectedLabel:function(){return this.choices.filter(":selected").text() },selectValue:function(b){var a=this.choices.filter('[value="'+b+'"]'); this._selectItem(this.items.eq(a.index()),true) },addOption:function(b,d){var c=$('<li data-label="'+b+'" class="pui-dropdown-item pui-dropdown-list-item ui-corner-all">'+b+"</li>"),a=$('<option value="'+d+'">'+b+"</option>"); a.appendTo(this.element); this._bindItemEvents(c); c.appendTo(this.itemsContainer); this.items.push(c[0]); this.choices=this.element.children("option"); if(this.items.length===1){this.selectValue(d); this._highlightItem(c) }},removeAllOptions:function(){this.element.empty(); this.itemsContainer.empty(); this.items.length=0; this.choices.length=0; this.element.val(""); this.label.text("") },_setOption:function(c,d){$.Widget.prototype._setOption.apply(this,arguments); if(c==="data"){this.removeAllOptions(); for(var b=0; b<this.options.data.length; b++){var a=this.options.data[b]; if(a.label){this.addOption(a.label,a.value) }else{this.addOption(a,a) }}if(this.options.scrollHeight&&this.panel.outerHeight()>this.options.scrollHeight){this.itemsWrapper.height(this.options.scrollHeight) }}},disable:function(){this._unbindEvents(); this.label.addClass("ui-state-disabled"); this.menuIcon.addClass("ui-state-disabled") },enable:function(){this._bindEvents(); this.label.removeClass("ui-state-disabled"); this.menuIcon.removeClass("ui-state-disabled") }}) });
JavaScript
$(function(){$.widget("primeui.puiaccordion",{options:{activeIndex:0,multiple:false},_create:function(){if(this.options.multiple){this.options.activeIndex=[] }var a=this; this.element.addClass("pui-accordion ui-widget ui-helper-reset"); this.element.children("h3").addClass("pui-accordion-header ui-helper-reset ui-state-default").each(function(c){var f=$(this),e=f.html(),d=(c==a.options.activeIndex)?"ui-state-active ui-corner-top":"ui-corner-all",b=(c==a.options.activeIndex)?"ui-icon ui-icon-triangle-1-s":"ui-icon ui-icon-triangle-1-e"; f.addClass(d).html('<span class="'+b+'"></span><a href="#">'+e+"</a>") }); this.element.children("div").each(function(b){var c=$(this); c.addClass("pui-accordion-content ui-helper-reset ui-widget-content"); if(b!=a.options.activeIndex){c.addClass("ui-helper-hidden") }}); this.headers=this.element.children(".pui-accordion-header"); this.panels=this.element.children(".pui-accordion-content"); this.headers.children("a").disableSelection(); this._bindEvents() },_bindEvents:function(){var a=this; this.headers.mouseover(function(){var b=$(this); if(!b.hasClass("ui-state-active")&&!b.hasClass("ui-state-disabled")){b.addClass("ui-state-hover") }}).mouseout(function(){var b=$(this); if(!b.hasClass("ui-state-active")&&!b.hasClass("ui-state-disabled")){b.removeClass("ui-state-hover") }}).click(function(d){var c=$(this); if(!c.hasClass("ui-state-disabled")){var b=c.index()/2; if(c.hasClass("ui-state-active")){a.unselect(b) }else{a.select(b) }}d.preventDefault() }) },select:function(b){var a=this.panels.eq(b); this._trigger("change",a); if(this.options.multiple){this._addToSelection(b) }else{this.options.activeIndex=b }this._show(a) },unselect:function(b){var a=this.panels.eq(b),c=a.prev(); c.attr("aria-expanded",false).children(".ui-icon").removeClass("ui-icon-triangle-1-s").addClass("ui-icon-triangle-1-e"); c.removeClass("ui-state-active ui-corner-top").addClass("ui-corner-all"); a.attr("aria-hidden",true).slideUp(); this._removeFromSelection(b) },_show:function(b){if(!this.options.multiple){var c=this.headers.filter(".ui-state-active"); c.children(".ui-icon").removeClass("ui-icon-triangle-1-s").addClass("ui-icon-triangle-1-e"); c.attr("aria-expanded",false).removeClass("ui-state-active ui-corner-top").addClass("ui-corner-all").next().attr("aria-hidden",true).slideUp() }var a=b.prev(); a.attr("aria-expanded",true).addClass("ui-state-active ui-corner-top").removeClass("ui-state-hover ui-corner-all").children(".ui-icon").removeClass("ui-icon-triangle-1-e").addClass("ui-icon-triangle-1-s"); b.attr("aria-hidden",false).slideDown("normal") },_addToSelection:function(a){this.options.activeIndex.push(a) },_removeFromSelection:function(a){this.options.activeIndex=$.grep(this.options.activeIndex,function(b){return b!=a }) }}) });
JavaScript
$(function(){$.widget("primeui.puidialog",{options:{draggable:true,resizable:true,location:"center",minWidth:150,minHeight:25,height:"auto",width:"300px",visible:false,modal:false,showEffect:null,hideEffect:null,effectOptions:{},effectSpeed:"normal",closeOnEscape:true,rtl:false,closable:true,minimizable:false,maximizable:false,appendTo:null,buttons:null},_create:function(){this.element.addClass("pui-dialog ui-widget ui-widget-content ui-helper-hidden ui-corner-all pui-shadow").contents().wrapAll('<div class="pui-dialog-content ui-widget-content" />'); this.element.prepend('<div class="pui-dialog-titlebar ui-widget-header ui-helper-clearfix ui-corner-top"><span id="'+this.element.attr("id")+'_label" class="pui-dialog-title">'+this.element.attr("title")+"</span>").removeAttr("title"); if(this.options.buttons){this.footer=$('<div class="pui-dialog-buttonpane ui-widget-content ui-helper-clearfix"></div>').appendTo(this.element); for(var b=0; b<this.options.buttons.length; b++){var c=this.options.buttons[b],a=$('<button type="button"></button>').appendTo(this.footer); if(c.text){a.text(c.text) }a.puibutton(c) }}if(this.options.rtl){this.element.addClass("pui-dialog-rtl") }this.content=this.element.children(".pui-dialog-content"); this.titlebar=this.element.children(".pui-dialog-titlebar"); if(this.options.closable){this._renderHeaderIcon("pui-dialog-titlebar-close","ui-icon-close") }if(this.options.maximizable){this._renderHeaderIcon("pui-dialog-titlebar-maximize","ui-icon-extlink") }if(this.options.minimizable){this._renderHeaderIcon("pui-dialog-titlebar-minimize","ui-icon-minus") }this.icons=this.titlebar.children(".pui-dialog-titlebar-icon"); this.closeIcon=this.titlebar.children(".pui-dialog-titlebar-close"); this.minimizeIcon=this.titlebar.children(".pui-dialog-titlebar-minimize"); this.maximizeIcon=this.titlebar.children(".pui-dialog-titlebar-maximize"); this.blockEvents="focus.puidialog mousedown.puidialog mouseup.puidialog keydown.puidialog keyup.puidialog"; this.parent=this.element.parent(); this.element.css({width:this.options.width,height:"auto"}); this.content.height(this.options.height); this._bindEvents(); if(this.options.draggable){this._setupDraggable() }if(this.options.resizable){this._setupResizable() }if(this.options.appendTo){this.element.appendTo(this.options.appendTo) }if($(document.body).children(".pui-dialog-docking-zone").length===0){$(document.body).append('<div class="pui-dialog-docking-zone"></div>') }this._applyARIA(); if(this.options.visible){this.show() }},_renderHeaderIcon:function(a,b){this.titlebar.append('<a class="pui-dialog-titlebar-icon '+a+' ui-corner-all" href="#" role="button"><span class="ui-icon '+b+'"></span></a>') },_enableModality:function(){var b=this,a=$(document); this.modality=$('<div id="'+this.element.attr("id")+'_modal" class="ui-widget-overlay"></div>').appendTo(document.body).css({width:a.width(),height:a.height(),"z-index":this.element.css("z-index")-1}); a.bind("keydown.puidialog",function(e){if(e.keyCode==$.ui.keyCode.TAB){var d=b.content.find(":tabbable"),f=d.filter(":first"),c=d.filter(":last"); if(e.target===c[0]&&!e.shiftKey){f.focus(1); return false }else{if(e.target===f[0]&&e.shiftKey){c.focus(1); return false }}}}).bind(this.blockEvents,function(c){if($(c.target).zIndex()<b.element.zIndex()){return false }}) },_disableModality:function(){this.modality.remove(); this.modality=null; $(document).unbind(this.blockEvents).unbind("keydown.dialog") },show:function(){if(this.element.is(":visible")){return }if(!this.positionInitialized){this._initPosition() }this._trigger("beforeShow",null); if(this.options.showEffect){var a=this; this.element.show(this.options.showEffect,this.options.effectOptions,this.options.effectSpeed,function(){a._postShow() }) }else{this.element.show(); this._postShow() }this._moveToTop(); if(this.options.modal){this._enableModality() }},_postShow:function(){this._trigger("afterShow",null); this.element.attr({"aria-hidden":false,"aria-live":"polite"}); this._applyFocus() },hide:function(){if(this.element.is(":hidden")){return }this._trigger("beforeHide",null); if(this.options.hideEffect){var a=this; this.element.hide(this.options.hideEffect,this.options.effectOptions,this.options.effectSpeed,function(){a._postHide() }) }else{this.element.hide(); this._postHide() }if(this.options.modal){this._disableModality() }},_postHide:function(){this._trigger("afterHide",null); this.element.attr({"aria-hidden":true,"aria-live":"off"}) },_applyFocus:function(){this.element.find(":not(:submit):not(:button):input:visible:enabled:first").focus() },_bindEvents:function(){var a=this; this.icons.mouseover(function(){$(this).addClass("ui-state-hover") }).mouseout(function(){$(this).removeClass("ui-state-hover") }); this.closeIcon.on("click.puidialog",function(b){a.hide(); b.preventDefault() }); this.maximizeIcon.click(function(b){a.toggleMaximize(); b.preventDefault() }); this.minimizeIcon.click(function(b){a.toggleMinimize(); b.preventDefault() }); if(this.options.closeOnEscape){$(document).on("keydown.dialog_"+this.element.attr("id"),function(d){var c=$.ui.keyCode,b=parseInt(a.element.css("z-index"),10)===PUI.zindex; if(d.which===c.ESCAPE&&a.element.is(":visible")&&b){a.hide() }}) }if(this.options.modal){$(window).on("resize.puidialog",function(){$(document.body).children(".ui-widget-overlay").css({width:$(document).width(),height:$(document).height()}) }) }},_setupDraggable:function(){this.element.draggable({cancel:".pui-dialog-content, .pui-dialog-titlebar-close",handle:".pui-dialog-titlebar",containment:"document"}) },_setupResizable:function(){this.element.resizable({minWidth:this.options.minWidth,minHeight:this.options.minHeight,alsoResize:this.content,containment:"document"}); this.resizers=this.element.children(".ui-resizable-handle") },_initPosition:function(){this.element.css({left:0,top:0}); if(/(center|left|top|right|bottom)/.test(this.options.location)){this.options.location=this.options.location.replace(","," "); this.element.position({my:"center",at:this.options.location,collision:"fit",of:window,using:function(f){var d=f.left<0?0:f.left,e=f.top<0?0:f.top; $(this).css({left:d,top:e}) }}) }else{var b=this.options.position.split(","),a=$.trim(b[0]),c=$.trim(b[1]); this.element.offset({left:a,top:c}) }this.positionInitialized=true },_moveToTop:function(){this.element.css("z-index",++PUI.zindex) },toggleMaximize:function(){if(this.minimized){this.toggleMinimize() }if(this.maximized){this.element.removeClass("pui-dialog-maximized"); this._restoreState(); this.maximizeIcon.removeClass("ui-state-hover").children(".ui-icon").removeClass("ui-icon-newwin").addClass("ui-icon-extlink"); this.maximized=false }else{this._saveState(); var a=$(window); this.element.addClass("pui-dialog-maximized").css({width:a.width()-6,height:a.height()}).offset({top:a.scrollTop(),left:a.scrollLeft()}); this.content.css({width:"auto",height:"auto"}); this.maximizeIcon.removeClass("ui-state-hover").children(".ui-icon").removeClass("ui-icon-extlink").addClass("ui-icon-newwin"); this.maximized=true; this._trigger("maximize") }},toggleMinimize:function(){var a=true,c=$(document.body).children(".pui-dialog-docking-zone"); if(this.maximized){this.toggleMaximize(); a=false }var b=this; if(this.minimized){this.element.appendTo(this.parent).removeClass("pui-dialog-minimized").css({position:"fixed","float":"none"}); this._restoreState(); this.content.show(); this.minimizeIcon.removeClass("ui-state-hover").children(".ui-icon").removeClass("ui-icon-plus").addClass("ui-icon-minus"); this.minimized=false; if(this.options.resizable){this.resizers.show() }if(this.footer){this.footer.show() }}else{this._saveState(); if(a){this.element.effect("transfer",{to:c,className:"pui-dialog-minimizing"},500,function(){b._dock(c); b.element.addClass("pui-dialog-minimized") }) }else{this._dock(c) }}},_dock:function(a){this.element.appendTo(a).css("position","static"); this.element.css({height:"auto",width:"auto","float":"left"}); this.content.hide(); this.minimizeIcon.removeClass("ui-state-hover").children(".ui-icon").removeClass("ui-icon-minus").addClass("ui-icon-plus"); this.minimized=true; if(this.options.resizable){this.resizers.hide() }if(this.footer){this.footer.hide() }a.css("z-index",++PUI.zindex); this._trigger("minimize") },_saveState:function(){this.state={width:this.element.width(),height:this.element.height()}; var a=$(window); this.state.offset=this.element.offset(); this.state.windowScrollLeft=a.scrollLeft(); this.state.windowScrollTop=a.scrollTop() },_restoreState:function(){this.element.width(this.state.width).height(this.state.height); var a=$(window); this.element.offset({top:this.state.offset.top+(a.scrollTop()-this.state.windowScrollTop),left:this.state.offset.left+(a.scrollLeft()-this.state.windowScrollLeft)}) },_applyARIA:function(){this.element.attr({role:"dialog","aria-labelledby":this.element.attr("id")+"_title","aria-hidden":!this.options.visible}); this.titlebar.children("a.pui-dialog-titlebar-icon").attr("role","button") }}) });
JavaScript
$(function(){$.widget("primeui.puisticky",{_create:function(){var a=this.element; this.initialState={top:a.offset().top,width:a.width(),height:a.height()}; var c=$(window),b=this; c.on("scroll",function(){if(c.scrollTop()>b.initialState.top){b._fix() }else{b._restore() }}) },_refresh:function(){$(window).off("scroll"); this._create() },_fix:function(){if(!this.fixed){this.element.css({position:"fixed",top:0,"z-index":10000,width:this.initialState.width}).addClass("pui-shadow ui-sticky"); $('<div class="ui-sticky-ghost"></div>').height(this.initialState.height).insertBefore(this.element); this.fixed=true }},_restore:function(){if(this.fixed){this.element.css({position:"static",top:"auto",width:this.initialState.width}).removeClass("pui-shadow ui-sticky"); this.element.prev(".ui-sticky-ghost").remove(); this.fixed=false }}}) });
JavaScript
$(function(){$.widget("primeui.puisplitbutton",{options:{icon:null,iconPos:"left",items:null},_create:function(){this.element.wrap('<div class="pui-splitbutton pui-buttonset ui-widget"></div>'); this.container=this.element.parent().uniqueId(); this.menuButton=this.container.append('<button class="pui-splitbutton-menubutton" type="button"></button>').children(".pui-splitbutton-menubutton"); this.options.disabled=this.element.prop("disabled"); if(this.options.disabled){this.menuButton.prop("disabled",true) }this.element.puibutton(this.options).removeClass("ui-corner-all").addClass("ui-corner-left"); this.menuButton.puibutton({icon:"ui-icon-triangle-1-s"}).removeClass("ui-corner-all").addClass("ui-corner-right"); if(this.options.items&&this.options.items.length){this._renderPanel(); this._bindEvents() }},_renderPanel:function(){this.menu=$('<div class="pui-menu pui-menu-dynamic ui-widget ui-widget-content ui-corner-all ui-helper-clearfix pui-shadow"></div>').append('<ul class="pui-menu-list ui-helper-reset"></ul>'); this.menuList=this.menu.children(".pui-menu-list"); for(var a=0; a<this.options.items.length; a++){var c=this.options.items[a],d=$('<li class="pui-menuitem ui-widget ui-corner-all" role="menuitem"></li>'),b=$('<a class="pui-menuitem-link ui-corner-all"><span class="pui-menuitem-icon ui-icon '+c.icon+'"></span><span class="ui-menuitem-text">'+c.text+"</span></a>"); if(c.url){b.attr("href",c.url) }if(c.click){b.on("click.puisplitbutton",c.click) }d.append(b).appendTo(this.menuList) }this.menu.appendTo(this.options.appendTo||this.container); this.options.position={my:"left top",at:"left bottom",of:this.element} },_bindEvents:function(){var b=this; this.menuButton.on("click.puisplitbutton",function(){if(b.menu.is(":hidden")){b.show() }else{b.hide() }}); this.menuList.children().on("mouseover.puisplitbutton",function(c){$(this).addClass("ui-state-hover") }).on("mouseout.puisplitbutton",function(c){$(this).removeClass("ui-state-hover") }).on("click.puisplitbutton",function(){b.hide() }); $(document.body).bind("mousedown."+this.container.attr("id"),function(d){if(b.menu.is(":hidden")){return }var c=$(d.target); if(c.is(b.element)||b.element.has(c).length>0){return }var f=b.menu.offset(); if(d.pageX<f.left||d.pageX>f.left+b.menu.width()||d.pageY<f.top||d.pageY>f.top+b.menu.height()){b.element.removeClass("ui-state-focus ui-state-hover"); b.hide() }}); var a="resize."+this.container.attr("id"); $(window).unbind(a).bind(a,function(){if(b.menu.is(":visible")){b._alignPanel() }}) },show:function(){this._alignPanel(); this.menuButton.trigger("focus"); this.menu.show(); this._trigger("show",null) },hide:function(){this.menuButton.removeClass("ui-state-focus"); this.menu.fadeOut("fast"); this._trigger("hide",null) },_alignPanel:function(){this.menu.css({left:"",top:"","z-index":++PUI.zindex}).position(this.options.position) },disable:function(){this.element.puibutton("disable"); this.menuButton.puibutton("disable") },enable:function(){this.element.puibutton("enable"); this.menuButton.puibutton("enable") }}) });
JavaScript
$(function(){$.widget("primeui.puitree",{options:{nodes:null,lazy:false,animate:false,selectionMode:null,icons:null},_create:function(){this.element.uniqueId().addClass("pui-tree ui-widget ui-widget-content ui-corner-all").append('<ul class="pui-tree-container"></ul>'); this.rootContainer=this.element.children(".pui-tree-container"); if(this.options.selectionMode){this.selection=[] }this._bindEvents(); if($.type(this.options.nodes)==="array"){this._renderNodes(this.options.nodes,this.rootContainer) }else{if($.type(this.options.nodes)==="function"){this.options.nodes.call(this,{},this._initData) }else{throw"Unsupported type. nodes option can be either an array or a function" }}},_renderNodes:function(b,a){for(var c=0; c<b.length; c++){this._renderNode(b[c],a) }},_renderNode:function(c,b){var k=this.options.lazy?c.leaf:!(c.children&&c.children.length),d=c.iconType||"def",h=c.expanded,m=this.options.selectionMode?(c.selectable===false?false:true):false,f=k?"pui-treenode-leaf-icon":(c.expanded?"pui-tree-toggler ui-icon ui-icon-triangle-1-s":"pui-tree-toggler ui-icon ui-icon-triangle-1-e"),g=k?"pui-treenode pui-treenode-leaf":"pui-treenode pui-treenode-parent",p=$('<li class="'+g+'"></li>'),o=$('<span class="pui-treenode-content"></span>'); p.data("puidata",c.data).appendTo(b); if(m){o.addClass("pui-treenode-selectable") }o.append('<span class="'+f+'"></span>').append('<span class="pui-treenode-icon"></span>').append('<span class="pui-treenode-label ui-corner-all">'+c.label+"</span>").appendTo(p); var a=this.options.icons&&this.options.icons[d]; if(a){var j=o.children(".pui-treenode-icon"),l=($.type(a)==="string")?a:(h?a.expanded:a.collapsed); j.addClass("ui-icon "+l) }if(!k){var n=$('<ul class="pui-treenode-children"></ul>'); if(!c.expanded){n.hide() }n.appendTo(p); if(c.children){for(var e=0; e<c.children.length; e++){this._renderNode(c.children[e],n) }}}},_initData:function(a){this._renderNodes(a,this.rootContainer) },_handleNodeData:function(b,a){this._renderNodes(b,a.children(".pui-treenode-children")); this._showNodeChildren(a); a.data("puiloaded",true) },_bindEvents:function(){var e=this,c=this.element.attr("id"),b="#"+c+" .pui-tree-toggler"; $(document).off("click.puitree-"+c,b).on("click.puitree-"+c,b,null,function(h){var f=$(this),g=f.closest("li"); if(g.hasClass("pui-treenode-expanded")){e.collapseNode(g) }else{e.expandNode(g) }}); if(this.options.selectionMode){var a="#"+c+" .pui-treenode-selectable .pui-treenode-label",d="#"+c+" .pui-treenode-selectable.pui-treenode-content"; $(document).off("mouseout.puitree-"+c+" mouseover.puitree-"+c,a).on("mouseout.puitree-"+c,a,null,function(){$(this).removeClass("ui-state-hover") }).on("mouseover.puitree-"+c,a,null,function(){$(this).addClass("ui-state-hover") }).off("click.puitree-"+c,d).on("click.puitree-"+c,d,null,function(f){e._nodeClick(f,$(this)) }) }},expandNode:function(a){this._trigger("beforeExpand",null,{node:a,data:a.data("puidata")}); if(this.options.lazy&&!a.data("puiloaded")){this.options.nodes.call(this,{node:a,data:a.data("puidata")},this._handleNodeData) }else{this._showNodeChildren(a) }},collapseNode:function(e){this._trigger("beforeCollapse",null,{node:e,data:e.data("puidata")}); e.removeClass("pui-treenode-expanded"); var a=e.iconType||"def",c=this.options.icons&&this.options.icons[a]; if(c&&$.type(c)!=="string"){e.find("> .pui-treenode-content > .pui-treenode-icon").removeClass(c.expanded).addClass(c.collapsed) }var d=e.find("> .pui-treenode-content > .pui-tree-toggler"),b=e.children(".pui-treenode-children"); d.addClass("ui-icon-triangle-1-e").removeClass("ui-icon-triangle-1-s"); if(this.options.animate){b.slideUp("fast") }else{b.hide() }this._trigger("afterCollapse",null,{node:e,data:e.data("puidata")}) },_showNodeChildren:function(d){d.addClass("pui-treenode-expanded").attr("aria-expanded",true); var a=d.iconType||"def",b=this.options.icons&&this.options.icons[a]; if(b&&$.type(b)!=="string"){d.find("> .pui-treenode-content > .pui-treenode-icon").removeClass(b.collapsed).addClass(b.expanded) }var c=d.find("> .pui-treenode-content > .pui-tree-toggler"); c.addClass("ui-icon-triangle-1-s").removeClass("ui-icon-triangle-1-e"); if(this.options.animate){d.children(".pui-treenode-children").slideDown("fast") }else{d.children(".pui-treenode-children").show() }this._trigger("afterExpand",null,{node:d,data:d.data("puidata")}) },_nodeClick:function(d,a){PUI.clearSelection(); if($(d.target).is(":not(.pui-tree-toggler)")){var c=a.parent(); var b=this._isNodeSelected(c.data("puidata")),e=d.metaKey||d.ctrlKey; if(b&&e){this.unselectNode(c) }else{if(this._isSingleSelection()||(this._isMultipleSelection()&&!e)){this.unselectAllNodes() }this.selectNode(c) }}},selectNode:function(a){a.attr("aria-selected",true).find("> .pui-treenode-content > .pui-treenode-label").removeClass("ui-state-hover").addClass("ui-state-highlight"); this._addToSelection(a.data("puidata")); this._trigger("nodeSelect",null,{node:a,data:a.data("puidata")}) },unselectNode:function(a){a.attr("aria-selected",false).find("> .pui-treenode-content > .pui-treenode-label").removeClass("ui-state-highlight ui-state-hover"); this._removeFromSelection(a.data("puidata")); this._trigger("nodeUnselect",null,{node:a,data:a.data("puidata")}) },unselectAllNodes:function(){this.selection=[]; this.element.find(".pui-treenode-label.ui-state-highlight").each(function(){$(this).removeClass("ui-state-highlight").closest(".ui-treenode").attr("aria-selected",false) }) },_addToSelection:function(b){if(b){var a=this._isNodeSelected(b); if(!a){this.selection.push(b) }}},_removeFromSelection:function(c){if(c){var a=-1; for(var b=0; b<this.selection.length; b++){var d=this.selection[b]; if(d&&(JSON.stringify(d)===JSON.stringify(c))){a=b; break }}if(a>=0){this.selection.splice(a,1) }}},_isNodeSelected:function(c){var b=false; if(c){for(var a=0; a<this.selection.length; a++){var d=this.selection[a]; if(d&&(JSON.stringify(d)===JSON.stringify(c))){b=true; break }}}return b },_isSingleSelection:function(){return this.options.selectionMode&&this.options.selectionMode==="single" },_isMultipleSelection:function(){return this.options.selectionMode&&this.options.selectionMode==="multiple" }}) });
JavaScript
$(function(){var a={}; $.widget("primeui.puiradiobutton",{_create:function(){this.element.wrap('<div class="pui-radiobutton ui-widget"><div class="ui-helper-hidden-accessible"></div></div>'); this.container=this.element.parent().parent(); this.box=$('<div class="pui-radiobutton-box ui-widget pui-radiobutton-relative ui-state-default">').appendTo(this.container); this.icon=$('<span class="pui-radiobutton-icon pui-c"></span>').appendTo(this.box); this.disabled=this.element.prop("disabled"); this.label=$('label[for="'+this.element.attr("id")+'"]'); if(this.element.prop("checked")){this.box.addClass("ui-state-active"); this.icon.addClass("ui-icon ui-icon-bullet"); a[this.element.attr("name")]=this.box }if(this.disabled){this.box.addClass("ui-state-disabled") }else{this._bindEvents() }},_bindEvents:function(){var b=this; this.box.on("mouseover.puiradiobutton",function(){if(!b._isChecked()){b.box.addClass("ui-state-hover") }}).on("mouseout.puiradiobutton",function(){if(!b._isChecked()){b.box.removeClass("ui-state-hover") }}).on("click.puiradiobutton",function(){if(!b._isChecked()){b.element.trigger("click"); if($.browser.msie&&parseInt($.browser.version,10)<9){b.element.trigger("change") }}}); if(this.label.length>0){this.label.on("click.puiradiobutton",function(c){b.element.trigger("click"); c.preventDefault() }) }this.element.focus(function(){if(b._isChecked()){b.box.removeClass("ui-state-active") }b.box.addClass("ui-state-focus") }).blur(function(){if(b._isChecked()){b.box.addClass("ui-state-active") }b.box.removeClass("ui-state-focus") }).change(function(d){var c=b.element.attr("name"); if(a[c]){a[c].removeClass("ui-state-active ui-state-focus ui-state-hover").children(".pui-radiobutton-icon").removeClass("ui-icon ui-icon-bullet") }b.icon.addClass("ui-icon ui-icon-bullet"); if(!b.element.is(":focus")){b.box.addClass("ui-state-active") }a[c]=b.box; b._trigger("change",null) }) },_isChecked:function(){return this.element.prop("checked") },_unbindEvents:function(){this.box.off(); if(this.label.length>0){this.label.off() }},enable:function(){this._bindEvents(); this.box.removeClass("ui-state-disabled") },disable:function(){this._unbindEvents(); this.box.addClass("ui-state-disabled") }}) });
JavaScript
$(function(){$.widget("primeui.puitabview",{options:{activeIndex:0,orientation:"top"},_create:function(){var a=this.element; a.addClass("pui-tabview ui-widget ui-widget-content ui-corner-all ui-hidden-container").children("ul").addClass("pui-tabview-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all").children("li").addClass("ui-state-default ui-corner-top"); a.addClass("pui-tabview-"+this.options.orientation); a.children("div").addClass("pui-tabview-panels").children().addClass("pui-tabview-panel ui-widget-content ui-corner-bottom"); a.find("> ul.pui-tabview-nav > li").eq(this.options.activeIndex).addClass("pui-tabview-selected ui-state-active"); a.find("> div.pui-tabview-panels > div.pui-tabview-panel:not(:eq("+this.options.activeIndex+"))").addClass("ui-helper-hidden"); this.navContainer=a.children(".pui-tabview-nav"); this.panelContainer=a.children(".pui-tabview-panels"); this._bindEvents() },_bindEvents:function(){var a=this; this.navContainer.children("li").on("mouseover.tabview",function(c){var b=$(this); if(!b.hasClass("ui-state-disabled")&&!b.hasClass("ui-state-active")){b.addClass("ui-state-hover") }}).on("mouseout.tabview",function(c){var b=$(this); if(!b.hasClass("ui-state-disabled")&&!b.hasClass("ui-state-active")){b.removeClass("ui-state-hover") }}).on("click.tabview",function(d){var c=$(this); if($(d.target).is(":not(.ui-icon-close)")){var b=c.index(); if(!c.hasClass("ui-state-disabled")&&b!=a.options.selected){a.select(b) }}d.preventDefault() }); this.navContainer.find("li .ui-icon-close").on("click.tabview",function(c){var b=$(this).parent().index(); a.remove(b); c.preventDefault() }) },select:function(c){this.options.selected=c; var b=this.panelContainer.children().eq(c),g=this.navContainer.children(),f=g.filter(".ui-state-active"),a=g.eq(b.index()),e=this.panelContainer.children(".pui-tabview-panel:visible"),d=this; e.attr("aria-hidden",true); f.attr("aria-expanded",false); b.attr("aria-hidden",false); a.attr("aria-expanded",true); if(this.options.effect){e.hide(this.options.effect.name,null,this.options.effect.duration,function(){f.removeClass("pui-tabview-selected ui-state-active"); a.removeClass("ui-state-hover").addClass("pui-tabview-selected ui-state-active"); b.show(d.options.name,null,d.options.effect.duration,function(){d._trigger("change",null,{index:c}) }) }) }else{f.removeClass("pui-tabview-selected ui-state-active"); e.hide(); a.removeClass("ui-state-hover").addClass("pui-tabview-selected ui-state-active"); b.show(); d._trigger("change",null,{index:c}) }},remove:function(b){var d=this.navContainer.children().eq(b),a=this.panelContainer.children().eq(b); this._trigger("close",null,{index:b}); d.remove(); a.remove(); if(b==this.options.selected){var c=this.options.selected==this.getLength()?this.options.selected-1:this.options.selected; this.select(c) }},getLength:function(){return this.navContainer.children().length },getActiveIndex:function(){return this.options.selected },_markAsLoaded:function(a){a.data("loaded",true) },_isLoaded:function(a){return a.data("loaded")===true },disable:function(a){this.navContainer.children().eq(a).addClass("ui-state-disabled") },enable:function(a){this.navContainer.children().eq(a).removeClass("ui-state-disabled") }}) });
JavaScript
$(function(){$.widget("primeui.puinotify",{options:{position:"top",visible:false,animate:true,effectSpeed:"normal",easing:"swing"},_create:function(){this.element.addClass("pui-notify pui-notify-"+this.options.position+" ui-widget ui-widget-content pui-shadow").wrapInner('<div class="pui-notify-content" />').appendTo(document.body); this.content=this.element.children(".pui-notify-content"); this.closeIcon=$('<span class="ui-icon ui-icon-closethick pui-notify-close"></span>').appendTo(this.element); this._bindEvents(); if(this.options.visible){this.show() }},_bindEvents:function(){var a=this; this.closeIcon.on("click.puinotify",function(){a.hide() }) },show:function(a){var b=this; if(a){this.update(a) }this.element.css("z-index",++PUI.zindex); this._trigger("beforeShow"); if(this.options.animate){this.element.slideDown(this.options.effectSpeed,this.options.easing,function(){b._trigger("afterShow") }) }else{this.element.show(); b._trigger("afterShow") }},hide:function(){var a=this; this._trigger("beforeHide"); if(this.options.animate){this.element.slideUp(this.options.effectSpeed,this.options.easing,function(){a._trigger("afterHide") }) }else{this.element.hide(); a._trigger("afterHide") }},update:function(a){this.content.html(a) }}) });
JavaScript
$(function(){$.widget("primeui.puispinner",{options:{step:1},_create:function(){var a=this.element,b=a.prop("disabled"); a.puiinputtext().addClass("pui-spinner-input").wrap('<span class="pui-spinner ui-widget ui-corner-all" />'); this.wrapper=a.parent(); this.wrapper.append('<a class="pui-spinner-button pui-spinner-up ui-corner-tr ui-button ui-widget ui-state-default ui-button-text-only"><span class="ui-button-text"><span class="ui-icon ui-icon-triangle-1-n"></span></span></a><a class="pui-spinner-button pui-spinner-down ui-corner-br ui-button ui-widget ui-state-default ui-button-text-only"><span class="ui-button-text"><span class="ui-icon ui-icon-triangle-1-s"></span></span></a>'); this.upButton=this.wrapper.children("a.pui-spinner-up"); this.downButton=this.wrapper.children("a.pui-spinner-down"); this.options.step=this.options.step||1; if(parseInt(this.options.step,10)===0){this.options.precision=this.options.step.toString().split(/[,]|[.]/)[1].length }this._initValue(); if(!b&&!a.prop("readonly")){this._bindEvents() }if(b){this.wrapper.addClass("ui-state-disabled") }a.attr({role:"spinner","aria-multiline":false,"aria-valuenow":this.value}); if(this.options.min!==undefined){a.attr("aria-valuemin",this.options.min) }if(this.options.max!==undefined){a.attr("aria-valuemax",this.options.max) }if(a.prop("disabled")){a.attr("aria-disabled",true) }if(a.prop("readonly")){a.attr("aria-readonly",true) }},_bindEvents:function(){var a=this; this.wrapper.children(".pui-spinner-button").mouseover(function(){$(this).addClass("ui-state-hover") }).mouseout(function(){$(this).removeClass("ui-state-hover ui-state-active"); if(a.timer){window.clearInterval(a.timer) }}).mouseup(function(){window.clearInterval(a.timer); $(this).removeClass("ui-state-active").addClass("ui-state-hover") }).mousedown(function(d){var c=$(this),b=c.hasClass("pui-spinner-up")?1:-1; c.removeClass("ui-state-hover").addClass("ui-state-active"); if(a.element.is(":not(:focus)")){a.element.focus() }a._repeat(null,b); d.preventDefault() }); this.element.keydown(function(c){var b=$.ui.keyCode; switch(c.which){case b.UP:a._spin(a.options.step); break; case b.DOWN:a._spin(-1*a.options.step); break; default:break }}).keyup(function(){a._updateValue() }).blur(function(){a._format() }).focus(function(){a.element.val(a.value) }); this.element.bind("mousewheel",function(b,c){if(a.element.is(":focus")){if(c>0){a._spin(a.options.step) }else{a._spin(-1*a.options.step) }return false }}) },_repeat:function(a,b){var d=this,c=a||500; window.clearTimeout(this.timer); this.timer=window.setTimeout(function(){d._repeat(40,b) },c); this._spin(this.options.step*b) },_toFixed:function(c,a){var b=Math.pow(10,a||0); return String(Math.round(c*b)/b) },_spin:function(b){var c,a=this.value?this.value:0; if(this.options.precision){c=parseFloat(this._toFixed(a+b,this.options.precision)) }else{c=parseInt(a+b,10) }if(this.options.min!==undefined&&c<this.options.min){c=this.options.min }if(this.options.max!==undefined&&c>this.options.max){c=this.options.max }this.element.val(c).attr("aria-valuenow",c); this.value=c; this.element.trigger("change") },_updateValue:function(){var a=this.element.val(); if(a===""){if(this.options.min!==undefined){this.value=this.options.min }else{this.value=0 }}else{if(this.options.step){a=parseFloat(a) }else{a=parseInt(a,10) }if(!isNaN(a)){this.value=a }}},_initValue:function(){var a=this.element.val(); if(a===""){if(this.options.min!==undefined){this.value=this.options.min }else{this.value=0 }}else{if(this.options.prefix){a=a.split(this.options.prefix)[1] }if(this.options.suffix){a=a.split(this.options.suffix)[0] }if(this.options.step){this.value=parseFloat(a) }else{this.value=parseInt(a,10) }}},_format:function(){var a=this.value; if(this.options.prefix){a=this.options.prefix+a }if(this.options.suffix){a=a+this.options.suffix }this.element.val(a) },_unbindEvents:function(){this.wrapper.children(".pui-spinner-button").off(); this.element.off() },enable:function(){this.wrapper.removeClass("ui-state-disabled"); this.element.puiinputtext("enable"); this._bindEvents() },disable:function(){this.wrapper.addClass("ui-state-disabled"); this.element.puiinputtext("disable"); this._unbindEvents() }}) });
JavaScript
$(function(){$.widget("primeui.puiautocomplete",{options:{delay:300,minQueryLength:1,multiple:false,dropdown:false,scrollHeight:200,forceSelection:false,effect:null,effectOptions:{},effectSpeed:"normal",content:null,caseSensitive:false},_create:function(){this.element.puiinputtext(); this.panel=$('<div class="pui-autocomplete-panel ui-widget-content ui-corner-all ui-helper-hidden pui-shadow"></div>').appendTo("body"); if(this.options.multiple){this.element.wrap('<ul class="pui-autocomplete-multiple ui-widget pui-inputtext ui-state-default ui-corner-all"><li class="pui-autocomplete-input-token"></li></ul>'); this.inputContainer=this.element.parent(); this.multiContainer=this.inputContainer.parent() }else{if(this.options.dropdown){this.dropdown=$('<button type="button" class="pui-button ui-widget ui-state-default ui-corner-right pui-button-icon-only"><span class="pui-button-icon-primary ui-icon ui-icon-triangle-1-s"></span><span class="pui-button-text">&nbsp;</span></button>').insertAfter(this.element); this.element.removeClass("ui-corner-all").addClass("ui-corner-left") }}this._bindEvents() },_bindEvents:function(){var a=this; this._bindKeyEvents(); if(this.options.dropdown){this.dropdown.on("hover.puiautocomplete",function(){if(!a.element.prop("disabled")){a.dropdown.toggleClass("ui-state-hover") }}).on("mousedown.puiautocomplete",function(){if(!a.element.prop("disabled")){a.dropdown.addClass("ui-state-active") }}).on("mouseup.puiautocomplete",function(){if(!a.element.prop("disabled")){a.dropdown.removeClass("ui-state-active"); a.search(""); a.element.focus() }}).on("focus.puiautocomplete",function(){a.dropdown.addClass("ui-state-focus") }).on("blur.puiautocomplete",function(){a.dropdown.removeClass("ui-state-focus") }).on("keydown.puiautocomplete",function(c){var b=$.ui.keyCode; if(c.which==b.ENTER||c.which==b.NUMPAD_ENTER){a.search(""); a.input.focus(); c.preventDefault() }}) }if(this.options.multiple){this.multiContainer.on("hover.puiautocomplete",function(){$(this).toggleClass("ui-state-hover") }).on("click.puiautocomplete",function(){a.element.trigger("focus") }); this.element.on("focus.pui-autocomplete",function(){a.multiContainer.addClass("ui-state-focus") }).on("blur.pui-autocomplete",function(b){a.multiContainer.removeClass("ui-state-focus") }) }if(this.options.forceSelection){this.currentItems=[this.element.val()]; this.element.on("blur.puiautocomplete",function(){var d=$(this).val(),c=false; for(var b=0; b<a.currentItems.length; b++){if(a.currentItems[b]===d){c=true; break }}if(!c){a.element.val("") }}) }$(document.body).bind("mousedown.puiautocomplete",function(b){if(a.panel.is(":hidden")){return }if(b.target===a.element.get(0)){return }var c=a.panel.offset(); if(b.pageX<c.left||b.pageX>c.left+a.panel.width()||b.pageY<c.top||b.pageY>c.top+a.panel.height()){a.hide() }}); $(window).bind("resize."+this.element.id,function(){if(a.panel.is(":visible")){a._alignPanel() }}) },_bindKeyEvents:function(){var a=this; this.element.on("keyup.puiautocomplete",function(g){var f=$.ui.keyCode,b=g.which,d=true; if(b==f.UP||b==f.LEFT||b==f.DOWN||b==f.RIGHT||b==f.TAB||b==f.SHIFT||b==f.ENTER||b==f.NUMPAD_ENTER){d=false }if(d){var c=a.element.val(); if(!c.length){a.hide() }if(c.length>=a.options.minQueryLength){if(a.timeout){window.clearTimeout(a.timeout) }a.timeout=window.setTimeout(function(){a.search(c) },a.options.delay) }}}).on("keydown.puiautocomplete",function(g){if(a.panel.is(":visible")){var f=$.ui.keyCode,d=a.items.filter(".ui-state-highlight"); switch(g.which){case f.UP:case f.LEFT:var c=d.prev(); if(c.length==1){d.removeClass("ui-state-highlight"); c.addClass("ui-state-highlight"); if(a.options.scrollHeight){PUI.scrollInView(a.panel,c) }}g.preventDefault(); break; case f.DOWN:case f.RIGHT:var b=d.next(); if(b.length==1){d.removeClass("ui-state-highlight"); b.addClass("ui-state-highlight"); if(a.options.scrollHeight){PUI.scrollInView(a.panel,b) }}g.preventDefault(); break; case f.ENTER:case f.NUMPAD_ENTER:d.trigger("click"); g.preventDefault(); break; case f.ALT:case 224:break; case f.TAB:d.trigger("click"); a.hide(); break }}}) },_bindDynamicEvents:function(){var a=this; this.items.on("mouseover.puiautocomplete",function(){var b=$(this); if(!b.hasClass("ui-state-highlight")){a.items.filter(".ui-state-highlight").removeClass("ui-state-highlight"); b.addClass("ui-state-highlight") }}).on("click.puiautocomplete",function(d){var c=$(this); if(a.options.multiple){var b='<li class="pui-autocomplete-token ui-state-active ui-corner-all ui-helper-hidden">'; b+='<span class="pui-autocomplete-token-icon ui-icon ui-icon-close" />'; b+='<span class="pui-autocomplete-token-label">'+c.data("label")+"</span></li>"; $(b).data(c.data()).insertBefore(a.inputContainer).fadeIn().children(".pui-autocomplete-token-icon").on("click.pui-autocomplete",function(g){var f=$(this).parent(); a._removeItem(f); a._trigger("unselect",g,f) }); a.element.val("").trigger("focus") }else{a.element.val(c.data("label")).focus() }a._trigger("select",d,c); a.hide() }) },search:function(h){this.query=this.options.caseSensitive?h:h.toLowerCase(); var f={query:this.query}; if(this.options.completeSource){if($.isArray(this.options.completeSource)){var b=this.options.completeSource,g=[],a=($.trim(h)===""); for(var c=0; c<b.length; c++){var e=b[c],d=e.label||e; if(!this.options.caseSensitive){d=d.toLowerCase() }if(a||d.indexOf(this.query)===0){g.push({label:b[c],value:e}) }}this._handleData(g) }else{this.options.completeSource.call(this,f,this._handleData) }}},_handleData:function(e){var g=this; this.panel.html(""); this.listContainer=$('<ul class="pui-autocomplete-items pui-autocomplete-list ui-widget-content ui-widget ui-corner-all ui-helper-reset"></ul>').appendTo(this.panel); for(var b=0; b<e.length; b++){var c=$('<li class="pui-autocomplete-item pui-autocomplete-list-item ui-corner-all"></li>'); c.data(e[b]); if(this.options.content){c.html(this.options.content.call(this,e[b])) }else{c.text(e[b].label) }this.listContainer.append(c) }this.items=this.listContainer.children(".pui-autocomplete-item"); this._bindDynamicEvents(); if(this.items.length>0){var f=g.items.eq(0),d=this.panel.is(":hidden"); f.addClass("ui-state-highlight"); if(g.query.length>0&&!g.options.content){g.items.each(function(){var i=$(this),k=i.html(),h=new RegExp(PUI.escapeRegExp(g.query),"gi"),j=k.replace(h,'<span class="pui-autocomplete-query">$&</span>'); i.html(j) }) }if(this.options.forceSelection){this.currentItems=[]; $.each(e,function(h,j){g.currentItems.push(j.label) }) }if(g.options.scrollHeight){var a=d?g.panel.height():g.panel.children().height(); if(a>g.options.scrollHeight){g.panel.height(g.options.scrollHeight) }else{g.panel.css("height","auto") }}if(d){g.show() }else{g._alignPanel() }}else{this.panel.hide() }},show:function(){this._alignPanel(); if(this.options.effect){this.panel.show(this.options.effect,{},this.options.effectSpeed) }else{this.panel.show() }},hide:function(){this.panel.hide(); this.panel.css("height","auto") },_removeItem:function(a){a.fadeOut("fast",function(){var b=$(this); b.remove() }) },_alignPanel:function(){var b=null; if(this.options.multiple){b=this.multiContainer.innerWidth()-(this.element.position().left-this.multiContainer.position().left) }else{if(this.panel.is(":visible")){b=this.panel.children(".pui-autocomplete-items").outerWidth() }else{this.panel.css({visibility:"hidden",display:"block"}); b=this.panel.children(".pui-autocomplete-items").outerWidth(); this.panel.css({visibility:"visible",display:"none"}) }var a=this.element.outerWidth(); if(b<a){b=a }}this.panel.css({left:"",top:"",width:b,"z-index":++PUI.zindex}).position({my:"left top",at:"left bottom",of:this.element}) }}) });
JavaScript
$(function(){$.widget("primeui.puifieldset",{options:{toggleable:false,toggleDuration:"normal",collapsed:false},_create:function(){this.element.addClass("pui-fieldset ui-widget ui-widget-content ui-corner-all").children("legend").addClass("pui-fieldset-legend ui-corner-all ui-state-default"); this.element.contents(":not(legend)").wrapAll('<div class="pui-fieldset-content" />'); this.legend=this.element.children("legend.pui-fieldset-legend"); this.content=this.element.children("div.pui-fieldset-content"); this.legend.prependTo(this.element); if(this.options.toggleable){this.element.addClass("pui-fieldset-toggleable"); this.toggler=$('<span class="pui-fieldset-toggler ui-icon" />').prependTo(this.legend); this._bindEvents(); if(this.options.collapsed){this.content.hide(); this.toggler.addClass("ui-icon-plusthick") }else{this.toggler.addClass("ui-icon-minusthick") }}},_bindEvents:function(){var a=this; this.legend.on("click.puifieldset",function(b){a.toggle(b) }).on("mouseover.puifieldset",function(){a.legend.addClass("ui-state-hover") }).on("mouseout.puifieldset",function(){a.legend.removeClass("ui-state-hover ui-state-active") }).on("mousedown.puifieldset",function(){a.legend.removeClass("ui-state-hover").addClass("ui-state-active") }).on("mouseup.puifieldset",function(){a.legend.removeClass("ui-state-active").addClass("ui-state-hover") }) },toggle:function(b){var a=this; this._trigger("beforeToggle",b); if(this.options.collapsed){this.toggler.removeClass("ui-icon-plusthick").addClass("ui-icon-minusthick") }else{this.toggler.removeClass("ui-icon-minusthick").addClass("ui-icon-plusthick") }this.content.slideToggle(this.options.toggleSpeed,"easeInOutCirc",function(){a._trigger("afterToggle",b); a.options.collapsed=!a.options.collapsed }) }}) });
JavaScript
(function(c){var l="undefined"; var d,g,q,f,b; var n,i,m,p; function j(s,v){var u=typeof s[v]; return u==="function"||(!!(u=="object"&&s[v]))||u=="unknown" }function k(s,t){return typeof(s[t])!=l }function e(s,t){return !!(typeof(s[t])=="object"&&s[t]) }function h(s){if(window.console&&window.console.log){window.console.log("TextInputs module for Rangy not supported in your browser. Reason: "+s) }}function o(t,u,s){if(u<0){u+=t.value.length }if(typeof s==l){s=u }if(s<0){s+=t.value.length }return{start:u,end:s} }function a(t,u,s){return{start:u,end:s,length:s-u,text:t.value.slice(u,s)} }function r(){return e(document,"body")?document.body:document.getElementsByTagName("body")[0] }c(document).ready(function(){var t=document.createElement("textarea"); r().appendChild(t); if(k(t,"selectionStart")&&k(t,"selectionEnd")){d=function(w){var x=w.selectionStart,v=w.selectionEnd; return a(w,x,v) }; g=function(x,v,w){var y=o(x,v,w); x.selectionStart=y.start; x.selectionEnd=y.end }; p=function(w,v){if(v){w.selectionEnd=w.selectionStart }else{w.selectionStart=w.selectionEnd }} }else{if(j(t,"createTextRange")&&e(document,"selection")&&j(document.selection,"createRange")){d=function(z){var C=0,x=0,B,w,v,A; var y=document.selection.createRange(); if(y&&y.parentElement()==z){v=z.value.length; B=z.value.replace(/\r\n/g,"\n"); w=z.createTextRange(); w.moveToBookmark(y.getBookmark()); A=z.createTextRange(); A.collapse(false); if(w.compareEndPoints("StartToEnd",A)>-1){C=x=v }else{C=-w.moveStart("character",-v); C+=B.slice(0,C).split("\n").length-1; if(w.compareEndPoints("EndToEnd",A)>-1){x=v }else{x=-w.moveEnd("character",-v); x+=B.slice(0,x).split("\n").length-1 }}}return a(z,C,x) }; var u=function(v,w){return w-(v.value.slice(0,w).split("\r\n").length-1) }; g=function(z,v,y){var A=o(z,v,y); var x=z.createTextRange(); var w=u(z,A.start); x.collapse(true); if(A.start==A.end){x.move("character",w) }else{x.moveEnd("character",u(z,A.end)); x.moveStart("character",w) }x.select() }; p=function(x,w){var v=document.selection.createRange(); v.collapse(w); v.select() } }else{r().removeChild(t); h("No means of finding text input caret position"); return }}r().removeChild(t); f=function(w,z,v,x){var y; if(z!=v){y=w.value; w.value=y.slice(0,z)+y.slice(v) }if(x){g(w,z,z) }}; q=function(v){var w=d(v); f(v,w.start,w.end,true) }; m=function(v){var w=d(v),x; if(w.start!=w.end){x=v.value; v.value=x.slice(0,w.start)+x.slice(w.end) }g(v,w.start,w.start); return w.text }; b=function(w,z,v,x){var y=w.value,A; w.value=y.slice(0,v)+z+y.slice(v); if(x){A=v+z.length; g(w,A,A) }}; n=function(v,y){var w=d(v),x=v.value; v.value=x.slice(0,w.start)+y+x.slice(w.end); var z=w.start+y.length; g(v,z,z) }; i=function(v,y,B){var x=d(v),A=v.value; v.value=A.slice(0,x.start)+y+x.text+B+A.slice(x.end); var z=x.start+y.length; var w=z+x.length; g(v,z,w) }; function s(v,w){return function(){var z=this.jquery?this[0]:this; var A=z.nodeName.toLowerCase(); if(z.nodeType==1&&(A=="textarea"||(A=="input"&&z.type=="text"))){var y=[z].concat(Array.prototype.slice.call(arguments)); var x=v.apply(this,y); if(!w){return x }}if(w){return this }} }c.fn.extend({getSelection:s(d,false),setSelection:s(g,true),collapseSelection:s(p,true),deleteSelectedText:s(q,true),deleteText:s(f,true),extractSelectedText:s(m,false),insertText:s(b,true),replaceSelectedText:s(n,true),surroundSelectedText:s(i,true)}) }) })(jQuery);
JavaScript
$(function(){var a={primaryStyles:["fontFamily","fontSize","fontWeight","fontVariant","fontStyle","paddingLeft","paddingTop","paddingBottom","paddingRight","marginLeft","marginTop","marginBottom","marginRight","borderLeftColor","borderTopColor","borderBottomColor","borderRightColor","borderLeftStyle","borderTopStyle","borderBottomStyle","borderRightStyle","borderLeftWidth","borderTopWidth","borderBottomWidth","borderRightWidth","line-height","outline"],specificStyle:{"word-wrap":"break-word","overflow-x":"hidden","overflow-y":"auto"},simulator:$('<div id="textarea_simulator"/>').css({position:"absolute",top:0,left:0,visibility:"hidden"}).appendTo(document.body),toHtml:function(b){return b.replace(/\n/g,"<br>").split(" ").join('<span style="white-space:prev-wrap">&nbsp;</span>') },getCaretPosition:function(){var c=a,n=this,g=n[0],d=n.offset(); if($.browser.msie){g.focus(); var h=document.selection.createRange(); $("#hskeywords").val(g.scrollTop); return{left:h.boundingLeft-d.left,top:parseInt(h.boundingTop)-d.top+g.scrollTop+document.documentElement.scrollTop+parseInt(n.getComputedStyle("fontSize"))} }c.simulator.empty(); $.each(c.primaryStyles,function(p,q){n.cloneStyle(c.simulator,q) }); c.simulator.css($.extend({width:n.width(),height:n.height()},c.specificStyle)); var l=n.val(),e=n.getCursorPosition(); var f=l.substring(0,e),m=l.substring(e); var j=$('<span class="before"/>').html(c.toHtml(f)),o=$('<span class="focus"/>'),b=$('<span class="after"/>').html(c.toHtml(m)); c.simulator.append(j).append(o).append(b); var i=o.offset(),k=c.simulator.offset(); return{top:i.top-k.top-g.scrollTop+($.browser.mozilla?0:parseInt(n.getComputedStyle("fontSize"))),left:o[0].offsetLeft-c.simulator[0].offsetLeft-g.scrollLeft} }}; $.fn.extend({getComputedStyle:function(c){if(this.length==0){return }var d=this[0]; var b=this.css(c); b=b||($.browser.msie?d.currentStyle[c]:document.defaultView.getComputedStyle(d,null)[c]); return b },cloneStyle:function(c,b){var d=this.getComputedStyle(b); if(!!d){$(c).css(b,d) }},cloneAllStyle:function(e,d){var c=this[0]; for(var b in c.style){var f=c.style[b]; typeof f=="string"||typeof f=="number"?this.cloneStyle(e,b):NaN }},getCursorPosition:function(){var e=this[0],b=0; if("selectionStart" in e){b=e.selectionStart }else{if("selection" in document){var c=document.selection.createRange(); if(parseInt($.browser.version)>6){e.focus(); var g=document.selection.createRange().text.length; c.moveStart("character",-e.value.length); b=c.text.length-g }else{var h=document.body.createTextRange(); h.moveToElementText(e); for(; h.compareEndPoints("StartToStart",c)<0; b++){h.moveStart("character",1) }for(var d=0; d<=b; d++){if(e.value.charAt(d)=="\n"){b++ }}var f=e.value.split("\n").length-1; b-=f; return b }}}return b },getCaretPosition:a.getCaretPosition}) });
JavaScript
(function(){ var $button = $("<div id='source-button' class='btn btn-primary btn-xs'>&lt; &gt;</div>").click(function(){ var html = $(this).parent().html(); html = cleanSource(html); $("#source-modal pre").text(html); $("#source-modal").modal(); }); $('.bs-component [data-toggle="popover"]').popover(); $('.bs-component [data-toggle="tooltip"]').tooltip(); $(".bs-component").hover(function(){ $(this).append($button); $button.show(); }, function(){ $button.hide(); }); function cleanSource(html) { var lines = html.split(/\n/); lines.shift(); lines.splice(-1, 1); var indentSize = lines[0].length - lines[0].trim().length, re = new RegExp(" {" + indentSize + "}"); lines = lines.map(function(line){ if (line.match(re)) { line = line.substring(indentSize); } return line; }); lines = lines.join("\n"); return lines; } })();
JavaScript
function loadPage(url){ $("#contenido").fadeOut("slow", function(){ $("#contenido").load(url, function(){ $("#contenido").fadeIn("slow"); }); }); } /*------------------------------- SLIDER ------------------------------------*/ function cargarContenido(id_div){ var capas = document.getElementById(id_div).querySelectorAll('img'); for (var i=0; i < capas.length; i++){ /* Muestra solo la primera imagen */ if (i == 0){ capas[i].style.visibility='visible'; capas[i].style.display='inline'; }else { capas[i].style.visibility='hidden'; capas[i].style.display='none'; } } } function siguiente(id_div){ var capas = document.getElementById(id_div).querySelectorAll('img'); for (var i=0; i < capas.length; i++){ if (capas[i].style.visibility == 'visible'){ var ind = i+1; if (ind >= capas.length){ ind = 0; } capas[ind].style.visibility='visible'; capas[ind].style.display='inline'; capas[i].style.visibility='hidden'; capas[i].style.display='none'; break; } } } function anterior(id_div){ var capas = document.getElementById(id_div).querySelectorAll('img'); for (var i=0; i < capas.length; i++){ if (capas[i].style.visibility == 'visible'){ var ind = i-1; if (ind < 0){ ind = capas.length - 1; } capas[ind].style.visibility='visible'; capas[ind].style.display='inline'; capas[i].style.visibility='hidden'; capas[i].style.display='none'; break; } } } /*--------------------------- SLIDER ------------------------------------------*/ function showPopup(){ document.getElementById('modal_fondo').style.visibility='visible'; $("#modal_contenido").show("slow"); } function ocultarDiv(id){ $(id).hide(); }
JavaScript
/** * Galleria Classic Theme 2012-08-08 * http://galleria.io * * Licensed under the MIT license * https://raw.github.com/aino/galleria/master/LICENSE * */ (function($) { /*global jQuery, Galleria */ Galleria.addTheme({ name: 'classic', author: 'Galleria', css: 'galleria.classic.css', defaults: { transition: 'slide', thumbCrop: 'height', // set this to false if you want to show the caption all the time: _toggleInfo: true }, init: function(options) { Galleria.requires(1.28, 'This version of Classic theme requires Galleria 1.2.8 or later'); // add some elements this.addElement('info-link','info-close'); this.append({ 'info' : ['info-link','info-close'] }); // cache some stuff var info = this.$('info-link,info-close,info-text'), touch = Galleria.TOUCH, click = touch ? 'touchstart' : 'click'; // show loader & counter with opacity this.$('loader,counter').show().css('opacity', 0.4); // some stuff for non-touch browsers if (! touch ) { this.addIdleState( this.get('image-nav-left'), { left:-50 }); this.addIdleState( this.get('image-nav-right'), { right:-50 }); this.addIdleState( this.get('counter'), { opacity:0 }); } // toggle info if ( options._toggleInfo === true ) { info.bind( click, function() { info.toggle(); }); } else { info.show(); this.$('info-link, info-close').hide(); } // bind some stuff this.bind('thumbnail', function(e) { if (! touch ) { // fade thumbnails $(e.thumbTarget).css('opacity', 0.6).parent().hover(function() { $(this).not('.active').children().stop().fadeTo(100, 1); }, function() { $(this).not('.active').children().stop().fadeTo(400, 0.6); }); if ( e.index === this.getIndex() ) { $(e.thumbTarget).css('opacity',1); } } else { $(e.thumbTarget).css('opacity', this.getIndex() ? 1 : 0.6); } }); this.bind('loadstart', function(e) { if (!e.cached) { this.$('loader').show().fadeTo(200, 0.4); } this.$('info').toggle( this.hasInfo() ); $(e.thumbTarget).css('opacity',1).parent().siblings().children().css('opacity', 0.6); }); this.bind('loadfinish', function(e) { this.$('loader').fadeOut(200); }); } }); }(jQuery));
JavaScript
/*! * jQuery Cycle Plugin (with Transition Definitions) * Examples and documentation at: http://jquery.malsup.com/cycle/ * Copyright (c) 2007-2013 M. Alsup * Version: 3.0.2 (19-APR-2013) * Dual licensed under the MIT and GPL licenses. * http://jquery.malsup.com/license.html * Requires: jQuery v1.7.1 or later */ ;(function($, undefined) { "use strict"; var ver = '3.0.2'; function debug(s) { if ($.fn.cycle.debug) log(s); } function log() { if (window.console && console.log) console.log('[cycle] ' + Array.prototype.join.call(arguments,' ')); } $.expr[':'].paused = function(el) { return el.cyclePause; }; // the options arg can be... // a number - indicates an immediate transition should occur to the given slide index // a string - 'pause', 'resume', 'toggle', 'next', 'prev', 'stop', 'destroy' or the name of a transition effect (ie, 'fade', 'zoom', etc) // an object - properties to control the slideshow // // the arg2 arg can be... // the name of an fx (only used in conjunction with a numeric value for 'options') // the value true (only used in first arg == 'resume') and indicates // that the resume should occur immediately (not wait for next timeout) $.fn.cycle = function(options, arg2) { var o = { s: this.selector, c: this.context }; // in 1.3+ we can fix mistakes with the ready state if (this.length === 0 && options != 'stop') { if (!$.isReady && o.s) { log('DOM not ready, queuing slideshow'); $(function() { $(o.s,o.c).cycle(options,arg2); }); 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; } // iterate the matched nodeset return this.each(function() { var opts = handleArguments(this, options, arg2); if (opts === false) return; opts.updateActivePagerLink = opts.updateActivePagerLink || $.fn.cycle.updateActivePagerLink; // stop existing slideshow for this container (if there is one) if (this.cycleTimeout) clearTimeout(this.cycleTimeout); this.cycleTimeout = this.cyclePause = 0; this.cycleStop = 0; // issue #108 var $cont = $(this); var $slides = opts.slideExpr ? $(opts.slideExpr, this) : $cont.children(); var els = $slides.get(); if (els.length < 2) { log('terminating; too few slides: ' + els.length); return; } var opts2 = buildOptions($cont, $slides, els, opts, o); if (opts2 === false) return; var startTime = opts2.continuous ? 10 : getTimeout(els[opts2.currSlide], els[opts2.nextSlide], opts2, !opts2.backwards); // if it's an auto slideshow, kick it off if (startTime) { startTime += (opts2.delay || 0); if (startTime < 10) startTime = 10; debug('first timeout: ' + startTime); this.cycleTimeout = setTimeout(function(){go(els,opts2,0,!opts.backwards);}, startTime); } }); }; function triggerPause(cont, byHover, onPager) { var opts = $(cont).data('cycle.opts'); if (!opts) return; var paused = !!cont.cyclePause; if (paused && opts.paused) opts.paused(cont, opts, byHover, onPager); else if (!paused && opts.resumed) opts.resumed(cont, opts, byHover, onPager); } // process the args that were passed to the plugin fn function handleArguments(cont, options, arg2) { if (cont.cycleStop === undefined) cont.cycleStop = 0; if (options === undefined || options === null) options = {}; if (options.constructor == String) { switch(options) { case 'destroy': case 'stop': var opts = $(cont).data('cycle.opts'); if (!opts) return false; cont.cycleStop++; // callbacks look for change if (cont.cycleTimeout) clearTimeout(cont.cycleTimeout); cont.cycleTimeout = 0; if (opts.elements) $(opts.elements).stop(); $(cont).removeData('cycle.opts'); if (options == 'destroy') destroy(cont, opts); return false; case 'toggle': cont.cyclePause = (cont.cyclePause === 1) ? 0 : 1; checkInstantResume(cont.cyclePause, arg2, cont); triggerPause(cont); return false; case 'pause': cont.cyclePause = 1; triggerPause(cont); return false; case 'resume': cont.cyclePause = 0; checkInstantResume(false, arg2, cont); triggerPause(cont); return false; case 'prev': case 'next': opts = $(cont).data('cycle.opts'); if (!opts) { log('options not found, "prev/next" ignored'); return false; } if (typeof arg2 == 'string') opts.oneTimeFx = arg2; $.fn.cycle[options](opts); return false; default: options = { fx: options }; } return options; } else if (options.constructor == Number) { // go to the requested slide var num = options; options = $(cont).data('cycle.opts'); if (!options) { log('options not found, can not advance slide'); return false; } if (num < 0 || num >= options.elements.length) { log('invalid slide index: ' + num); return false; } options.nextSlide = num; if (cont.cycleTimeout) { clearTimeout(cont.cycleTimeout); cont.cycleTimeout = 0; } if (typeof arg2 == 'string') options.oneTimeFx = arg2; go(options.elements, options, 1, num >= options.currSlide); return false; } return options; function checkInstantResume(isPaused, arg2, cont) { if (!isPaused && arg2 === true) { // resume now! var options = $(cont).data('cycle.opts'); if (!options) { log('options not found, can not resume'); return false; } if (cont.cycleTimeout) { clearTimeout(cont.cycleTimeout); cont.cycleTimeout = 0; } go(options.elements, options, 1, !options.backwards); } } } function removeFilter(el, opts) { if (!$.support.opacity && opts.cleartype && el.style.filter) { try { el.style.removeAttribute('filter'); } catch(smother) {} // handle old opera versions } } // unbind event handlers function destroy(cont, opts) { if (opts.next) $(opts.next).unbind(opts.prevNextEvent); if (opts.prev) $(opts.prev).unbind(opts.prevNextEvent); if (opts.pager || opts.pagerAnchorBuilder) $.each(opts.pagerAnchors || [], function() { this.unbind().remove(); }); opts.pagerAnchors = null; $(cont).unbind('mouseenter.cycle mouseleave.cycle'); if (opts.destroy) // callback opts.destroy(opts); } // one-time initialization function buildOptions($cont, $slides, els, options, o) { var startingSlideSpecified; // support metadata plugin (v1.0 and v2.0) var opts = $.extend({}, $.fn.cycle.defaults, options || {}, $.metadata ? $cont.metadata() : $.meta ? $cont.data() : {}); var meta = $.isFunction($cont.data) ? $cont.data(opts.metaAttr) : null; if (meta) opts = $.extend(opts, meta); if (opts.autostop) opts.countdown = opts.autostopCount || els.length; var cont = $cont[0]; $cont.data('cycle.opts', opts); opts.$cont = $cont; opts.stopCount = cont.cycleStop; opts.elements = els; opts.before = opts.before ? [opts.before] : []; opts.after = opts.after ? [opts.after] : []; // push some after callbacks if (!$.support.opacity && opts.cleartype) opts.after.push(function() { removeFilter(this, opts); }); if (opts.continuous) opts.after.push(function() { go(els,opts,0,!opts.backwards); }); saveOriginalOpts(opts); // clearType corrections if (!$.support.opacity && opts.cleartype && !opts.cleartypeNoBg) clearTypeFix($slides); // container requires non-static position so that slides can be position within if ($cont.css('position') == 'static') $cont.css('position', 'relative'); if (opts.width) $cont.width(opts.width); if (opts.height && opts.height != 'auto') $cont.height(opts.height); if (opts.startingSlide !== undefined) { opts.startingSlide = parseInt(opts.startingSlide,10); if (opts.startingSlide >= els.length || opts.startSlide < 0) opts.startingSlide = 0; // catch bogus input else startingSlideSpecified = true; } else if (opts.backwards) opts.startingSlide = els.length - 1; else opts.startingSlide = 0; // if random, mix up the slide array if (opts.random) { opts.randomMap = []; for (var i = 0; i < els.length; i++) opts.randomMap.push(i); opts.randomMap.sort(function(a,b) {return Math.random() - 0.5;}); if (startingSlideSpecified) { // try to find the specified starting slide and if found set start slide index in the map accordingly for ( var cnt = 0; cnt < els.length; cnt++ ) { if ( opts.startingSlide == opts.randomMap[cnt] ) { opts.randomIndex = cnt; } } } else { opts.randomIndex = 1; opts.startingSlide = opts.randomMap[1]; } } else if (opts.startingSlide >= els.length) opts.startingSlide = 0; // catch bogus input opts.currSlide = opts.startingSlide || 0; var first = opts.startingSlide; // set position and zIndex on all the slides $slides.css({position: 'absolute', top:0, left:0}).hide().each(function(i) { var z; if (opts.backwards) z = first ? i <= first ? els.length + (i-first) : first-i : els.length-i; else z = first ? i >= first ? els.length - (i-first) : first-i : els.length-i; $(this).css('z-index', z); }); // make sure first slide is visible $(els[first]).css('opacity',1).show(); // opacity bit needed to handle restart use case removeFilter(els[first], opts); // stretch slides if (opts.fit) { if (!opts.aspect) { if (opts.width) $slides.width(opts.width); if (opts.height && opts.height != 'auto') $slides.height(opts.height); } else { $slides.each(function(){ var $slide = $(this); var ratio = (opts.aspect === true) ? $slide.width()/$slide.height() : opts.aspect; if( opts.width && $slide.width() != opts.width ) { $slide.width( opts.width ); $slide.height( opts.width / ratio ); } if( opts.height && $slide.height() < opts.height ) { $slide.height( opts.height ); $slide.width( opts.height * ratio ); } }); } } if (opts.center && ((!opts.fit) || opts.aspect)) { $slides.each(function(){ var $slide = $(this); $slide.css({ "margin-left": opts.width ? ((opts.width - $slide.width()) / 2) + "px" : 0, "margin-top": opts.height ? ((opts.height - $slide.height()) / 2) + "px" : 0 }); }); } if (opts.center && !opts.fit && !opts.slideResize) { $slides.each(function(){ var $slide = $(this); $slide.css({ "margin-left": opts.width ? ((opts.width - $slide.width()) / 2) + "px" : 0, "margin-top": opts.height ? ((opts.height - $slide.height()) / 2) + "px" : 0 }); }); } // stretch container var reshape = (opts.containerResize || opts.containerResizeHeight) && $cont.innerHeight() < 1; if (reshape) { // do this only if container has no size http://tinyurl.com/da2oa9 var maxw = 0, maxh = 0; for(var j=0; j < els.length; j++) { var $e = $(els[j]), e = $e[0], w = $e.outerWidth(), h = $e.outerHeight(); if (!w) w = e.offsetWidth || e.width || $e.attr('width'); if (!h) h = e.offsetHeight || e.height || $e.attr('height'); maxw = w > maxw ? w : maxw; maxh = h > maxh ? h : maxh; } if (opts.containerResize && maxw > 0 && maxh > 0) $cont.css({width:maxw+'px',height:maxh+'px'}); if (opts.containerResizeHeight && maxh > 0) $cont.css({height:maxh+'px'}); } var pauseFlag = false; // https://github.com/malsup/cycle/issues/44 if (opts.pause) $cont.bind('mouseenter.cycle', function(){ pauseFlag = true; this.cyclePause++; triggerPause(cont, true); }).bind('mouseleave.cycle', function(){ if (pauseFlag) this.cyclePause--; triggerPause(cont, true); }); if (supportMultiTransitions(opts) === false) return false; // apparently a lot of people use image slideshows without height/width attributes on the images. // Cycle 2.50+ requires the sizing info for every slide; this block tries to deal with that. var requeue = false; options.requeueAttempts = options.requeueAttempts || 0; $slides.each(function() { // try to get height/width of each slide var $el = $(this); this.cycleH = (opts.fit && opts.height) ? opts.height : ($el.height() || this.offsetHeight || this.height || $el.attr('height') || 0); this.cycleW = (opts.fit && opts.width) ? opts.width : ($el.width() || this.offsetWidth || this.width || $el.attr('width') || 0); if ( $el.is('img') ) { var loading = (this.cycleH === 0 && this.cycleW === 0 && !this.complete); // don't requeue for images that are still loading but have a valid size if (loading) { if (o.s && opts.requeueOnImageNotLoaded && ++options.requeueAttempts < 100) { // track retry count so we don't loop forever log(options.requeueAttempts,' - img slide not loaded, requeuing slideshow: ', this.src, this.cycleW, this.cycleH); setTimeout(function() {$(o.s,o.c).cycle(options);}, opts.requeueTimeout); requeue = true; return false; // break each loop } else { log('could not determine size of image: '+this.src, this.cycleW, this.cycleH); } } } return true; }); if (requeue) return false; opts.cssBefore = opts.cssBefore || {}; opts.cssAfter = opts.cssAfter || {}; opts.cssFirst = opts.cssFirst || {}; opts.animIn = opts.animIn || {}; opts.animOut = opts.animOut || {}; $slides.not(':eq('+first+')').css(opts.cssBefore); $($slides[first]).css(opts.cssFirst); if (opts.timeout) { opts.timeout = parseInt(opts.timeout,10); // ensure that timeout and speed settings are sane if (opts.speed.constructor == String) opts.speed = $.fx.speeds[opts.speed] || parseInt(opts.speed,10); if (!opts.sync) opts.speed = opts.speed / 2; var buffer = opts.fx == 'none' ? 0 : opts.fx == 'shuffle' ? 500 : 250; while((opts.timeout - opts.speed) < buffer) // sanitize timeout opts.timeout += opts.speed; } if (opts.easing) opts.easeIn = opts.easeOut = opts.easing; if (!opts.speedIn) opts.speedIn = opts.speed; if (!opts.speedOut) opts.speedOut = opts.speed; opts.slideCount = els.length; opts.currSlide = opts.lastSlide = first; if (opts.random) { if (++opts.randomIndex == els.length) opts.randomIndex = 0; opts.nextSlide = opts.randomMap[opts.randomIndex]; } else if (opts.backwards) opts.nextSlide = opts.startingSlide === 0 ? (els.length-1) : opts.startingSlide-1; else opts.nextSlide = opts.startingSlide >= (els.length-1) ? 0 : opts.startingSlide+1; // run transition init fn if (!opts.multiFx) { var init = $.fn.cycle.transitions[opts.fx]; if ($.isFunction(init)) init($cont, $slides, opts); else if (opts.fx != 'custom' && !opts.multiFx) { log('unknown transition: ' + opts.fx,'; slideshow terminating'); return false; } } // fire artificial events var e0 = $slides[first]; if (!opts.skipInitializationCallbacks) { if (opts.before.length) opts.before[0].apply(e0, [e0, e0, opts, true]); if (opts.after.length) opts.after[0].apply(e0, [e0, e0, opts, true]); } if (opts.next) $(opts.next).bind(opts.prevNextEvent,function(){return advance(opts,1);}); if (opts.prev) $(opts.prev).bind(opts.prevNextEvent,function(){return advance(opts,0);}); if (opts.pager || opts.pagerAnchorBuilder) buildPager(els,opts); exposeAddSlide(opts, els); return opts; } // save off original opts so we can restore after clearing state function saveOriginalOpts(opts) { opts.original = { before: [], after: [] }; opts.original.cssBefore = $.extend({}, opts.cssBefore); opts.original.cssAfter = $.extend({}, opts.cssAfter); opts.original.animIn = $.extend({}, opts.animIn); opts.original.animOut = $.extend({}, opts.animOut); $.each(opts.before, function() { opts.original.before.push(this); }); $.each(opts.after, function() { opts.original.after.push(this); }); } function supportMultiTransitions(opts) { var i, tx, txs = $.fn.cycle.transitions; // look for multiple effects if (opts.fx.indexOf(',') > 0) { opts.multiFx = true; opts.fxs = opts.fx.replace(/\s*/g,'').split(','); // discard any bogus effect names for (i=0; i < opts.fxs.length; i++) { var fx = opts.fxs[i]; tx = txs[fx]; if (!tx || !txs.hasOwnProperty(fx) || !$.isFunction(tx)) { log('discarding unknown transition: ',fx); opts.fxs.splice(i,1); i--; } } // if we have an empty list then we threw everything away! if (!opts.fxs.length) { log('No valid transitions named; slideshow terminating.'); return false; } } else if (opts.fx == 'all') { // auto-gen the list of transitions opts.multiFx = true; opts.fxs = []; for (var p in txs) { if (txs.hasOwnProperty(p)) { tx = txs[p]; if (txs.hasOwnProperty(p) && $.isFunction(tx)) opts.fxs.push(p); } } } if (opts.multiFx && opts.randomizeEffects) { // munge the fxs array to make effect selection random var r1 = Math.floor(Math.random() * 20) + 30; for (i = 0; i < r1; i++) { var r2 = Math.floor(Math.random() * opts.fxs.length); opts.fxs.push(opts.fxs.splice(r2,1)[0]); } debug('randomized fx sequence: ',opts.fxs); } return true; } // provide a mechanism for adding slides after the slideshow has started function exposeAddSlide(opts, els) { opts.addSlide = function(newSlide, prepend) { var $s = $(newSlide), s = $s[0]; if (!opts.autostopCount) opts.countdown++; els[prepend?'unshift':'push'](s); if (opts.els) opts.els[prepend?'unshift':'push'](s); // shuffle needs this opts.slideCount = els.length; // add the slide to the random map and resort if (opts.random) { opts.randomMap.push(opts.slideCount-1); opts.randomMap.sort(function(a,b) {return Math.random() - 0.5;}); } $s.css('position','absolute'); $s[prepend?'prependTo':'appendTo'](opts.$cont); if (prepend) { opts.currSlide++; opts.nextSlide++; } if (!$.support.opacity && opts.cleartype && !opts.cleartypeNoBg) clearTypeFix($s); if (opts.fit && opts.width) $s.width(opts.width); if (opts.fit && opts.height && opts.height != 'auto') $s.height(opts.height); s.cycleH = (opts.fit && opts.height) ? opts.height : $s.height(); s.cycleW = (opts.fit && opts.width) ? opts.width : $s.width(); $s.css(opts.cssBefore); if (opts.pager || opts.pagerAnchorBuilder) $.fn.cycle.createPagerAnchor(els.length-1, s, $(opts.pager), els, opts); if ($.isFunction(opts.onAddSlide)) opts.onAddSlide($s); else $s.hide(); // default behavior }; } // reset internal state; we do this on every pass in order to support multiple effects $.fn.cycle.resetState = function(opts, fx) { fx = fx || opts.fx; opts.before = []; opts.after = []; opts.cssBefore = $.extend({}, opts.original.cssBefore); opts.cssAfter = $.extend({}, opts.original.cssAfter); opts.animIn = $.extend({}, opts.original.animIn); opts.animOut = $.extend({}, opts.original.animOut); opts.fxFn = null; $.each(opts.original.before, function() { opts.before.push(this); }); $.each(opts.original.after, function() { opts.after.push(this); }); // re-init var init = $.fn.cycle.transitions[fx]; if ($.isFunction(init)) init(opts.$cont, $(opts.elements), opts); }; // this is the main engine fn, it handles the timeouts, callbacks and slide index mgmt function go(els, opts, manual, fwd) { var p = opts.$cont[0], curr = els[opts.currSlide], next = els[opts.nextSlide]; // opts.busy is true if we're in the middle of an animation if (manual && opts.busy && opts.manualTrump) { // let manual transitions requests trump active ones debug('manualTrump in go(), stopping active transition'); $(els).stop(true,true); opts.busy = 0; clearTimeout(p.cycleTimeout); } // don't begin another timeout-based transition if there is one active if (opts.busy) { debug('transition active, ignoring new tx request'); return; } // stop cycling if we have an outstanding stop request if (p.cycleStop != opts.stopCount || p.cycleTimeout === 0 && !manual) return; // check to see if we should stop cycling based on autostop options if (!manual && !p.cyclePause && !opts.bounce && ((opts.autostop && (--opts.countdown <= 0)) || (opts.nowrap && !opts.random && opts.nextSlide < opts.currSlide))) { if (opts.end) opts.end(opts); return; } // if slideshow is paused, only transition on a manual trigger var changed = false; if ((manual || !p.cyclePause) && (opts.nextSlide != opts.currSlide)) { changed = true; var fx = opts.fx; // keep trying to get the slide size if we don't have it yet curr.cycleH = curr.cycleH || $(curr).height(); curr.cycleW = curr.cycleW || $(curr).width(); next.cycleH = next.cycleH || $(next).height(); next.cycleW = next.cycleW || $(next).width(); // support multiple transition types if (opts.multiFx) { if (fwd && (opts.lastFx === undefined || ++opts.lastFx >= opts.fxs.length)) opts.lastFx = 0; else if (!fwd && (opts.lastFx === undefined || --opts.lastFx < 0)) opts.lastFx = opts.fxs.length - 1; fx = opts.fxs[opts.lastFx]; } // one-time fx overrides apply to: $('div').cycle(3,'zoom'); if (opts.oneTimeFx) { fx = opts.oneTimeFx; opts.oneTimeFx = null; } $.fn.cycle.resetState(opts, fx); // run the before callbacks if (opts.before.length) $.each(opts.before, function(i,o) { if (p.cycleStop != opts.stopCount) return; o.apply(next, [curr, next, opts, fwd]); }); // stage the after callacks var after = function() { opts.busy = 0; $.each(opts.after, function(i,o) { if (p.cycleStop != opts.stopCount) return; o.apply(next, [curr, next, opts, fwd]); }); if (!p.cycleStop) { // queue next transition queueNext(); } }; debug('tx firing('+fx+'); currSlide: ' + opts.currSlide + '; nextSlide: ' + opts.nextSlide); // get ready to perform the transition opts.busy = 1; if (opts.fxFn) // fx function provided? opts.fxFn(curr, next, opts, after, fwd, manual && opts.fastOnEvent); else if ($.isFunction($.fn.cycle[opts.fx])) // fx plugin ? $.fn.cycle[opts.fx](curr, next, opts, after, fwd, manual && opts.fastOnEvent); else $.fn.cycle.custom(curr, next, opts, after, fwd, manual && opts.fastOnEvent); } else { queueNext(); } if (changed || opts.nextSlide == opts.currSlide) { // calculate the next slide var roll; opts.lastSlide = opts.currSlide; if (opts.random) { opts.currSlide = opts.nextSlide; if (++opts.randomIndex == els.length) { opts.randomIndex = 0; opts.randomMap.sort(function(a,b) {return Math.random() - 0.5;}); } opts.nextSlide = opts.randomMap[opts.randomIndex]; if (opts.nextSlide == opts.currSlide) opts.nextSlide = (opts.currSlide == opts.slideCount - 1) ? 0 : opts.currSlide + 1; } else if (opts.backwards) { roll = (opts.nextSlide - 1) < 0; if (roll && opts.bounce) { opts.backwards = !opts.backwards; opts.nextSlide = 1; opts.currSlide = 0; } else { opts.nextSlide = roll ? (els.length-1) : opts.nextSlide-1; opts.currSlide = roll ? 0 : opts.nextSlide+1; } } else { // sequence roll = (opts.nextSlide + 1) == els.length; if (roll && opts.bounce) { opts.backwards = !opts.backwards; opts.nextSlide = els.length-2; opts.currSlide = els.length-1; } else { opts.nextSlide = roll ? 0 : opts.nextSlide+1; opts.currSlide = roll ? els.length-1 : opts.nextSlide-1; } } } if (changed && opts.pager) opts.updateActivePagerLink(opts.pager, opts.currSlide, opts.activePagerClass); function queueNext() { // stage the next transition var ms = 0, timeout = opts.timeout; if (opts.timeout && !opts.continuous) { ms = getTimeout(els[opts.currSlide], els[opts.nextSlide], opts, fwd); if (opts.fx == 'shuffle') ms -= opts.speedOut; } else if (opts.continuous && p.cyclePause) // continuous shows work off an after callback, not this timer logic ms = 10; if (ms > 0) p.cycleTimeout = setTimeout(function(){ go(els, opts, 0, !opts.backwards); }, ms); } } // invoked after transition $.fn.cycle.updateActivePagerLink = function(pager, currSlide, clsName) { $(pager).each(function() { $(this).children().removeClass(clsName).eq(currSlide).addClass(clsName); }); }; // calculate timeout value for current transition function getTimeout(curr, next, opts, fwd) { if (opts.timeoutFn) { // call user provided calc fn var t = opts.timeoutFn.call(curr,curr,next,opts,fwd); while (opts.fx != 'none' && (t - opts.speed) < 250) // sanitize timeout t += opts.speed; debug('calculated timeout: ' + t + '; speed: ' + opts.speed); if (t !== false) return t; } return opts.timeout; } // expose next/prev function, caller must pass in state $.fn.cycle.next = function(opts) { advance(opts,1); }; $.fn.cycle.prev = function(opts) { advance(opts,0);}; // advance slide forward or back function advance(opts, moveForward) { var val = moveForward ? 1 : -1; var els = opts.elements; var p = opts.$cont[0], timeout = p.cycleTimeout; if (timeout) { clearTimeout(timeout); p.cycleTimeout = 0; } if (opts.random && val < 0) { // move back to the previously display slide opts.randomIndex--; if (--opts.randomIndex == -2) opts.randomIndex = els.length-2; else if (opts.randomIndex == -1) opts.randomIndex = els.length-1; opts.nextSlide = opts.randomMap[opts.randomIndex]; } else if (opts.random) { opts.nextSlide = opts.randomMap[opts.randomIndex]; } else { opts.nextSlide = opts.currSlide + val; if (opts.nextSlide < 0) { if (opts.nowrap) return false; opts.nextSlide = els.length - 1; } else if (opts.nextSlide >= els.length) { if (opts.nowrap) return false; opts.nextSlide = 0; } } var cb = opts.onPrevNextEvent || opts.prevNextClick; // prevNextClick is deprecated if ($.isFunction(cb)) cb(val > 0, opts.nextSlide, els[opts.nextSlide]); go(els, opts, 1, moveForward); return false; } function buildPager(els, opts) { var $p = $(opts.pager); $.each(els, function(i,o) { $.fn.cycle.createPagerAnchor(i,o,$p,els,opts); }); opts.updateActivePagerLink(opts.pager, opts.startingSlide, opts.activePagerClass); } $.fn.cycle.createPagerAnchor = function(i, el, $p, els, opts) { var a; if ($.isFunction(opts.pagerAnchorBuilder)) { a = opts.pagerAnchorBuilder(i,el); debug('pagerAnchorBuilder('+i+', el) returned: ' + a); } else a = '<a href="#">'+(i+1)+'</a>'; if (!a) return; var $a = $(a); // don't reparent if anchor is in the dom if ($a.parents('body').length === 0) { var arr = []; if ($p.length > 1) { $p.each(function() { var $clone = $a.clone(true); $(this).append($clone); arr.push($clone[0]); }); $a = $(arr); } else { $a.appendTo($p); } } opts.pagerAnchors = opts.pagerAnchors || []; opts.pagerAnchors.push($a); var pagerFn = function(e) { e.preventDefault(); opts.nextSlide = i; var p = opts.$cont[0], timeout = p.cycleTimeout; if (timeout) { clearTimeout(timeout); p.cycleTimeout = 0; } var cb = opts.onPagerEvent || opts.pagerClick; // pagerClick is deprecated if ($.isFunction(cb)) cb(opts.nextSlide, els[opts.nextSlide]); go(els,opts,1,opts.currSlide < i); // trigger the trans // return false; // <== allow bubble }; if ( /mouseenter|mouseover/i.test(opts.pagerEvent) ) { $a.hover(pagerFn, function(){/* no-op */} ); } else { $a.bind(opts.pagerEvent, pagerFn); } if ( ! /^click/.test(opts.pagerEvent) && !opts.allowPagerClickBubble) $a.bind('click.cycle', function(){return false;}); // suppress click var cont = opts.$cont[0]; var pauseFlag = false; // https://github.com/malsup/cycle/issues/44 if (opts.pauseOnPagerHover) { $a.hover( function() { pauseFlag = true; cont.cyclePause++; triggerPause(cont,true,true); }, function() { if (pauseFlag) cont.cyclePause--; triggerPause(cont,true,true); } ); } }; // helper fn to calculate the number of slides between the current and the next $.fn.cycle.hopsFromLast = function(opts, fwd) { var hops, l = opts.lastSlide, c = opts.currSlide; if (fwd) hops = c > l ? c - l : opts.slideCount - l; else hops = c < l ? l - c : l + opts.slideCount - c; return hops; }; // fix clearType problems in ie6 by setting an explicit bg color // (otherwise text slides look horrible during a fade transition) function clearTypeFix($slides) { debug('applying clearType background-color hack'); function hex(s) { s = parseInt(s,10).toString(16); return s.length < 2 ? '0'+s : s; } function getBg(e) { for ( ; e && e.nodeName.toLowerCase() != 'html'; e = e.parentNode) { var v = $.css(e,'background-color'); if (v && v.indexOf('rgb') >= 0 ) { var rgb = v.match(/\d+/g); return '#'+ hex(rgb[0]) + hex(rgb[1]) + hex(rgb[2]); } if (v && v != 'transparent') return v; } return '#ffffff'; } $slides.each(function() { $(this).css('background-color', getBg(this)); }); } // reset common props before the next transition $.fn.cycle.commonReset = function(curr,next,opts,w,h,rev) { $(opts.elements).not(curr).hide(); if (typeof opts.cssBefore.opacity == 'undefined') opts.cssBefore.opacity = 1; opts.cssBefore.display = 'block'; if (opts.slideResize && w !== false && next.cycleW > 0) opts.cssBefore.width = next.cycleW; if (opts.slideResize && h !== false && next.cycleH > 0) opts.cssBefore.height = next.cycleH; opts.cssAfter = opts.cssAfter || {}; opts.cssAfter.display = 'none'; $(curr).css('zIndex',opts.slideCount + (rev === true ? 1 : 0)); $(next).css('zIndex',opts.slideCount + (rev === true ? 0 : 1)); }; // the actual fn for effecting a transition $.fn.cycle.custom = function(curr, next, opts, cb, fwd, speedOverride) { var $l = $(curr), $n = $(next); var speedIn = opts.speedIn, speedOut = opts.speedOut, easeIn = opts.easeIn, easeOut = opts.easeOut; $n.css(opts.cssBefore); if (speedOverride) { if (typeof speedOverride == 'number') speedIn = speedOut = speedOverride; else speedIn = speedOut = 1; easeIn = easeOut = null; } var fn = function() { $n.animate(opts.animIn, speedIn, easeIn, function() { cb(); }); }; $l.animate(opts.animOut, speedOut, easeOut, function() { $l.css(opts.cssAfter); if (!opts.sync) fn(); }); if (opts.sync) fn(); }; // transition definitions - only fade is defined here, transition pack defines the rest $.fn.cycle.transitions = { fade: function($cont, $slides, opts) { $slides.not(':eq('+opts.currSlide+')').css('opacity',0); opts.before.push(function(curr,next,opts) { $.fn.cycle.commonReset(curr,next,opts); opts.cssBefore.opacity = 0; }); opts.animIn = { opacity: 1 }; opts.animOut = { opacity: 0 }; opts.cssBefore = { top: 0, left: 0 }; } }; $.fn.cycle.ver = function() { return ver; }; // override these globally if you like (they are all optional) $.fn.cycle.defaults = { activePagerClass: 'activeSlide', // class name used for the active pager link after: null, // transition callback (scope set to element that was shown): function(currSlideElement, nextSlideElement, options, forwardFlag) allowPagerClickBubble: false, // allows or prevents click event on pager anchors from bubbling animIn: null, // properties that define how the slide animates in animOut: null, // properties that define how the slide animates out aspect: false, // preserve aspect ratio during fit resizing, cropping if necessary (must be used with fit option) autostop: 0, // true to end slideshow after X transitions (where X == slide count) autostopCount: 0, // number of transitions (optionally used with autostop to define X) backwards: false, // true to start slideshow at last slide and move backwards through the stack before: null, // transition callback (scope set to element to be shown): function(currSlideElement, nextSlideElement, options, forwardFlag) center: null, // set to true to have cycle add top/left margin to each slide (use with width and height options) cleartype: !$.support.opacity, // true if clearType corrections should be applied (for IE) cleartypeNoBg: false, // set to true to disable extra cleartype fixing (leave false to force background color setting on slides) containerResize: 1, // resize container to fit largest slide containerResizeHeight: 0, // resize containers height to fit the largest slide but leave the width dynamic continuous: 0, // true to start next transition immediately after current one completes cssAfter: null, // properties that defined the state of the slide after transitioning out cssBefore: null, // properties that define the initial state of the slide before transitioning in delay: 0, // additional delay (in ms) for first transition (hint: can be negative) easeIn: null, // easing for "in" transition easeOut: null, // easing for "out" transition easing: null, // easing method for both in and out transitions end: null, // callback invoked when the slideshow terminates (use with autostop or nowrap options): function(options) fastOnEvent: 0, // force fast transitions when triggered manually (via pager or prev/next); value == time in ms fit: 0, // force slides to fit container fx: 'fade', // name of transition effect (or comma separated names, ex: 'fade,scrollUp,shuffle') fxFn: null, // function used to control the transition: function(currSlideElement, nextSlideElement, options, afterCalback, forwardFlag) height: 'auto', // container height (if the 'fit' option is true, the slides will be set to this height as well) manualTrump: true, // causes manual transition to stop an active transition instead of being ignored metaAttr: 'cycle', // data- attribute that holds the option data for the slideshow next: null, // element, jQuery object, or jQuery selector string for the element to use as event trigger for next slide nowrap: 0, // true to prevent slideshow from wrapping onPagerEvent: null, // callback fn for pager events: function(zeroBasedSlideIndex, slideElement) onPrevNextEvent: null, // callback fn for prev/next events: function(isNext, zeroBasedSlideIndex, slideElement) pager: null, // element, jQuery object, or jQuery selector string for the element to use as pager container pagerAnchorBuilder: null, // callback fn for building anchor links: function(index, DOMelement) pagerEvent: 'click.cycle', // name of event which drives the pager navigation pause: 0, // true to enable "pause on hover" pauseOnPagerHover: 0, // true to pause when hovering over pager link prev: null, // element, jQuery object, or jQuery selector string for the element to use as event trigger for previous slide prevNextEvent: 'click.cycle',// event which drives the manual transition to the previous or next slide random: 0, // true for random, false for sequence (not applicable to shuffle fx) randomizeEffects: 1, // valid when multiple effects are used; true to make the effect sequence random requeueOnImageNotLoaded: true, // requeue the slideshow if any image slides are not yet loaded requeueTimeout: 250, // ms delay for requeue rev: 0, // causes animations to transition in reverse (for effects that support it such as scrollHorz/scrollVert/shuffle) shuffle: null, // coords for shuffle animation, ex: { top:15, left: 200 } skipInitializationCallbacks: false, // set to true to disable the first before/after callback that occurs prior to any transition slideExpr: null, // expression for selecting slides (if something other than all children is required) slideResize: 1, // force slide width/height to fixed size before every transition speed: 1000, // speed of the transition (any valid fx speed value) speedIn: null, // speed of the 'in' transition speedOut: null, // speed of the 'out' transition startingSlide: undefined,// zero-based index of the first slide to be displayed sync: 1, // true if in/out transitions should occur simultaneously timeout: 4000, // milliseconds between slide transitions (0 to disable auto advance) timeoutFn: null, // callback for determining per-slide timeout value: function(currSlideElement, nextSlideElement, options, forwardFlag) updateActivePagerLink: null,// callback fn invoked to update the active pager link (adds/removes activePagerClass style) width: null // container width (if the 'fit' option is true, the slides will be set to this width as well) }; })(jQuery); /*! * jQuery Cycle Plugin Transition Definitions * This script is a plugin for the jQuery Cycle Plugin * Examples and documentation at: http://malsup.com/jquery/cycle/ * Copyright (c) 2007-2010 M. Alsup * Version: 2.73 * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html */ (function($) { "use strict"; // // These functions define slide initialization and properties for the named // transitions. To save file size feel free to remove any of these that you // don't need. // $.fn.cycle.transitions.none = function($cont, $slides, opts) { opts.fxFn = function(curr,next,opts,after){ $(next).show(); $(curr).hide(); after(); }; }; // not a cross-fade, fadeout only fades out the top slide $.fn.cycle.transitions.fadeout = function($cont, $slides, opts) { $slides.not(':eq('+opts.currSlide+')').css({ display: 'block', 'opacity': 1 }); opts.before.push(function(curr,next,opts,w,h,rev) { $(curr).css('zIndex',opts.slideCount + (rev !== true ? 1 : 0)); $(next).css('zIndex',opts.slideCount + (rev !== true ? 0 : 1)); }); opts.animIn.opacity = 1; opts.animOut.opacity = 0; opts.cssBefore.opacity = 1; opts.cssBefore.display = 'block'; opts.cssAfter.zIndex = 0; }; // scrollUp/Down/Left/Right $.fn.cycle.transitions.scrollUp = function($cont, $slides, opts) { $cont.css('overflow','hidden'); opts.before.push($.fn.cycle.commonReset); var h = $cont.height(); opts.cssBefore.top = h; opts.cssBefore.left = 0; opts.cssFirst.top = 0; opts.animIn.top = 0; opts.animOut.top = -h; }; $.fn.cycle.transitions.scrollDown = function($cont, $slides, opts) { $cont.css('overflow','hidden'); opts.before.push($.fn.cycle.commonReset); var h = $cont.height(); opts.cssFirst.top = 0; opts.cssBefore.top = -h; opts.cssBefore.left = 0; opts.animIn.top = 0; opts.animOut.top = h; }; $.fn.cycle.transitions.scrollLeft = function($cont, $slides, opts) { $cont.css('overflow','hidden'); opts.before.push($.fn.cycle.commonReset); var w = $cont.width(); opts.cssFirst.left = 0; opts.cssBefore.left = w; opts.cssBefore.top = 0; opts.animIn.left = 0; opts.animOut.left = 0-w; }; $.fn.cycle.transitions.scrollRight = function($cont, $slides, opts) { $cont.css('overflow','hidden'); opts.before.push($.fn.cycle.commonReset); var w = $cont.width(); opts.cssFirst.left = 0; opts.cssBefore.left = -w; opts.cssBefore.top = 0; opts.animIn.left = 0; opts.animOut.left = w; }; $.fn.cycle.transitions.scrollHorz = function($cont, $slides, opts) { $cont.css('overflow','hidden').width(); opts.before.push(function(curr, next, opts, fwd) { if (opts.rev) fwd = !fwd; $.fn.cycle.commonReset(curr,next,opts); opts.cssBefore.left = fwd ? (next.cycleW-1) : (1-next.cycleW); opts.animOut.left = fwd ? -curr.cycleW : curr.cycleW; }); opts.cssFirst.left = 0; opts.cssBefore.top = 0; opts.animIn.left = 0; opts.animOut.top = 0; }; $.fn.cycle.transitions.scrollVert = function($cont, $slides, opts) { $cont.css('overflow','hidden'); opts.before.push(function(curr, next, opts, fwd) { if (opts.rev) fwd = !fwd; $.fn.cycle.commonReset(curr,next,opts); opts.cssBefore.top = fwd ? (1-next.cycleH) : (next.cycleH-1); opts.animOut.top = fwd ? curr.cycleH : -curr.cycleH; }); opts.cssFirst.top = 0; opts.cssBefore.left = 0; opts.animIn.top = 0; opts.animOut.left = 0; }; // slideX/slideY $.fn.cycle.transitions.slideX = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $(opts.elements).not(curr).hide(); $.fn.cycle.commonReset(curr,next,opts,false,true); opts.animIn.width = next.cycleW; }); opts.cssBefore.left = 0; opts.cssBefore.top = 0; opts.cssBefore.width = 0; opts.animIn.width = 'show'; opts.animOut.width = 0; }; $.fn.cycle.transitions.slideY = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $(opts.elements).not(curr).hide(); $.fn.cycle.commonReset(curr,next,opts,true,false); opts.animIn.height = next.cycleH; }); opts.cssBefore.left = 0; opts.cssBefore.top = 0; opts.cssBefore.height = 0; opts.animIn.height = 'show'; opts.animOut.height = 0; }; // shuffle $.fn.cycle.transitions.shuffle = function($cont, $slides, opts) { var i, w = $cont.css('overflow', 'visible').width(); $slides.css({left: 0, top: 0}); opts.before.push(function(curr,next,opts) { $.fn.cycle.commonReset(curr,next,opts,true,true,true); }); // only adjust speed once! if (!opts.speedAdjusted) { opts.speed = opts.speed / 2; // shuffle has 2 transitions opts.speedAdjusted = true; } opts.random = 0; opts.shuffle = opts.shuffle || {left:-w, top:15}; opts.els = []; for (i=0; i < $slides.length; i++) opts.els.push($slides[i]); for (i=0; i < opts.currSlide; i++) opts.els.push(opts.els.shift()); // custom transition fn (hat tip to Benjamin Sterling for this bit of sweetness!) opts.fxFn = function(curr, next, opts, cb, fwd) { if (opts.rev) fwd = !fwd; var $el = fwd ? $(curr) : $(next); $(next).css(opts.cssBefore); var count = opts.slideCount; $el.animate(opts.shuffle, opts.speedIn, opts.easeIn, function() { var hops = $.fn.cycle.hopsFromLast(opts, fwd); for (var k=0; k < hops; k++) { if (fwd) opts.els.push(opts.els.shift()); else opts.els.unshift(opts.els.pop()); } if (fwd) { for (var i=0, len=opts.els.length; i < len; i++) $(opts.els[i]).css('z-index', len-i+count); } else { var z = $(curr).css('z-index'); $el.css('z-index', parseInt(z,10)+1+count); } $el.animate({left:0, top:0}, opts.speedOut, opts.easeOut, function() { $(fwd ? this : curr).hide(); if (cb) cb(); }); }); }; $.extend(opts.cssBefore, { display: 'block', opacity: 1, top: 0, left: 0 }); }; // turnUp/Down/Left/Right $.fn.cycle.transitions.turnUp = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,true,false); opts.cssBefore.top = next.cycleH; opts.animIn.height = next.cycleH; opts.animOut.width = next.cycleW; }); opts.cssFirst.top = 0; opts.cssBefore.left = 0; opts.cssBefore.height = 0; opts.animIn.top = 0; opts.animOut.height = 0; }; $.fn.cycle.transitions.turnDown = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,true,false); opts.animIn.height = next.cycleH; opts.animOut.top = curr.cycleH; }); opts.cssFirst.top = 0; opts.cssBefore.left = 0; opts.cssBefore.top = 0; opts.cssBefore.height = 0; opts.animOut.height = 0; }; $.fn.cycle.transitions.turnLeft = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,false,true); opts.cssBefore.left = next.cycleW; opts.animIn.width = next.cycleW; }); opts.cssBefore.top = 0; opts.cssBefore.width = 0; opts.animIn.left = 0; opts.animOut.width = 0; }; $.fn.cycle.transitions.turnRight = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,false,true); opts.animIn.width = next.cycleW; opts.animOut.left = curr.cycleW; }); $.extend(opts.cssBefore, { top: 0, left: 0, width: 0 }); opts.animIn.left = 0; opts.animOut.width = 0; }; // zoom $.fn.cycle.transitions.zoom = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,false,false,true); opts.cssBefore.top = next.cycleH/2; opts.cssBefore.left = next.cycleW/2; $.extend(opts.animIn, { top: 0, left: 0, width: next.cycleW, height: next.cycleH }); $.extend(opts.animOut, { width: 0, height: 0, top: curr.cycleH/2, left: curr.cycleW/2 }); }); opts.cssFirst.top = 0; opts.cssFirst.left = 0; opts.cssBefore.width = 0; opts.cssBefore.height = 0; }; // fadeZoom $.fn.cycle.transitions.fadeZoom = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,false,false); opts.cssBefore.left = next.cycleW/2; opts.cssBefore.top = next.cycleH/2; $.extend(opts.animIn, { top: 0, left: 0, width: next.cycleW, height: next.cycleH }); }); opts.cssBefore.width = 0; opts.cssBefore.height = 0; opts.animOut.opacity = 0; }; // blindX $.fn.cycle.transitions.blindX = function($cont, $slides, opts) { var w = $cont.css('overflow','hidden').width(); opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts); opts.animIn.width = next.cycleW; opts.animOut.left = curr.cycleW; }); opts.cssBefore.left = w; opts.cssBefore.top = 0; opts.animIn.left = 0; opts.animOut.left = w; }; // blindY $.fn.cycle.transitions.blindY = function($cont, $slides, opts) { var h = $cont.css('overflow','hidden').height(); opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts); opts.animIn.height = next.cycleH; opts.animOut.top = curr.cycleH; }); opts.cssBefore.top = h; opts.cssBefore.left = 0; opts.animIn.top = 0; opts.animOut.top = h; }; // blindZ $.fn.cycle.transitions.blindZ = function($cont, $slides, opts) { var h = $cont.css('overflow','hidden').height(); var w = $cont.width(); opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts); opts.animIn.height = next.cycleH; opts.animOut.top = curr.cycleH; }); opts.cssBefore.top = h; opts.cssBefore.left = w; opts.animIn.top = 0; opts.animIn.left = 0; opts.animOut.top = h; opts.animOut.left = w; }; // growX - grow horizontally from centered 0 width $.fn.cycle.transitions.growX = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,false,true); opts.cssBefore.left = this.cycleW/2; opts.animIn.left = 0; opts.animIn.width = this.cycleW; opts.animOut.left = 0; }); opts.cssBefore.top = 0; opts.cssBefore.width = 0; }; // growY - grow vertically from centered 0 height $.fn.cycle.transitions.growY = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,true,false); opts.cssBefore.top = this.cycleH/2; opts.animIn.top = 0; opts.animIn.height = this.cycleH; opts.animOut.top = 0; }); opts.cssBefore.height = 0; opts.cssBefore.left = 0; }; // curtainX - squeeze in both edges horizontally $.fn.cycle.transitions.curtainX = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,false,true,true); opts.cssBefore.left = next.cycleW/2; opts.animIn.left = 0; opts.animIn.width = this.cycleW; opts.animOut.left = curr.cycleW/2; opts.animOut.width = 0; }); opts.cssBefore.top = 0; opts.cssBefore.width = 0; }; // curtainY - squeeze in both edges vertically $.fn.cycle.transitions.curtainY = function($cont, $slides, opts) { opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,true,false,true); opts.cssBefore.top = next.cycleH/2; opts.animIn.top = 0; opts.animIn.height = next.cycleH; opts.animOut.top = curr.cycleH/2; opts.animOut.height = 0; }); opts.cssBefore.height = 0; opts.cssBefore.left = 0; }; // cover - curr slide covered by next slide $.fn.cycle.transitions.cover = function($cont, $slides, opts) { var d = opts.direction || 'left'; var w = $cont.css('overflow','hidden').width(); var h = $cont.height(); opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts); opts.cssAfter.display = ''; if (d == 'right') opts.cssBefore.left = -w; else if (d == 'up') opts.cssBefore.top = h; else if (d == 'down') opts.cssBefore.top = -h; else opts.cssBefore.left = w; }); opts.animIn.left = 0; opts.animIn.top = 0; opts.cssBefore.top = 0; opts.cssBefore.left = 0; }; // uncover - curr slide moves off next slide $.fn.cycle.transitions.uncover = function($cont, $slides, opts) { var d = opts.direction || 'left'; var w = $cont.css('overflow','hidden').width(); var h = $cont.height(); opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,true,true,true); if (d == 'right') opts.animOut.left = w; else if (d == 'up') opts.animOut.top = -h; else if (d == 'down') opts.animOut.top = h; else opts.animOut.left = -w; }); opts.animIn.left = 0; opts.animIn.top = 0; opts.cssBefore.top = 0; opts.cssBefore.left = 0; }; // toss - move top slide and fade away $.fn.cycle.transitions.toss = function($cont, $slides, opts) { var w = $cont.css('overflow','visible').width(); var h = $cont.height(); opts.before.push(function(curr, next, opts) { $.fn.cycle.commonReset(curr,next,opts,true,true,true); // provide default toss settings if animOut not provided if (!opts.animOut.left && !opts.animOut.top) $.extend(opts.animOut, { left: w*2, top: -h/2, opacity: 0 }); else opts.animOut.opacity = 0; }); opts.cssBefore.left = 0; opts.cssBefore.top = 0; opts.animIn.left = 0; }; // wipe - clip animation $.fn.cycle.transitions.wipe = function($cont, $slides, opts) { var w = $cont.css('overflow','hidden').width(); var h = $cont.height(); opts.cssBefore = opts.cssBefore || {}; var clip; if (opts.clip) { if (/l2r/.test(opts.clip)) clip = 'rect(0px 0px '+h+'px 0px)'; else if (/r2l/.test(opts.clip)) clip = 'rect(0px '+w+'px '+h+'px '+w+'px)'; else if (/t2b/.test(opts.clip)) clip = 'rect(0px '+w+'px 0px 0px)'; else if (/b2t/.test(opts.clip)) clip = 'rect('+h+'px '+w+'px '+h+'px 0px)'; else if (/zoom/.test(opts.clip)) { var top = parseInt(h/2,10); var left = parseInt(w/2,10); clip = 'rect('+top+'px '+left+'px '+top+'px '+left+'px)'; } } opts.cssBefore.clip = opts.cssBefore.clip || clip || 'rect(0px 0px 0px 0px)'; var d = opts.cssBefore.clip.match(/(\d+)/g); var t = parseInt(d[0],10), r = parseInt(d[1],10), b = parseInt(d[2],10), l = parseInt(d[3],10); opts.before.push(function(curr, next, opts) { if (curr == next) return; var $curr = $(curr), $next = $(next); $.fn.cycle.commonReset(curr,next,opts,true,true,false); opts.cssAfter.display = 'block'; var step = 1, count = parseInt((opts.speedIn / 13),10) - 1; (function f() { var tt = t ? t - parseInt(step * (t/count),10) : 0; var ll = l ? l - parseInt(step * (l/count),10) : 0; var bb = b < h ? b + parseInt(step * ((h-b)/count || 1),10) : h; var rr = r < w ? r + parseInt(step * ((w-r)/count || 1),10) : w; $next.css({ clip: 'rect('+tt+'px '+rr+'px '+bb+'px '+ll+'px)' }); (step++ <= count) ? setTimeout(f, 13) : $curr.css('display', 'none'); })(); }); $.extend(opts.cssBefore, { display: 'block', opacity: 1, top: 0, left: 0 }); opts.animIn = { left: 0 }; opts.animOut = { left: 0 }; }; })(jQuery);
JavaScript
function loadPage(id_div, url){ $(id_div).fadeIn("slow", function(){ $(id_div).load(url, function(){ $(id_div).fadeIn("slow"); }); }); } /** Calcula mi edad actual ;) */ function edadAc(){ var fecha = new Date (); var anio = fecha.getYear(); var mes = fecha.getMonth(); var edad = (anio + 1900) - 1986; if (mes <= 5){ edad = edad - 1; } document.getElementById('out_edad').innerHTML = edad; } function ocultarContenidos(){ $("#bio").hide(); $("#arte").hide(); $("#musica").hide(); $("#trabajos").hide(); $("#anoche").hide(); } function subirOtrosContenidos(){ $("#bio").slideUp("slow"); $("#arte").slideUp("slow"); $("#musica").slideUp("slow"); $("#trabajos").slideUp("slow"); $("#anoche").slideUp("slow"); //$("#seccion_fondo").slideUp("slow"); //alert('dd'); } function i(){ $('#seccion_bio').click(function(){ subirOtrosContenidos(); if ($("#bio").is(":hidden") || $("#seccion_fondo").is(":visible")) { /* Oculto las demas pestannas*/ $("#seccion_arte").slideUp(); $("#seccion_musica").slideUp(); $("#seccion_trabajos").slideUp(); $("#seccion_anoche").slideUp(); /* Muestra el contenido seleccionado */ $("#bio").fadeIn(); /* Oculto la imagen del cielo */ $("#seccion_fondo").slideUp(); loadPage('#contenido_bio', 'bio.html'); } else { /*$("#bio").fadeOut("slow");*/ $("#seccion_bio").slideDown(); $("#seccion_arte").slideDown(); $("#seccion_musica").slideDown(); $("#seccion_trabajos").slideDown(); $("#seccion_anoche").slideDown(); /* Muestra la imagen del cielo */ $("#seccion_fondo").slideDown(); } }); $('#seccion_arte').click(function(){ subirOtrosContenidos(); if ($("#arte").is(":hidden") || $("#seccion_fondo").is(":visible")) { /* Muestra el contenido seleccionado */ $("#arte").fadeIn(); /* Oculto las demas pestannas*/ $("#seccion_bio").slideUp(); $("#seccion_musica").slideUp(); $("#seccion_trabajos").slideUp(); $("#seccion_anoche").slideUp(); /* Oculto la imagen del cielo */ $("#seccion_fondo").slideUp(); loadPage('#contenido_arte', 'arte.html'); } else { $("#arte").hide(); $("#seccion_bio").slideDown(); $("#seccion_arte").slideDown(); $("#seccion_musica").slideDown(); $("#seccion_trabajos").slideDown(); $("#seccion_anoche").slideDown(); /* Muestra la imagen del cielo */ $("#seccion_fondo").slideDown(); } }); $('#seccion_musica').click(function(){ subirOtrosContenidos(); if ($("#musica").is(":hidden") || $("#seccion_fondo").is(":visible")) { /* Muestra el contenido seleccionado */ $("#musica").fadeIn(); /* Oculto las demas pestannas*/ $("#seccion_bio").slideUp(); $("#seccion_arte").slideUp(); $("#seccion_trabajos").slideUp(); $("#seccion_anoche").slideUp(); /* Oculto la imagen del cielo */ $("#seccion_fondo").slideUp(); loadPage('#contenido_musica', 'musica.html'); } else { $("#musica").fadeOut("slow"); $("#seccion_bio").slideDown(); $("#seccion_arte").slideDown(); $("#seccion_musica").slideDown(); $("#seccion_trabajos").slideDown(); $("#seccion_anoche").slideDown(); /* Muestra la imagen del cielo */ $("#seccion_fondo").slideDown(); } }); $('#seccion_trabajos').click(function(){ subirOtrosContenidos(); if ($("#trabajos").is(":hidden") || $("#seccion_fondo").is(":visible")) { /* Muestra el contenido seleccionado */ $("#trabajos").fadeIn(); /* Oculto las demas pestannas*/ $("#seccion_bio").slideUp(); $("#seccion_arte").slideUp(); $("#seccion_musica").slideUp(); $("#seccion_anoche").slideUp(); /* Oculto la imagen del cielo */ $("#seccion_fondo").slideUp(); loadPage('#contenido_trabajos', 'trabajos.html'); } else { $("#trabajos").fadeOut(); $("#seccion_bio").slideDown(); $("#seccion_arte").slideDown(); $("#seccion_musica").slideDown(); $("#seccion_trabajos").slideDown(); $("#seccion_anoche").slideDown(); /* Muestra la imagen del cielo */ $("#seccion_fondo").slideDown(); } }); $('#seccion_anoche').click(function(){ subirOtrosContenidos(); if ($("#anoche").is(":hidden") || $("#seccion_fondo").is(":visible")) { /* Muestra el contenido seleccionado */ $("#anoche").fadeIn(); /* Oculto las demas pestannas*/ $("#seccion_bio").slideUp(); $("#seccion_arte").slideUp(); $("#seccion_musica").slideUp(); $("#seccion_trabajos").slideUp(); /* Oculto la imagen del cielo */ $("#seccion_fondo").slideUp(); loadPage('#contenido_anoche', 'anoche.html'); } else { $("#anoche").fadeOut("slow"); $("#seccion_bio").slideDown(); $("#seccion_arte").slideDown(); $("#seccion_musica").slideDown(); $("#seccion_trabajos").slideDown(); $("#seccion_anoche").slideDown(); /* Muestra la imagen del cielo */ $("#seccion_fondo").slideDown(); } }); cargarSeccion(); inicializarGlobo(); } function inicializarGlobo(){ $("#menu_despl").fadeOut(); $('#globo').click(function(){ if ($("#menu_despl").css('display') == 'none'){ //$("#menu_despl").css('visibility', 'visible'); $("#menu_despl").fadeIn(); }else { //$("#menu_despl").css('visibility','hidden'); $("#menu_despl").fadeOut(); } }); $(document).click(function (event) { $('#menu_despl').fadeOut(); }); $("#menu_despl").click(function(e) { e.stopPropagation(); return false; }); $("#globo").click(function(e) { e.stopPropagation(); return false; }); } function cargarSeccion(){ var param = getURLParameter("seccion"); if (param != "null"){ ocultarContenidos(); $('#seccion_'+param).click(); //alert(param); }else { //subirOtrosContenidos(); } } function getURLParameter(name) { return decodeURI( (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1] ); }
JavaScript
var Wami = window.Wami || {}; // Upon a creation of a new Wami.GUI(options), we assume that a WAMI recorder // has been initialized. Wami.GUI = function(options) { var RECORD_BUTTON = 1; var PLAY_BUTTON = 2; setOptions(options); setupDOM(); var recordButton, playButton; var recordInterval, playInterval; function createDiv(id, style) { var div = document.createElement("div"); if (id) { div.setAttribute('id', id); } if (style) { div.style.cssText = style; } return div; } function setOptions(options) { if (!options.buttonUrl) { options.buttonUrl = "buttons.png"; } if (typeof options.listen == 'undefined' || options.listen) { listen(); } } function setupDOM() { var guidiv = createDiv(null, "position: absolute; width: 214px; height: 137px;"); document.getElementById(options.id).appendChild(guidiv); var rid = Wami.createID(); var recordDiv = createDiv(rid, "position: absolute; left: 40px; top: 25px"); guidiv.appendChild(recordDiv); recordButton = new Button(rid, RECORD_BUTTON, options.buttonUrl); recordButton.onstart = startRecording; recordButton.onstop = stopRecording; recordButton.setEnabled(true); if (!options.singleButton) { var pid = Wami.createID(); var playDiv = createDiv(pid, "position: absolute; right: 40px; top: 25px"); guidiv.appendChild(playDiv); playButton = new Button(pid, PLAY_BUTTON, options.buttonUrl); playButton.onstart = startPlaying; playButton.onstop = stopPlaying; } } /** * These methods are called on clicks from the GUI. */ function startRecording() { if (!options.recordUrl) { alert("No record Url specified!"); } recordButton.setActivity(0); playButton.setEnabled(false); Wami.startRecording(options.recordUrl, Wami.nameCallback(onRecordStart), Wami .nameCallback(onRecordFinish), Wami .nameCallback(onError)); } function stopRecording() { Wami.stopRecording(); clearInterval(recordInterval); recordButton.setEnabled(true); } function startPlaying() { if (!options.playUrl) { alert('No play URL specified!'); } playButton.setActivity(0); recordButton.setEnabled(false); Wami.startPlaying(options.playUrl, Wami.nameCallback(onPlayStart), Wami .nameCallback(onPlayFinish), Wami.nameCallback(onError)); } function stopPlaying() { Wami.stopPlaying(); } this.setPlayUrl = function(url) { options.playUrl = url; } this.setRecordUrl = function(url) { options.recordUrl = url; } this.setPlayEnabled = function(val) { playButton.setEnabled(val); } this.setRecordEnabled = function(val) { recordButton.setEnabled(val); } /** * Callbacks from the flash indicating certain events */ function onError(e) { alert(e); } function onRecordStart() { recordInterval = setInterval(function() { if (recordButton.isActive()) { var level = Wami.getRecordingLevel(); recordButton.setActivity(level); } }, 200); if (options.onRecordStart) { options.onRecordStart(); } } function onRecordFinish() { playButton.setEnabled(true); if (options.onRecordFinish) { options.onRecordFinish(); } } function onPlayStart() { playInterval = setInterval(function() { if (playButton.isActive()) { var level = Wami.getPlayingLevel(); playButton.setActivity(level); } }, 200); if (options.onPlayStart) { options.onPlayStart(); } } function onPlayFinish() { clearInterval(playInterval); recordButton.setEnabled(true); playButton.setEnabled(true); if (options.onPlayFinish) { options.onPlayFinish(); } } function listen() { Wami.startListening(); // Continually listening when the window is in focus allows us to // buffer a little audio before the users clicks, since sometimes // people talk too soon. Without "listening", the audio would record // exactly when startRecording() is called. window.onfocus = function() { Wami.startListening(); }; // Note that the use of onfocus and onblur should probably be replaced // with a more robust solution (e.g. jQuery's $(window).focus(...) window.onblur = function() { Wami.stopListening(); }; } function Button(buttonid, type, url) { var self = this; self.active = false; self.type = type; init(); // Get the background button image position // Index: 1) normal 2) pressed 3) mouse-over function background(index) { if (index == 1) return "-56px 0px"; if (index == 2) return "0px 0px"; if (index == 3) return "-112px 0"; alert("Background not found: " + index); } // Get the type of meter and its state // Index: 1) enabled 2) meter 3) disabled function meter(index, offset) { var top = 5; if (offset) top += offset; if (self.type == RECORD_BUTTON) { if (index == 1) return "-169px " + top + "px"; if (index == 2) return "-189px " + top + "px"; if (index == 3) return "-249px " + top + "px"; } else { if (index == 1) return "-269px " + top + "px"; if (index == 2) return "-298px " + top + "px"; if (index == 3) return "-327px " + top + "px"; } alert("Meter not found: " + self.type + " " + index); } function silhouetteWidth() { if (self.type == RECORD_BUTTON) { return "20px"; } else { return "29px"; } } function mouseHandler(e) { var rightclick; if (!e) var e = window.event; if (e.which) rightclick = (e.which == 3); else if (e.button) rightclick = (e.button == 2); if (!rightclick) { if (self.active && self.onstop) { self.active = false; self.onstop(); } else if (!self.active && self.onstart) { self.active = true; self.onstart(); } } } function init() { var div = document.createElement("div"); var elem = document.getElementById(buttonid); if (elem) { elem.appendChild(div); } else { alert('Could not find element on page named ' + buttonid); } self.guidiv = document.createElement("div"); self.guidiv.style.width = '56px'; self.guidiv.style.height = '63px'; self.guidiv.style.cursor = 'pointer'; self.guidiv.style.background = "url(" + url + ") no-repeat"; self.guidiv.style.backgroundPosition = background(1); div.appendChild(self.guidiv); // margin auto doesn't work in IE quirks mode // http://stackoverflow.com/questions/816343/why-will-this-div-img-not-center-in-ie8 // text-align is a hack to force it to work even if you forget the // doctype. self.guidiv.style.textAlign = 'center'; self.meterDiv = document.createElement("div"); self.meterDiv.style.width = silhouetteWidth(); self.meterDiv.style.height = '63px'; self.meterDiv.style.margin = 'auto'; self.meterDiv.style.cursor = 'pointer'; self.meterDiv.style.position = 'relative'; self.meterDiv.style.background = "url(" + url + ") no-repeat"; self.meterDiv.style.backgroundPosition = meter(2); self.guidiv.appendChild(self.meterDiv); self.coverDiv = document.createElement("div"); self.coverDiv.style.width = silhouetteWidth(); self.coverDiv.style.height = '63px'; self.coverDiv.style.margin = 'auto'; self.coverDiv.style.cursor = 'pointer'; self.coverDiv.style.position = 'relative'; self.coverDiv.style.background = "url(" + url + ") no-repeat"; self.coverDiv.style.backgroundPosition = meter(1); self.meterDiv.appendChild(self.coverDiv); self.active = false; self.guidiv.onmousedown = mouseHandler; } self.isActive = function() { return self.active; } self.setActivity = function(level) { self.guidiv.onmouseout = function() { }; self.guidiv.onmouseover = function() { }; self.guidiv.style.backgroundPosition = background(2); self.coverDiv.style.backgroundPosition = meter(1, 5); self.meterDiv.style.backgroundPosition = meter(2, 5); var totalHeight = 31; var maxHeight = 9; // When volume goes up, the black image loses height, // creating the perception of the colored one increasing. var height = (maxHeight + totalHeight - Math.floor(level / 100 * totalHeight)); self.coverDiv.style.height = height + "px"; } self.setEnabled = function(enable) { var guidiv = self.guidiv; self.active = false; if (enable) { self.coverDiv.style.backgroundPosition = meter(1); self.meterDiv.style.backgroundPosition = meter(1); guidiv.style.backgroundPosition = background(1); guidiv.onmousedown = mouseHandler; guidiv.onmouseover = function() { guidiv.style.backgroundPosition = background(3); }; guidiv.onmouseout = function() { guidiv.style.backgroundPosition = background(1); }; } else { self.coverDiv.style.backgroundPosition = meter(3); self.meterDiv.style.backgroundPosition = meter(3); guidiv.style.backgroundPosition = background(1); guidiv.onmousedown = null; guidiv.onmouseout = function() { }; guidiv.onmouseover = function() { }; } } } }
JavaScript
var Wami = window.Wami || {}; // Returns a (very likely) unique string with of random letters and numbers Wami.createID = function() { return "wid" + ("" + 1e10).replace(/[018]/g, function(a) { return (a ^ Math.random() * 16 >> a / 4).toString(16) }); } // Creates a named callback in WAMI and returns the name as a string. Wami.nameCallback = function(cb, cleanup) { Wami._callbacks = Wami._callbacks || {}; var id = Wami.createID(); Wami._callbacks[id] = function() { if (cleanup) { Wami._callbacks[id] = null; } cb.apply(null, arguments); }; var named = "Wami._callbacks['" + id + "']"; return named; } // This method ensures that a WAMI recorder is operational, and that // the following API is available in the Wami namespace. All functions // must be named (i.e. cannot be anonymous). // // Wami.startPlaying(url, startfn = null, finishedfn = null, failedfn = null); // Wami.stopPlaying() // // Wami.startRecording(url, startfn = null, finishedfn = null, failedfn = null); // Wami.stopRecording() // // Wami.getRecordingLevel() // Returns a number between 0 and 100 // Wami.getPlayingLevel() // Returns a number between 0 and 100 // // Wami.hide() // Wami.show() // // Manipulate the WAMI recorder's settings. In Flash // we need to check if the microphone permission has been granted. // We might also set/return sample rate here, etc. // // Wami.getSettings(); // Wami.setSettings(options); // // Optional way to set up browser so that it's constantly listening // This is to prepend audio in case the user starts talking before // they click-to-talk. // // Wami.startListening() // Wami.setup = function(options) { if (Wami.startRecording) { // Wami's already defined. if (options.onReady) { options.onReady(); } return; } // Assumes that swfobject.js is included if Wami.swfobject isn't // already defined. Wami.swfobject = Wami.swfobject || swfobject; if (!Wami.swfobject) { alert("Unable to find swfobject to help embed the SWF."); } var _options; setOptions(options); embedWamiSWF(_options.id, Wami.nameCallback(delegateWamiAPI)); function supportsTransparency() { // Detecting the OS is a big no-no in Javascript programming, but // I can't think of a better way to know if wmode is supported or // not... since NOT supporting it (like Flash on Ubuntu) is a bug. return (navigator.platform.indexOf("Linux") == -1); } function setOptions(options) { // Start with default options _options = { swfUrl : "Wami.swf", onReady : function() { Wami.hide(); }, onSecurity : checkSecurity, onError : function(error) { alert(error); } }; if (typeof options == 'undefined') { alert('Need at least an element ID to place the Flash object.'); } if (typeof options == 'string') { _options.id = options; } else { _options.id = options.id; } if (options.swfUrl) { _options.swfUrl = options.swfUrl; } if (options.onReady) { _options.onReady = options.onReady; } if (options.onLoaded) { _options.onLoaded = options.onLoaded; } if (options.onSecurity) { _options.onSecurity = options.onSecurity; } if (options.onError) { _options.onError = options.onError; } // Create a DIV for the SWF under _options.id var container = document.createElement('div'); container.style.position = 'absolute'; _options.cid = Wami.createID(); container.setAttribute('id', _options.cid); var swfdiv = document.createElement('div'); var id = Wami.createID(); swfdiv.setAttribute('id', id); container.appendChild(swfdiv); document.getElementById(_options.id).appendChild(container); _options.id = id; } function checkSecurity() { var settings = Wami.getSettings(); if (settings.microphone.granted) { _options.onReady(); } else { // Show any Flash settings panel you want: // http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/system/SecurityPanel.html Wami.showSecurity("privacy", "Wami.show", Wami .nameCallback(_options.onSecurity), Wami .nameCallback(_options.onError)); } } // Embed the WAMI SWF and call the named callback function when loaded. function embedWamiSWF(id, initfn) { var flashVars = { visible : false, loadedCallback : initfn } var params = { allowScriptAccess : "always" } if (supportsTransparency()) { params.wmode = "transparent"; } if (typeof console !== 'undefined') { flashVars.console = true; } var version = '10.0.0'; document.getElementById(id).innerHTML = "WAMI requires Flash " + version + " or greater<br />https://get.adobe.com/flashplayer/"; // This is the minimum size due to the microphone security panel Wami.swfobject.embedSWF(_options.swfUrl, id, 214, 137, version, null, flashVars, params); // Without this line, Firefox has a dotted outline of the flash Wami.swfobject.createCSS("#" + id, "outline:none"); } // To check if the microphone settings were 'remembered', we // must actually embed an entirely new Wami client and check // whether its microphone is granted. If it is, it was remembered. function checkRemembered(finishedfn) { var id = Wami.createID(); var div = document.createElement('div'); div.style.top = '-999px'; div.style.left = '-999px'; div.setAttribute('id', id); var body = document.getElementsByTagName('body').item(0); body.appendChild(div); var fn = Wami.nameCallback(function() { var swf = document.getElementById(id); Wami._remembered = swf.getSettings().microphone.granted; Wami.swfobject.removeSWF(id); eval(finishedfn + "()"); }); embedWamiSWF(id, fn); } // Attach all the audio methods to the Wami namespace in the callback. function delegateWamiAPI() { var recorder = document.getElementById(_options.id); function delegate(name) { Wami[name] = function() { return recorder[name].apply(recorder, arguments); } } delegate('startPlaying'); delegate('stopPlaying'); delegate('startRecording'); delegate('stopRecording'); delegate('startListening'); delegate('stopListening'); delegate('getRecordingLevel'); delegate('getPlayingLevel'); delegate('setSettings'); // Append extra information about whether mic settings are sticky Wami.getSettings = function() { var settings = recorder.getSettings(); settings.microphone.remembered = Wami._remembered; return settings; } Wami.showSecurity = function(panel, startfn, finishedfn, failfn) { // Flash must be on top for this. var container = document.getElementById(_options.cid); var augmentedfn = Wami.nameCallback(function() { checkRemembered(finishedfn); container.style.cssText = "position: absolute;"; }); container.style.cssText = "position: absolute; z-index: 99999"; recorder.showSecurity(panel, startfn, augmentedfn, failfn); } Wami.show = function() { if (!supportsTransparency()) { recorder.style.visibility = "visible"; } } Wami.hide = function() { // Hiding flash in all the browsers is tricky. Please read: // https://code.google.com/p/wami-recorder/wiki/HidingFlash if (!supportsTransparency()) { recorder.style.visibility = "hidden"; } } // If we already have permissions, they were previously 'remembered' Wami._remembered = recorder.getSettings().microphone.granted; if (_options.onLoaded) { _options.onLoaded(); } if (!_options.noSecurityCheck) { checkSecurity(); } } }
JavaScript
/*! * jQuery JavaScript Library v2.0.3 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-07-03T13:30Z */ (function( window, undefined ) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ //"use strict"; var // A central reference to the root jQuery(document) rootjQuery, // The deferred used on DOM ready readyList, // Support: IE9 // For `typeof xmlNode.method` instead of `xmlNode.method !== undefined` core_strundefined = typeof undefined, // Use the correct document accordingly with window argument (sandbox) location = window.location, document = window.document, docElem = document.documentElement, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // [[Class]] -> type pairs class2type = {}, // List of deleted data cache ids, so we can reuse them core_deletedIds = [], core_version = "2.0.3", // Save a reference to some core methods core_concat = core_deletedIds.concat, core_push = core_deletedIds.push, core_slice = core_deletedIds.slice, core_indexOf = core_deletedIds.indexOf, core_toString = class2type.toString, core_hasOwn = class2type.hasOwnProperty, core_trim = core_version.trim, // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Used for matching numbers core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, // Used for splitting on whitespace core_rnotwhite = /\S+/g, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }, // The ready event handler and self cleanup method completed = function() { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); jQuery.ready(); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: core_version, constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return core_slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, slice: function() { return this.pushStack( core_slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: core_push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ // Unique for each copy of jQuery on the page expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger("ready").off("ready"); } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray, isWindow: function( obj ) { return obj != null && obj === obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { if ( obj == null ) { return String( obj ); } // Support: Safari <= 5.1 (functionish RegExp) return typeof obj === "object" || typeof obj === "function" ? class2type[ core_toString.call(obj) ] || "object" : typeof obj; }, isPlainObject: function( obj ) { // Not plain objects: // - Any object or value whose internal [[Class]] property is not "[object Object]" // - DOM nodes // - window if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } // Support: Firefox <20 // The try/catch suppresses exceptions thrown when attempting to access // the "constructor" property of certain host objects, ie. |window.location| // https://bugzilla.mozilla.org/show_bug.cgi?id=814622 try { if ( obj.constructor && !core_hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) { return false; } } catch ( e ) { return false; } // If the function hasn't returned already, we're confident that // |obj| is a plain object, created by {} or constructed with new Object return true; }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string parseHTML: function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }, parseJSON: JSON.parse, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } // Support: IE9 try { tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } catch ( e ) { xml = undefined; } if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context globalEval: function( code ) { var script, indirect = eval; code = jQuery.trim( code ); if ( code ) { // If the code includes a valid, prologue position // strict mode pragma, execute code by injecting a // script tag into the document. if ( code.indexOf("use strict") === 1 ) { script = document.createElement("script"); script.text = code; document.head.appendChild( script ).parentNode.removeChild( script ); } else { // Otherwise, avoid the DOM node creation, insertion // and removal by using an indirect global eval indirect( code ); } } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, trim: function( text ) { return text == null ? "" : core_trim.call( text ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { core_push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { return arr == null ? -1 : core_indexOf.call( arr, elem, i ); }, merge: function( first, second ) { var l = second.length, i = first.length, j = 0; if ( typeof l === "number" ) { for ( ; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var retVal, ret = [], i = 0, length = elems.length; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return core_concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = core_slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function access: function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, length = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < length; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: Date.now, // A method for quickly swapping in/out CSS properties to get correct calculations. // Note: this method belongs to the css module but it's needed here for the support module. // If support gets modularized, this method should be moved back to the css module. swap: function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; } }); jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); } else { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); } } return readyList.promise( obj ); }; // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || type !== "function" && ( length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj ); } // All jQuery objects should point back to these rootjQuery = jQuery(document); /*! * Sizzle CSS Selector Engine v1.9.4-pre * http://sizzlejs.com/ * * Copyright 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-06-03 */ (function( window, undefined ) { var i, support, cachedruns, Expr, getText, isXML, compile, outermostContext, sortInput, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), hasDuplicate = false, sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } return 0; }, // General-purpose constants strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf if we can't use a native one indexOf = arr.indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments quoted, // then not containing pseudos/brackets, // then attribute selectors/non-parenthetical expressions, // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rsibling = new RegExp( whitespace + "*[+~]" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rescape = /'|\\/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : // BMP codepoint high < 0 ? String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }; // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; results = results || []; if ( !selector || typeof selector !== "string" ) { return results; } if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( documentIsHTML && !seed ) { // Shortcuts if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // QSA path if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { nid = old = expando; newContext = context; newSelector = nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + toSelector( groups[i] ); } newContext = rsibling.test( selector ) && context.parentNode || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key += " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return !!fn( div ); } catch (e) { return false; } finally { // Remove from its parent by default if ( div.parentNode ) { div.parentNode.removeChild( div ); } // release memory in IE div = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = attrs.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Detect xml * @param {Element|Object} elem An element or a document */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; // Expose support vars for convenience support = Sizzle.support = {}; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var doc = node ? node.ownerDocument || node : preferredDoc, parent = doc.defaultView; // If no document and documentElement is available, return if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Set our document document = doc; docElem = doc.documentElement; // Support tests documentIsHTML = !isXML( doc ); // Support: IE>8 // If iframe document is assigned to "document" variable and if iframe has been reloaded, // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 // IE6-8 do not support the defaultView property so parent will be undefined if ( parent && parent.attachEvent && parent !== parent.top ) { parent.attachEvent( "onbeforeunload", function() { setDocument(); }); } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) support.attributes = assert(function( div ) { div.className = "i"; return !div.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Check if getElementsByClassName can be trusted support.getElementsByClassName = assert(function( div ) { div.innerHTML = "<div class='a'></div><div class='a i'></div>"; // Support: Safari<4 // Catch class over-caching div.firstChild.className = "i"; // Support: Opera<10 // Catch gEBCN failure to find non-leading classes return div.getElementsByClassName("i").length === 2; }); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( div ) { docElem.appendChild( div ).id = expando; return !doc.getElementsByName || !doc.getElementsByName( expando ).length; }); // ID find and filter if ( support.getById ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && documentIsHTML ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { // Support: IE6/7 // getElementById is not reliable as a find shortcut delete Expr.find["ID"]; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See http://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select><option selected=''></option></select>"; // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Support: Opera 10-12/IE8 // ^= $= *= and empty values // Should not select anything // Support: Windows 8 Native Apps // The type attribute is restricted during .innerHTML assignment var input = doc.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "t", "" ); if ( div.querySelectorAll("[t^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = rnative.test( (matches = docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = rnative.test( docElem.contains ) || docElem.compareDocumentPosition ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = docElem.compareDocumentPosition ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b ); if ( compare ) { // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === doc || contains(preferredDoc, a) ) { return -1; } if ( b === doc || contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } // Not directly comparable, sort on existence of method return a.compareDocumentPosition ? -1 : 1; } : function( a, b ) { var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; // Parentless nodes are either documents or disconnected } else if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return doc; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, document, null, [elem] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val === undefined ? support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null : val; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array for ( ; (node = elem[i]); i++ ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[5] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] && match[4] !== undefined ) { match[2] = match[4]; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index outerCache = parent[ expando ] || (parent[ expando ] = {}); cache = outerCache[ type ] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = cache[0] === dirruns && cache[2]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { outerCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } // Use previously-cached element index if available } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { diff = cache[1]; // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( tokens = [] ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); } function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var data, cache, outerCache, dirkey = dirruns + " " + doneName; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) { if ( (data = cache[1]) === true || data === cachedruns ) { return data === true; } } else { cache = outerCache[ dir ] = [ dirkey ]; cache[1] = matcher( elem, context, xml ) || cachedruns; if ( cache[1] === true ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { // A counter to specify which element is currently being matched var matcherCachedRuns = 0, bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, expandContext ) { var elem, j, matcher, setMatched = [], matchedCount = 0, i = "0", unmatched = seed && [], outermost = expandContext != null, contextBackup = outermostContext, // We must always have either seed elements or context elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); if ( outermost ) { outermostContext = context !== document && context; cachedruns = matcherCachedRuns; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below for ( ; (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; cachedruns = ++matcherCachedRuns; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !group ) { group = tokenize( selector ); } i = group.length; while ( i-- ) { cached = matcherFromTokens( group[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); } return cached; }; function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function select( selector, context, results, seed ) { var i, tokens, token, type, find, match = tokenize( selector ); if ( !seed ) { // Try to minimize operations if there is only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && context.parentNode || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } } // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile( selector, match )( seed, context, !documentIsHTML, results, rsibling.test( selector ) ); return results; } // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Support: Chrome<14 // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( div1 ) { // Should return 1, but returns 4 (following) return div1.compareDocumentPosition( document.createElement("div") ) & 1; }); // Support: IE<8 // Prevent attribute/property "interpolation" // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild.getAttribute("href") === "#" ; }) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } }); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert(function( div ) { div.innerHTML = "<input/>"; div.firstChild.setAttribute( "value", "" ); return div.firstChild.getAttribute( "value" ) === ""; }) ) { addHandle( "value", function( elem, name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } }); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert(function( div ) { return div.getAttribute("disabled") == null; }) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return (val = elem.getAttributeNode( name )) && val.specified ? val.value : elem[ name ] === true ? name.toLowerCase() : null; } }); } jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })( window ); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; firingLength = 0; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( list && ( !fired || stack ) ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var action = tuple[ 0 ], fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = core_slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; if( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); jQuery.support = (function( support ) { var input = document.createElement("input"), fragment = document.createDocumentFragment(), div = document.createElement("div"), select = document.createElement("select"), opt = select.appendChild( document.createElement("option") ); // Finish early in limited environments if ( !input.type ) { return support; } input.type = "checkbox"; // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3 // Check the default checkbox/radio value ("" on old WebKit; "on" elsewhere) support.checkOn = input.value !== ""; // Must access the parent to make an option select properly // Support: IE9, IE10 support.optSelected = opt.selected; // Will be defined later support.reliableMarginRight = true; support.boxSizingReliable = true; support.pixelPosition = false; // Make sure checked status is properly cloned // Support: IE9, IE10 input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Check if an input maintains its value after becoming a radio // Support: IE9, IE10 input = document.createElement("input"); input.value = "t"; input.type = "radio"; support.radioValue = input.value === "t"; // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "checked", "t" ); input.setAttribute( "name", "t" ); fragment.appendChild( input ); // Support: Safari 5.1, Android 4.x, Android 2.3 // old WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: Firefox, Chrome, Safari // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) support.focusinBubbles = "onfocusin" in window; div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Run tests that need a body at doc ready jQuery(function() { var container, marginDiv, // Support: Firefox, Android 2.3 (Prefixed box-sizing versions). divReset = "padding:0;margin:0;border:0;display:block;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box", body = document.getElementsByTagName("body")[ 0 ]; if ( !body ) { // Return for frameset docs that don't have a body return; } container = document.createElement("div"); container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; // Check box-sizing and margin behavior. body.appendChild( container ).appendChild( div ); div.innerHTML = ""; // Support: Firefox, Android 2.3 (Prefixed box-sizing versions). div.style.cssText = "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%"; // Workaround failing boxSizing test due to offsetWidth returning wrong value // with some non-1 values of body zoom, ticket #13543 jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() { support.boxSizing = div.offsetWidth === 4; }); // Use window.getComputedStyle because jsdom on node.js will break without it. if ( window.getComputedStyle ) { support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Support: Android 2.3 // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = div.appendChild( document.createElement("div") ); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } body.removeChild( container ); }); return support; })( {} ); /* Implementation Summary 1. Enforce API surface and semantic compatibility with 1.9.x branch 2. Improve the module's maintainability by reducing the storage paths to a single mechanism. 3. Use the same single mechanism to support "private" and "user" data. 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) 5. Avoid exposing implementation details on user objects (eg. expando properties) 6. Provide a clear path for implementation upgrade to WeakMap in 2014 */ var data_user, data_priv, rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; function Data() { // Support: Android < 4, // Old WebKit does not have Object.preventExtensions/freeze method, // return new empty object instead with no [[set]] accessor Object.defineProperty( this.cache = {}, 0, { get: function() { return {}; } }); this.expando = jQuery.expando + Math.random(); } Data.uid = 1; Data.accepts = function( owner ) { // Accepts only: // - Node // - Node.ELEMENT_NODE // - Node.DOCUMENT_NODE // - Object // - Any return owner.nodeType ? owner.nodeType === 1 || owner.nodeType === 9 : true; }; Data.prototype = { key: function( owner ) { // We can accept data for non-element nodes in modern browsers, // but we should not, see #8335. // Always return the key for a frozen object. if ( !Data.accepts( owner ) ) { return 0; } var descriptor = {}, // Check if the owner object already has a cache key unlock = owner[ this.expando ]; // If not, create one if ( !unlock ) { unlock = Data.uid++; // Secure it in a non-enumerable, non-writable property try { descriptor[ this.expando ] = { value: unlock }; Object.defineProperties( owner, descriptor ); // Support: Android < 4 // Fallback to a less secure definition } catch ( e ) { descriptor[ this.expando ] = unlock; jQuery.extend( owner, descriptor ); } } // Ensure the cache object if ( !this.cache[ unlock ] ) { this.cache[ unlock ] = {}; } return unlock; }, set: function( owner, data, value ) { var prop, // There may be an unlock assigned to this node, // if there is no entry for this "owner", create one inline // and set the unlock as though an owner entry had always existed unlock = this.key( owner ), cache = this.cache[ unlock ]; // Handle: [ owner, key, value ] args if ( typeof data === "string" ) { cache[ data ] = value; // Handle: [ owner, { properties } ] args } else { // Fresh assignments by object are shallow copied if ( jQuery.isEmptyObject( cache ) ) { jQuery.extend( this.cache[ unlock ], data ); // Otherwise, copy the properties one-by-one to the cache object } else { for ( prop in data ) { cache[ prop ] = data[ prop ]; } } } return cache; }, get: function( owner, key ) { // Either a valid cache is found, or will be created. // New caches will be created and the unlock returned, // allowing direct access to the newly created // empty data object. A valid owner object must be provided. var cache = this.cache[ this.key( owner ) ]; return key === undefined ? cache : cache[ key ]; }, access: function( owner, key, value ) { var stored; // In cases where either: // // 1. No key was specified // 2. A string key was specified, but no value provided // // Take the "read" path and allow the get method to determine // which value to return, respectively either: // // 1. The entire cache object // 2. The data stored at the key // if ( key === undefined || ((key && typeof key === "string") && value === undefined) ) { stored = this.get( owner, key ); return stored !== undefined ? stored : this.get( owner, jQuery.camelCase(key) ); } // [*]When the key is not a string, or both a key and value // are specified, set or extend (existing objects) with either: // // 1. An object of properties // 2. A key and value // this.set( owner, key, value ); // Since the "set" path can have two possible entry points // return the expected data based on which path was taken[*] return value !== undefined ? value : key; }, remove: function( owner, key ) { var i, name, camel, unlock = this.key( owner ), cache = this.cache[ unlock ]; if ( key === undefined ) { this.cache[ unlock ] = {}; } else { // Support array or space separated string of keys if ( jQuery.isArray( key ) ) { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = key.concat( key.map( jQuery.camelCase ) ); } else { camel = jQuery.camelCase( key ); // Try the string as a key before any manipulation if ( key in cache ) { name = [ key, camel ]; } else { // If a key with the spaces exists, use it. // Otherwise, create an array by matching non-whitespace name = camel; name = name in cache ? [ name ] : ( name.match( core_rnotwhite ) || [] ); } } i = name.length; while ( i-- ) { delete cache[ name[ i ] ]; } } }, hasData: function( owner ) { return !jQuery.isEmptyObject( this.cache[ owner[ this.expando ] ] || {} ); }, discard: function( owner ) { if ( owner[ this.expando ] ) { delete this.cache[ owner[ this.expando ] ]; } } }; // These may be used throughout the jQuery core codebase data_user = new Data(); data_priv = new Data(); jQuery.extend({ acceptData: Data.accepts, hasData: function( elem ) { return data_user.hasData( elem ) || data_priv.hasData( elem ); }, data: function( elem, name, data ) { return data_user.access( elem, name, data ); }, removeData: function( elem, name ) { data_user.remove( elem, name ); }, // TODO: Now that all calls to _data and _removeData have been replaced // with direct calls to data_priv methods, these can be deprecated. _data: function( elem, name, data ) { return data_priv.access( elem, name, data ); }, _removeData: function( elem, name ) { data_priv.remove( elem, name ); } }); jQuery.fn.extend({ data: function( key, value ) { var attrs, name, elem = this[ 0 ], i = 0, data = null; // Gets all values if ( key === undefined ) { if ( this.length ) { data = data_user.get( elem ); if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) { attrs = elem.attributes; for ( ; i < attrs.length; i++ ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } data_priv.set( elem, "hasDataAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { data_user.set( this, key ); }); } return jQuery.access( this, function( value ) { var data, camelKey = jQuery.camelCase( key ); // The calling jQuery object (element matches) is not empty // (and therefore has an element appears at this[ 0 ]) and the // `value` parameter was not undefined. An empty jQuery object // will result in `undefined` for elem = this[ 0 ] which will // throw an exception if an attempt to read a data cache is made. if ( elem && value === undefined ) { // Attempt to get data from the cache // with the key as-is data = data_user.get( elem, key ); if ( data !== undefined ) { return data; } // Attempt to get data from the cache // with the key camelized data = data_user.get( elem, camelKey ); if ( data !== undefined ) { return data; } // Attempt to "discover" the data in // HTML5 custom data-* attrs data = dataAttr( elem, camelKey, undefined ); if ( data !== undefined ) { return data; } // We tried really hard, but the data doesn't exist. return; } // Set the data... this.each(function() { // First, attempt to store a copy or reference of any // data that might've been store with a camelCased key. var data = data_user.get( this, camelKey ); // For HTML5 data-* attribute interop, we have to // store property names with dashes in a camelCase form. // This might not apply to all properties...* data_user.set( this, camelKey, value ); // *... In the case of properties that might _actually_ // have dashes, we need to also store a copy of that // unchanged property. if ( key.indexOf("-") !== -1 && data !== undefined ) { data_user.set( this, key, value ); } }); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each(function() { data_user.remove( this, key ); }); } }); function dataAttr( elem, key, data ) { var name; // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? JSON.parse( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later data_user.set( elem, key, data ); } else { data = undefined; } } return data; } jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = data_priv.get( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray( data ) ) { queue = data_priv.access( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return data_priv.get( elem, key ) || data_priv.access( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { data_priv.remove( elem, [ type + "queue", key ] ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while( i-- ) { tmp = data_priv.get( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var nodeHook, boolHook, rclass = /[\t\r\n\f]/g, rreturn = /\r/g, rfocusable = /^(?:input|select|textarea|button)$/i; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { return this.each(function() { delete this[ jQuery.propFix[ name ] || name ]; }); }, addClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : " " ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } elem.className = jQuery.trim( cur ); } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = arguments.length === 0 || typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : "" ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { cur = cur.replace( " " + clazz + " ", " " ); } } elem.className = value ? jQuery.trim( cur ) : ""; } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value; if ( typeof stateVal === "boolean" && type === "string" ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), classNames = value.match( core_rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list if ( self.hasClass( className ) ) { self.removeClass( className ); } else { self.addClass( className ); } } // Toggle whole class name } else if ( type === core_strundefined || type === "boolean" ) { if ( this.className ) { // store className if set data_priv.set( this, "__className__", this.className ); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : data_priv.get( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; }, val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // IE6-9 doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) { optionSet = true; } } // force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } }, attr: function( elem, name, value ) { var hooks, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === core_strundefined ) { return jQuery.prop( elem, name, value ); } // All attributes are lowercase // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( core_rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( jQuery.expr.match.bool.test( name ) ) { // Set corresponding property to false elem[ propName ] = false; } elem.removeAttribute( name ); } } }, attrHooks: { type: { set: function( elem, value ) { if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to default in case type is set after value during creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } }, propFix: { "for": "htmlFor", "class": "className" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? ret : ( elem[ name ] = value ); } else { return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? ret : elem[ name ]; } }, propHooks: { tabIndex: { get: function( elem ) { return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ? elem.tabIndex : -1; } } } }); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { elem.setAttribute( name, name ); } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr; jQuery.expr.attrHandle[ name ] = function( elem, name, isXML ) { var fn = jQuery.expr.attrHandle[ name ], ret = isXML ? undefined : /* jshint eqeqeq: false */ // Temporarily disable this handler to check existence (jQuery.expr.attrHandle[ name ] = undefined) != getter( elem, name, isXML ) ? name.toLowerCase() : null; // Restore handler jQuery.expr.attrHandle[ name ] = fn; return ret; }; }); // Support: IE9+ // Selectedness for an option in an optgroup can be inaccurate if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; if ( parent && parent.parentNode ) { parent.parentNode.selectedIndex; } return null; } }; } jQuery.each([ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; }); // Radios and checkboxes getter/setter jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }; if ( !jQuery.support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { // Support: Webkit // "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; }; } }); var rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var handleObjIn, eventHandle, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.get( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, origCount, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.hasData( elem ) && data_priv.get( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; data_priv.remove( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var i, cur, tmp, bubbleType, ontype, handle, special, eventPath = [ elem || document ], type = core_hasOwn.call( event, "type" ) ? event.type : event, namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; elem[ type ](); jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, j, ret, matched, handleObj, handlerQueue = [], args = core_slice.call( arguments ), handlers = ( data_priv.get( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var i, matches, sel, handleObj, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { for ( ; cur !== this; cur = cur.parentNode || this ) { // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.disabled !== true || event.type !== "click" ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, // Includes some event props shared by KeyEvent and MouseEvent props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var eventDoc, doc, body, button = original.button; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: Cordova 2.5 (WebKit) (#13255) // All events should have a target; Cordova deviceready doesn't if ( !event.target ) { event.target = document; } // Support: Safari 6.0+, Chrome < 28 // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } return fixHook.filter? fixHook.filter( event, originalEvent ) : event; }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { this.focus(); return false; } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Support: Firefox 20+ // Firefox doesn't alert if the returnValue field is not set. if ( event.result !== undefined ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( e && e.preventDefault ) { e.preventDefault(); } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( e && e.stopPropagation ) { e.stopPropagation(); } }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks // Support: Chrome 15+ jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // Create "bubbling" focus and blur events // Support: Firefox, Chrome, Safari if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); var isSimple = /^.[^:#\[\.,]*$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, rneedsContext = jQuery.expr.match.needsContext, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var i, ret = [], self = this, len = self.length; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, has: function( target ) { var targets = jQuery( target, this ), l = targets.length; return this.filter(function() { var i = 0; for ( ; i < l; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector || [], true) ); }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], pos = ( rneedsContext.test( selectors ) || typeof selectors !== "string" ) ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && (pos ? pos.index(cur) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors)) ) { cur = matched.push( cur ); break; } } } return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return core_indexOf.call( jQuery( elem ), this[ 0 ] ); } // Locate the position of the desired element return core_indexOf.call( this, // If it receives a jQuery object, the first element is used elem.jquery ? elem[ 0 ] : elem ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( jQuery.unique(all) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); function sibling( cur, dir ) { while ( (cur = cur[dir]) && cur.nodeType !== 1 ) {} return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return elem.contentDocument || jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var matched = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { matched = jQuery.filter( selector, matched ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { jQuery.unique( matched ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { matched.reverse(); } } return this.pushStack( matched ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; })); }, dir: function( elem, dir, until ) { var matched = [], truncate = until !== undefined; while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) { if ( elem.nodeType === 1 ) { if ( truncate && jQuery( elem ).is( until ) ) { break; } matched.push( elem ); } } return matched; }, sibling: function( n, elem ) { var matched = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { matched.push( n ); } } return matched; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; }); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; }); } if ( typeof qualifier === "string" ) { if ( isSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( core_indexOf.call( qualifier, elem ) >= 0 ) !== not; }); } var rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, manipulation_rcheckableType = /^(?:checkbox|radio)$/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { // Support: IE 9 option: [ 1, "<select multiple='multiple'>", "</select>" ], thead: [ 1, "<table>", "</table>" ], col: [ 2, "<table><colgroup>", "</colgroup></table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], _default: [ 0, "", "" ] }; // Support: IE 9 wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; jQuery.fn.extend({ text: function( value ) { return jQuery.access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[ 0 ] && this[ 0 ].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { if ( elem.nodeType === 1 ) { // Prevent memory leaks jQuery.cleanData( getAll( elem, false ) ); // Remove any remaining nodes elem.textContent = ""; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return jQuery.access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined && elem.nodeType === 1 ) { return elem.innerHTML; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for ( ; i < l; i++ ) { elem = this[ i ] || {}; // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch( e ) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var // Snapshot the DOM in case .domManip sweeps something relevant into its fragment args = jQuery.map( this, function( elem ) { return [ elem.nextSibling, elem.parentNode ]; }), i = 0; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { var next = args[ i++ ], parent = args[ i++ ]; if ( parent ) { // Don't use the snapshot next if it has moved (#13810) if ( next && next.parentNode !== parent ) { next = this.nextSibling; } jQuery( this ).remove(); parent.insertBefore( elem, next ); } // Allow new content to include elements from the context set }, true ); // Force removal if there was no new content (e.g., from empty arguments) return i ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback, allowIntersection ) { // Flatten any nested arrays args = core_concat.apply( [], args ); var fragment, first, scripts, hasScripts, node, doc, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[ 0 ], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[ 0 ] = value.call( this, index, self.html() ); } self.domManip( args, callback, allowIntersection ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { // Support: QtWebKit // jQuery.merge because core_push.apply(_, arraylike) throws jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[ i ], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Hope ajax is available... jQuery._evalUrl( node.src ); } else { jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) ); } } } } } } return this; } }); jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, ret = [], insert = jQuery( selector ), last = insert.length - 1, i = 0; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone( true ); jQuery( insert[ i ] )[ original ]( elems ); // Support: QtWebKit // .get() because core_push.apply(_, arraylike) throws core_push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var i, l, srcElements, destElements, clone = elem.cloneNode( true ), inPage = jQuery.contains( elem.ownerDocument, elem ); // Support: IE >= 9 // Fix Cloning issues if ( !jQuery.support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); for ( i = 0, l = srcElements.length; i < l; i++ ) { fixInput( srcElements[ i ], destElements[ i ] ); } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0, l = srcElements.length; i < l; i++ ) { cloneCopyEvent( srcElements[ i ], destElements[ i ] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var elem, tmp, tag, wrap, contains, j, i = 0, l = elems.length, fragment = context.createDocumentFragment(), nodes = []; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { // Support: QtWebKit // jQuery.merge because core_push.apply(_, arraylike) throws jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || fragment.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || ["", ""] )[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[ 2 ]; // Descend through wrappers to the right content j = wrap[ 0 ]; while ( j-- ) { tmp = tmp.lastChild; } // Support: QtWebKit // jQuery.merge because core_push.apply(_, arraylike) throws jQuery.merge( nodes, tmp.childNodes ); // Remember the top-level container tmp = fragment.firstChild; // Fixes #12346 // Support: Webkit, IE tmp.textContent = ""; } } } // Remove wrapper from fragment fragment.textContent = ""; i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( fragment.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } return fragment; }, cleanData: function( elems ) { var data, elem, events, type, key, j, special = jQuery.event.special, i = 0; for ( ; (elem = elems[ i ]) !== undefined; i++ ) { if ( Data.accepts( elem ) ) { key = elem[ data_priv.expando ]; if ( key && (data = data_priv.cache[ key ]) ) { events = Object.keys( data.events || {} ); if ( events.length ) { for ( j = 0; (type = events[j]) !== undefined; j++ ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } if ( data_priv.cache[ key ] ) { // Discard any remaining `private` data delete data_priv.cache[ key ]; } } } // Discard any remaining `user` data delete data_user.cache[ elem[ data_user.expando ] ]; } }, _evalUrl: function( url ) { return jQuery.ajax({ url: url, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } }); // Support: 1.x compatibility // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType === 1 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[ 1 ]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var l = elems.length, i = 0; for ( ; i < l; i++ ) { data_priv.set( elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; if ( dest.nodeType !== 1 ) { return; } // 1. Copy private data: events, handlers, etc. if ( data_priv.hasData( src ) ) { pdataOld = data_priv.access( src ); pdataCur = data_priv.set( dest, pdataOld ); events = pdataOld.events; if ( events ) { delete pdataCur.handle; pdataCur.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } } // 2. Copy user data if ( data_user.hasData( src ) ) { udataOld = data_user.access( src ); udataCur = jQuery.extend( {}, udataOld ); data_user.set( dest, udataCur ); } } function getAll( context, tag ) { var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) : context.querySelectorAll ? context.querySelectorAll( tag || "*" ) : []; return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], ret ) : ret; } // Support: IE >= 9 function fixInput( src, dest ) { var nodeName = dest.nodeName.toLowerCase(); // Fails to persist the checked state of a cloned checkbox or radio button. if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) { dest.checked = src.checked; // Fails to return the selected option to the default selected state when cloning options } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.fn.extend({ wrapAll: function( html ) { var wrap; if ( jQuery.isFunction( html ) ) { return this.each(function( i ) { jQuery( this ).wrapAll( html.call(this, i) ); }); } if ( this[ 0 ] ) { // The elements to wrap the target around wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); if ( this[ 0 ].parentNode ) { wrap.insertBefore( this[ 0 ] ); } wrap.map(function() { var elem = this; while ( elem.firstElementChild ) { elem = elem.firstElementChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function( i ) { jQuery( this ).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function( i ) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); } }); var curCSS, iframe, // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rmargin = /^margin/, rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ), elemdisplay = { BODY: "block" }, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, cssExpand = [ "Top", "Right", "Bottom", "Left" ], cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name.charAt(0).toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function isHidden( elem, el ) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); } // NOTE: we've included the "window" in window.getComputedStyle // because jsdom on node.js will break without it. function getStyles( elem ) { return window.getComputedStyle( elem, null ); } function showHide( elements, show ) { var display, elem, hidden, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = data_priv.get( elem, "olddisplay" ); display = elem.style.display; if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = data_priv.access( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); } } else { if ( !values[ index ] ) { hidden = isHidden( elem ); if ( display && display !== "none" || !hidden ) { data_priv.set( elem, "olddisplay", hidden ? display : jQuery.css(elem, "display") ); } } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.fn.extend({ css: function( name, value ) { return jQuery.access( this, function( elem, name, value ) { var styles, len, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { if ( typeof state === "boolean" ) { return state ? this.show() : this.hide(); } return this.each(function() { if ( isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "columnCount": true, "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "order": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": "cssFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( value ) ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // Fixes #8908, it can be done more correctly by specifying setters in cssHooks, // but it would mean to define eight (for every problematic property) identical functions if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { style[ name ] = value; } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var val, num, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; } return val; } }); curCSS = function( elem, name, _computed ) { var width, minWidth, maxWidth, computed = _computed || getStyles( elem ), // Support: IE9 // getPropertyValue is only needed for .css('filter') in IE9, see #12537 ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined, style = elem.style; if ( computed ) { if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // Support: Safari 5.1 // A tribute to the "awesome hack by Dean Edwards" // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret; }; function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // at this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val = name === "width" ? elem.offsetWidth : elem.offsetHeight, styles = getStyles( elem ), isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } // Try to determine the default display value of an element function css_defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = ( iframe || jQuery("<iframe frameborder='0' width='0' height='0'/>") .css( "cssText", "display:block !important" ) ).appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document; doc.write("<!doctype html><html><body>"); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } // Called ONLY from within css_defaultDisplay function actualDisplay( name, doc ) { var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), display = jQuery.css( elem[0], "display" ); elem.remove(); return display; } jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ? jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var styles = extra && getStyles( elem ); return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); // These hooks cannot be added until DOM ready because the support test // for it is not run until after DOM ready jQuery(function() { // Support: Android 2.3 if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { if ( computed ) { // Support: Android 2.3 // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, curCSS, [ elem, "marginRight" ] ); } } }; } // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here if ( !jQuery.support.pixelPosition && jQuery.fn.position ) { jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = { get: function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } }; }); } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { // Support: Opera <= 12.12 // Opera reports offsetWidths and offsetHeights less than zero on some elements return elem.offsetWidth <= 0 && elem.offsetHeight <= 0; }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function(){ var type = this.type; // Use .is(":disabled") so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !manipulation_rcheckableType.test( type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); //Serialize an array of form elements or a set of //key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; }); jQuery.fn.extend({ hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); } }); var // Document location ajaxLocParts, ajaxLocation, ajax_nonce = jQuery.now(), ajax_rquery = /\?/, rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat("*"); // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( core_rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( (dataType = dataTypes[i++]) ) { // Prepend if requested if ( dataType[0] === "+" ) { dataType = dataType.slice( 1 ) || "*"; (structure[ dataType ] = structure[ dataType ] || []).unshift( func ); // Otherwise append } else { (structure[ dataType ] = structure[ dataType ] || []).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } }); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } var selector, type, response, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = url.slice( off ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // If we have elements to modify, make the request if ( self.length > 0 ) { jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params }).done(function( responseText ) { // Save response for use in complete callback response = arguments; self.html( selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) : // Otherwise use the full result responseText ); }).complete( callback && function( jqXHR, status ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); }); } return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ){ jQuery.fn[ type ] = function( fn ){ return this.on( type, fn ); }; }); jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: ajaxLocation, type: "GET", isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText", json: "responseJSON" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var transport, // URL without anti-cache param cacheURL, // Response headers responseHeadersString, responseHeaders, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks("once memory"), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while ( (match = rheaders.exec( responseHeadersString )) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match == null ? null : match; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { var lname = name.toLowerCase(); if ( !state ) { name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( state < 2 ) { for ( code in map ) { // Lazy-add the new callback in a way that preserves old ones statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } else { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ).complete = completeDeferred.add; jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (prefilters might expect it) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ) .replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( core_rnotwhite ) || [""]; // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !== ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger("ajaxStart"); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on cacheURL = s.url; // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { cacheURL = ( s.url += ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + s.data ); // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add anti-cache in url if needed if ( s.cache === false ) { s.url = rts.test( cacheURL ) ? // If there is already a '_' parameter, set its value cacheURL.replace( rts, "$1_=" + ajax_nonce++ ) : // Otherwise add one to the end cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_nonce++; } } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout(function() { jqXHR.abort("timeout"); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch ( e ) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader("etag"); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger("ajaxStop"); } } } return jqXHR; }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); } }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ url: url, type: method, dataType: type, data: data, success: callback }); }; }); /* Handles responses to an ajax request: * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var ct, type, finalDataType, firstDataType, contents = s.contents, dataTypes = s.dataTypes; // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } /* Chain conversions given the request and the original response * Also sets the responseXXX fields on the jqXHR instance */ function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There's only work to do if current dataType is non-auto if ( current === "*" ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split( " " ); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.unshift( tmp[ 1 ] ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s[ "throws" ] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; } // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /(?:java|ecma)script/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and crossDomain jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function( s ) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, callback; return { send: function( _, complete ) { script = jQuery("<script>").prop({ async: true, charset: s.scriptCharset, src: s.url }).on( "load error", callback = function( evt ) { script.remove(); callback = null; if ( evt ) { complete( evt.type === "error" ? 404 : 200, evt.type ); } } ); document.head.appendChild( script[ 0 ] ); }, abort: function() { if ( callback ) { callback(); } } }; } }); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? "url" : typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data" ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if ( jsonProp ) { s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); } else if ( s.jsonp !== false ) { s.url += ( ajax_rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback overwritten = window[ callbackName ]; window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); jQuery.ajaxSettings.xhr = function() { try { return new XMLHttpRequest(); } catch( e ) {} }; var xhrSupported = jQuery.ajaxSettings.xhr(), xhrSuccessStatus = { // file protocol always yields status code 0, assume 200 0: 200, // Support: IE9 // #1450: sometimes IE returns 1223 when it should be 204 1223: 204 }, // Support: IE9 // We need to keep track of outbound xhr and abort them manually // because IE is not smart enough to do it all by itself xhrId = 0, xhrCallbacks = {}; if ( window.ActiveXObject ) { jQuery( window ).on( "unload", function() { for( var key in xhrCallbacks ) { xhrCallbacks[ key ](); } xhrCallbacks = undefined; }); } jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); jQuery.support.ajax = xhrSupported = !!xhrSupported; jQuery.ajaxTransport(function( options ) { var callback; // Cross domain only allowed if supported through XMLHttpRequest if ( jQuery.support.cors || xhrSupported && !options.crossDomain ) { return { send: function( headers, complete ) { var i, id, xhr = options.xhr(); xhr.open( options.type, options.url, options.async, options.username, options.password ); // Apply custom fields if provided if ( options.xhrFields ) { for ( i in options.xhrFields ) { xhr[ i ] = options.xhrFields[ i ]; } } // Override mime type if needed if ( options.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( options.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !options.crossDomain && !headers["X-Requested-With"] ) { headers["X-Requested-With"] = "XMLHttpRequest"; } // Set headers for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } // Callback callback = function( type ) { return function() { if ( callback ) { delete xhrCallbacks[ id ]; callback = xhr.onload = xhr.onerror = null; if ( type === "abort" ) { xhr.abort(); } else if ( type === "error" ) { complete( // file protocol always yields status 0, assume 404 xhr.status || 404, xhr.statusText ); } else { complete( xhrSuccessStatus[ xhr.status ] || xhr.status, xhr.statusText, // Support: IE9 // #11426: When requesting binary data, IE9 will throw an exception // on any attempt to access responseText typeof xhr.responseText === "string" ? { text: xhr.responseText } : undefined, xhr.getAllResponseHeaders() ); } } }; }; // Listen to events xhr.onload = callback(); xhr.onerror = callback("error"); // Create the abort callback callback = xhrCallbacks[( id = xhrId++ )] = callback("abort"); // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( options.hasContent && options.data || null ); }, abort: function() { if ( callback ) { callback(); } } }; } }); var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [function( prop, value ) { var tween = this.createTween( prop, value ), target = tween.cur(), parts = rfxnum.exec( value ), unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), // Starting value computation is required for potential unit mismatches start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) && rfxnum.exec( jQuery.css( tween.elem, prop ) ), scale = 1, maxIterations = 20; if ( start && start[ 3 ] !== unit ) { // Trust units reported by jQuery.css unit = unit || start[ 3 ]; // Make sure we update the tween properties later on parts = parts || []; // Iteratively approximate from a nonzero starting point start = +target || 1; do { // If previous iteration zeroed out, double until we get *something* // Use a string for doubling factor so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); // Update scale, tolerating zero or NaN from tween.cur() // And breaking the loop if scale is unchanged or perfect, or if we've just had enough } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); } // Update tween properties if ( parts ) { start = tween.start = +start || +target || 0; tween.unit = unit; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[ 1 ] ? start + ( parts[ 1 ] + 1 ) * parts[ 2 ] : +parts[ 2 ]; } return tween; }] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }); return ( fxNow = jQuery.now() ); } function createTween( value, prop, animation ) { var tween, collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( (tween = collection[ index ].call( animation, prop, value )) ) { // we're done with this property return tween; } } } function Animation( elem, properties, options ) { var result, stopped, index = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // don't match elem in the :animated selector delete tick.elem; }), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // if we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // resolve when we played the last frame // otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } jQuery.map( props, createTween, animation ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue }) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'index' from above because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } jQuery.Animation = jQuery.extend( Animation, { tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.split(" "); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; tweeners[ prop ] = tweeners[ prop ] || []; tweeners[ prop ].unshift( callback ); } }, prefilter: function( callback, prepend ) { if ( prepend ) { animationPrefilters.unshift( callback ); } else { animationPrefilters.push( callback ); } } }); function defaultPrefilter( elem, props, opts ) { /* jshint validthis: true */ var prop, value, toggle, tween, hooks, oldfire, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHidden( elem ), dataShow = data_priv.get( elem, "fxshow" ); // handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { // doing this makes sure that the complete handler will be called // before this completes anim.always(function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } }); }); } // height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE9-10 do not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated if ( jQuery.css( elem, "display" ) === "inline" && jQuery.css( elem, "float" ) === "none" ) { style.display = "inline-block"; } } if ( opts.overflow ) { style.overflow = "hidden"; anim.always(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } // show/hide pass for ( prop in props ) { value = props[ prop ]; if ( rfxtypes.exec( value ) ) { delete props[ prop ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { // If there is dataShow left over from a stopped hide or show and we are going to proceed with show, we should pretend to be hidden if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { hidden = true; } else { continue; } } orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); } } if ( !jQuery.isEmptyObject( orig ) ) { if ( dataShow ) { if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } } else { dataShow = data_priv.access( elem, "fxshow", {} ); } // store state if its toggle - enables .stop().toggle() to "reverse" if ( toggle ) { dataShow.hidden = !hidden; } if ( hidden ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; data_priv.remove( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( prop in orig ) { tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } } } function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || "swing"; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; if ( tween.elem[ tween.prop ] != null && (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { return tween.elem[ tween.prop ]; } // passing an empty string as a 3rd parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails // so, simple values such as "10px" are parsed to Float. // complex values such as "rotate(1rad)" are returned as is. result = jQuery.css( tween.elem, tween.prop, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // use step hook for back compat - use cssHook if its there - use .style if its // available and use plain properties where available if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Support: IE9 // Panic based approach to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.each([ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; }); jQuery.fn.extend({ fadeTo: function( speed, to, easing, callback ) { // show any hidden elements after setting opacity to 0 return this.filter( isHidden ).css( "opacity", 0 ).show() // animate to the value specified .end().animate({ opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations, or finishing resolves immediately if ( empty || data_priv.get( this, "finish" ) ) { anim.stop( true ); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = data_priv.get( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // start the next in the queue if the last step wasn't forced // timers currently will call their complete callbacks, which will dequeue // but only if they were gotoEnd if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } }); }, finish: function( type ) { if ( type !== false ) { type = type || "fx"; } return this.each(function() { var index, data = data_priv.get( this ), queue = data[ type + "queue" ], hooks = data[ type + "queueHooks" ], timers = jQuery.timers, length = queue ? queue.length : 0; // enable finishing flag on private data data.finish = true; // empty the queue first jQuery.queue( this, type, [] ); if ( hooks && hooks.stop ) { hooks.stop.call( this, true ); } // look for any active animations, and finish them for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && timers[ index ].queue === type ) { timers[ index ].anim.stop( true ); timers.splice( index, 1 ); } } // look for any animations in the old queue and finish them for ( index = 0; index < length; index++ ) { if ( queue[ index ] && queue[ index ].finish ) { queue[ index ].finish.call( this ); } } // turn off finishing flag delete data.finish; }); } }); // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, attrs = { height: type }, i = 0; // if we include width, step value is 1 to do all cssExpand values, // if we don't include width, step value is 2 to skip over Left and Right includeWidth = includeWidth? 1 : 0; for( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show"), slideUp: genFx("hide"), slideToggle: genFx("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p*Math.PI ) / 2; } }; jQuery.timers = []; jQuery.fx = Tween.prototype.init; jQuery.fx.tick = function() { var timer, timers = jQuery.timers, i = 0; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { if ( timer() && jQuery.timers.push( timer ) ) { jQuery.fx.start(); } }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if ( !timerId ) { timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.stop = function() { clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Back Compat <1.8 extension point jQuery.fx.step = {}; if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } jQuery.fn.offset = function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, win, elem = this[ 0 ], box = { top: 0, left: 0 }, doc = elem && elem.ownerDocument; if ( !doc ) { return; } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== core_strundefined ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); return { top: box.top + win.pageYOffset - docElem.clientTop, left: box.left + win.pageXOffset - docElem.clientLeft }; }; jQuery.offset = { setOffset: function( elem, options, i ) { var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition, position = jQuery.css( elem, "position" ), curElem = jQuery( elem ), props = {}; // Set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } curOffset = curElem.offset(); curCSSTop = jQuery.css( elem, "top" ); curCSSLeft = jQuery.css( elem, "left" ); calculatePosition = ( position === "absolute" || position === "fixed" ) && ( curCSSTop + curCSSLeft ).indexOf("auto") > -1; // Need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, elem = this[ 0 ], parentOffset = { top: 0, left: 0 }; // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent if ( jQuery.css( elem, "position" ) === "fixed" ) { // We assume that getBoundingClientRect is available when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ); parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ); } // Subtract parent offsets and element margins return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true ) }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || docElem; while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || docElem; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) { var top = "pageYOffset" === prop; jQuery.fn[ method ] = function( val ) { return jQuery.access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? win[ prop ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : window.pageXOffset, top ? val : window.pageYOffset ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView; } // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return jQuery.access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], // whichever is greatest return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; }); }); // Limit scope pollution from any deprecated API // (function() { // The number of elements contained in the matched element set jQuery.fn.size = function() { return this.length; }; jQuery.fn.andSelf = jQuery.fn.addBack; // })(); if ( typeof module === "object" && module && typeof module.exports === "object" ) { // Expose jQuery as module.exports in loaders that implement the Node // module pattern (including browserify). Do not create the global, since // the user will be storing it themselves locally, and globals are frowned // upon in the Node module world. module.exports = jQuery; } else { // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd ) { define( "jquery", [], function () { return jQuery; } ); } } // If there is a window object, that at least has a document property, // define jQuery and $ identifiers if ( typeof window === "object" && typeof window.document === "object" ) { window.jQuery = window.$ = jQuery; } })( window );
JavaScript
$(document).ready(function(){ });
JavaScript
$(document).ready(function(){ });
JavaScript
$(document).ready(function(){ });
JavaScript
/* * jQuery Iframe Transport Plugin 1.2.3 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2011, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://creativecommons.org/licenses/MIT/ */ /*jslint unparam: true */ /*global jQuery */ (function ($) { 'use strict'; // Helper variable to create unique names for the transport iframes: var counter = 0; // The iframe transport accepts three additional options: // options.fileInput: a jQuery collection of file input fields // options.paramName: the parameter name for the file form data, // overrides the name property of the file input field(s) // options.formData: an array of objects with name and value properties, // equivalent to the return data of .serializeArray(), e.g.: // [{name: a, value: 1}, {name: b, value: 2}] $.ajaxTransport('iframe', function (options, originalOptions, jqXHR) { if (options.type === 'POST' || options.type === 'GET') { var form, iframe; return { send: function (headers, completeCallback) { form = $('<form style="display:none;"></form>'); // javascript:false as initial iframe src // prevents warning popups on HTTPS in IE6. // IE versions below IE8 cannot set the name property of // elements that have already been added to the DOM, // so we set the name along with the iframe HTML markup: iframe = $( '<iframe src="javascript:false;" name="iframe-transport-' + (counter += 1) + '"></iframe>' ).bind('load', function () { var fileInputClones; iframe .unbind('load') .bind('load', function () { var response; // Wrap in a try/catch block to catch exceptions thrown // when trying to access cross-domain iframe contents: try { response = iframe.contents(); // Google Chrome and Firefox do not throw an // exception when calling iframe.contents() on // cross-domain requests, so we unify the response: if (!response.length || !response[0].firstChild) { throw new Error(); } } catch (e) { response = undefined; } // The complete callback returns the // iframe content document as response object: completeCallback( 200, 'success', {'iframe': response} ); // Fix for IE endless progress bar activity bug // (happens on form submits to iframe targets): $('<iframe src="javascript:false;"></iframe>') .appendTo(form); form.remove(); }); form .prop('target', iframe.prop('name')) .prop('action', options.url) .prop('method', options.type); if (options.formData) { $.each(options.formData, function (index, field) { $('<input type="hidden"/>') .prop('name', field.name) .val(field.value) .appendTo(form); }); } if (options.fileInput && options.fileInput.length && options.type === 'POST') { fileInputClones = options.fileInput.clone(); // Insert a clone for each file input field: options.fileInput.after(function (index) { return fileInputClones[index]; }); if (options.paramName) { options.fileInput.each(function () { $(this).prop('name', options.paramName); }); } // Appending the file input fields to the hidden form // removes them from their original location: form .append(options.fileInput) .prop('enctype', 'multipart/form-data') // enctype must be set as encoding for IE: .prop('encoding', 'multipart/form-data'); } form.submit(); // Insert the file input fields at their original location // by replacing the clones with the originals: if (fileInputClones && fileInputClones.length) { options.fileInput.each(function (index, input) { var clone = $(fileInputClones[index]); $(input).prop('name', clone.prop('name')); clone.replaceWith(input); }); } }); form.append(iframe).appendTo('body'); }, abort: function () { if (iframe) { // javascript:false as iframe src aborts the request // and prevents warning popups on HTTPS in IE6. // concat is used to avoid the "Script URL" JSLint error: iframe .unbind('load') .prop('src', 'javascript'.concat(':false;')); } if (form) { form.remove(); } } }; } }); // The iframe transport returns the iframe content document as response. // The following adds converters from iframe to text, json, html, and script: $.ajaxSetup({ converters: { 'iframe text': function (iframe) { return iframe.find('body').text(); }, 'iframe json': function (iframe) { return $.parseJSON(iframe.find('body').text()); }, 'iframe html': function (iframe) { return iframe.find('body').html(); }, 'iframe script': function (iframe) { return $.globalEval(iframe.find('body').text()); } } }); }(jQuery));
JavaScript
root theme js file
JavaScript
nested theme js file
JavaScript