text
stringlengths
2
1.05M
import FuzzyCompositeTerm from './FuzzyCompositeTerm.js'; /** * @author {@link https://github.com/Mugen87|Mugen87} * @augments FuzzyCompositeTerm */ class FuzzyAND extends FuzzyCompositeTerm { constructor() { const terms = Array.from(arguments); super(terms); } getDegreeOfMembership() { const terms = this.terms; let minDOM = Infinity; for (let i = 0, l = terms.length; i < l; i++) { const currentDOM = terms[i].getDegreeOfMembership(); if (currentDOM < minDOM) { minDOM = currentDOM; } } return minDOM; } } export default FuzzyAND;
/** * Interaction for the Profiles module */ jsBackend.Profiles = { init: function() { jsBackend.Profiles.massAddToGroup.init(); jsBackend.Profiles.settings.init(); jsBackend.Profiles.editEmail.init(); jsBackend.Profiles.editPassword.init(); }, massAddToGroup: { init: function() { // update the hidden input for the new group's ID with the remembered value var $txtNewGroup = $('input[name="newGroup"]').val(); // clone the groups SELECT into the "add to group" mass action dialog $('.jsMassActionAddToGroupSelectGroup').replaceWith( $('select[name="group"]') .clone(true) .removeAttr('id') .attr('name', 'newGroup') .on('change', function() { // update the hidden input for the new group's ID with the current value $txtNewGroup.val(this.value); }) ); } }, editEmail: { init: function() { if ($('#newEmailBox').length == 0) return false; $('#newEmail').on('change', function() { jsBackend.Profiles.editEmail.toggleBox(); }); jsBackend.Profiles.editEmail.toggleBox(); }, toggleBox: function() { var $item = $('#newEmail'); var checked = ($item.attr('checked') == 'checked'); $('#newEmailBox').toggle(checked); } }, editPassword: { init: function() { if ($('#newPasswordBox').length == 0) return false; $('#newPassword').on('change', function() { jsBackend.Profiles.editPassword.toggleBox(); }); jsBackend.Profiles.editPassword.toggleBox(); }, toggleBox: function() { var $item = $('#newPassword'); var checked = ($item.attr('checked') == 'checked'); $('#newPasswordBox').toggle(checked); } }, settings: { init: function() { if ($('#sendNewProfileAdminMail').length == 0) return false; $('#sendNewProfileAdminMail').on('change', function() { jsBackend.Profiles.settings.toggleAdminMail(); }); $('#overwriteProfileNotificationEmail').on('change', function() { jsBackend.Profiles.settings.toggleProfileNotificationEmail(); }); jsBackend.Profiles.settings.toggleAdminMail(); jsBackend.Profiles.settings.toggleProfileNotificationEmail(); }, toggleAdminMail: function() { var $item = $('#sendNewProfileAdminMail'); var checked = ($item.attr('checked') == 'checked'); $('#overwriteProfileNotificationEmailBox').toggle(checked); }, toggleProfileNotificationEmail: function() { var $item = $('#overwriteProfileNotificationEmail'); var checked = ($item.attr('checked') == 'checked'); $('#profileNotificationEmailBox').toggle(checked); } } }; $(jsBackend.Profiles.init);
/** * 创建标签 * @param funWhenCreateLabelSuccess 创建成功时回调,回传参数为新标签id * @param funWhenCreateLabelFail 创建失败时回调,参数为错误码和错误信息 */ function createLabel(funWhenCreateLabelSuccess, funWhenCreateLabelFail) { var name = $('#labelName').val(); // 需要common.js if (isStrEmpty(name)) { error('标签名称不能为空', 'labelErrorMsg', true, 2000); return; } else { $('#labelErrorMsg').html(' '); } disableButton(false, 'newLabelBtn', '正在创建...', "button-disable"); $.post( '/blogger/' + pageOwnerBloggerId + '/label', {title: name}, function (result) { if (result.code === 0) { disableButton(false, 'newLabelBtn', '创建成功', "button-disable"); funWhenCreateLabelSuccess(result.data); setTimeout(function () { disableButton(true, 'newLabelBtn', '创建', "button-disable"); $('#labelName').val(''); $('#newLabelDialog').modal('toggle'); }, 1000); } else { disableButton(true, 'newLabelBtn', '创建', "button-disable"); error(result.msg, 'labelErrorMsg', true, 3000); funWhenCreateLabelFail(result); } }, 'json' ); }
export default { data() { return { items: [], }; }, methods: { add(item) { this.items.push(item); this.$emit('added'); }, remove(i) { this.items.splice(i, 1); this.$emit('remove'); } } }
/** * * Asynchronously loads the component for TestPage * */ import Loadable from 'react-loadable'; export default Loadable({ loader: () => import('./index'), loading: () => null, });
/* |-------------------------------------------------------------------------- | Providers |-------------------------------------------------------------------------- | | Providers are building blocks for your Adonis app. Anytime you install | a new Adonis specific package, chances are you will register the | provider here. | */ const providers = [ '@adonisjs/framework/providers/AppProvider', '@adonisjs/auth/providers/AuthProvider', '@adonisjs/bodyparser/providers/BodyParserProvider', '@adonisjs/cors/providers/CorsProvider', '@adonisjs/lucid/providers/LucidProvider', 'adonis-swagger/providers/SwaggerProvider', '@adonisjs/vow/providers/VowProvider', ]; /* |-------------------------------------------------------------------------- | Ace Providers |-------------------------------------------------------------------------- | | Ace providers are required only when running ace commands. For example | Providers for migrations, tests etc. | */ const aceProviders = ['@adonisjs/lucid/providers/MigrationsProvider']; /* |-------------------------------------------------------------------------- | Aliases |-------------------------------------------------------------------------- | | Aliases are short unique names for IoC container bindings. You are free | to create your own aliases. | | For example: | { Route: 'Adonis/Src/Route' } | */ const aliases = {}; /* |-------------------------------------------------------------------------- | Commands |-------------------------------------------------------------------------- | | Here you store ace commands for your package | */ const commands = []; module.exports = { providers, aceProviders, aliases, commands };
import React from 'react' import Layout from '../components/layout' const Datenschutz = () => { return ( <Layout> <h1>Datenschutz</h1> </Layout> ) } export default Datenschutz
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var React = _interopRequireWildcard(require("react")); var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _default = (0, _createSvgIcon["default"])( /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("path", { d: "M6.38 6L12 16l5.63-10z", opacity: ".3" }), /*#__PURE__*/React.createElement("path", { d: "M3 4l9 16 9-16H3zm3.38 2h11.25L12 16 6.38 6z" })), 'DetailsTwoTone'); exports["default"] = _default;
// Just define namespace for JSDoc /** @namespace App.Controllers */
"use strict"; module.exports = function (grunt) { // A temporary directory used by amdserialize to output the processed modules. var tmpdir = "./tmp/"; // The final output directory. var outdir = "./build/"; // The grunt.config property populated by amdserialize, containing the // list of files to include in the layer. var outprop = "amdoutput"; var decorPatterns = [ // Include "decor/*.js", "requirejs-dplugins/has.js", "requirejs-dplugins/i18n.js", "requirejs-dplugins/css.js", "requirejs-dplugins/jquery.js", "lie/dist/lie.js", // Exclude "!decor/Gruntfile.js" ]; var delitePatterns = [ // Include "delite/**/*.js", //"dojo/dom-geometry.js", // For dtreemap "requirejs-text/text.js", // Exclude "!delite/Gruntfile.js", "!delite/node_modules/**", "!delite/nls/**", "!delite/samples/**", "!delite/tests/**", "!delite/TooltipDialog.js", "!delite/Tooltip.js", "!delite/Overlay.js", "!delite/Opener.js", "!delite/DialogLevelManager.js", "!delite/DialogBase.js", "!delite/Dialog.js" ]; var delitefulPatterns = [ // Include "deliteful/**/*.js", // Exclude "!deliteful/tests/**", "!deliteful/samples/**", "!deliteful/docs/**", "!deliteful/**/holodark/**", "!deliteful/**/ios/**", "!deliteful/Gruntfile.js" ]; var dtreemapPatterns = [ // Include "dtreemap/**/*.js", // Exclude "!dtreemap/tests/**", "!dtreemap/demos/**", "!dtreemap/docs/**", "!dtreemap/Gruntfile.js" ]; var expandFiles = { filter: "isFile" }; function trimExt(path) { return path.slice(0, -3); } grunt.initConfig({ // The loader config should go here. amdloader: { baseUrl: "./", // Enable build of requirejs-text/text inlineText: true, map: { jquery: { "jquery/src/selector": "jquery/src/selector-native" // don't pull in sizzle } } }, amdbuild: { buildPlugin: true, // dir is the output directory. dir: tmpdir, runtimePlugins: [], // List of layers to build. layers: [{ name: "decor/layer", include: grunt.file.expand(expandFiles, decorPatterns).map(trimExt) }, { name: "dpointer/layer", includeFiles: ["dpointer/events.js", "dpointer/handlers/*.js"] }, { name: "ecma402/layer", include: ["ecma402/IntlShim"], exclude: ["requirejs-dplugins/has", "requirejs-text/text"] }, { name: "delite/layer", include: grunt.file.expand(expandFiles, delitePatterns).map(trimExt) .concat(["delite/theme!delite/themes/{{theme}}/global.css"]), excludeLayers: ["decor/layer", "dpointer/layer", "ecma402/layer"] }, { name: "deliteful/layer", include: grunt.file.expand(expandFiles, delitefulPatterns).map(trimExt), exclude: ["dstore/Memory", "dstore/Trackable", "dstore/Filter"], excludeLayers: ["decor/layer", "dpointer/layer", "ecma402/layer", "delite/layer"] }/*, { name: "dtreemap/layer", include: grunt.file.expand(expandFiles, dtreemapPatterns).map(trimExt), exclude: ["dstore/Memory", "dstore/Trackable", "dstore/Filter"], excludeLayers: ["decor/layer", "dpointer/layer", "delite/layer"] }, { name: "dcolor/layer", includeFiles: ["dcolor/*.js"], excludeFiles: ["dcolor/Gruntfile.js"] }, { name: "liaison/layer", includeFiles: ["liaison/**//*.js"], excludeFiles: ["liaison/delite/**", "liaison/polymer/**", "liaison/tests/**", "liaison/samples/**", "liaison/docs/**", "liaison/node_modules/**", "liaison/Gruntfile.js"] }, { name: "liaison/delite/layer", includeFiles: ["liaison/delite/**//*.js"], excludeFiles: ["liaison/delite/widgets/StarRating.js"] }*/] }, updateSamples: { liaison: { samples: { src: [ "samples/*", "samples/css/*", "!samples/loan.html" ] } }, "liaison/delite": { samples: { src: [ "../samples/delite/*", "!**/samples/delite/widgetskitchensink.html", "!**/loan.html" ]/*, deps: ["delite", "liaison"]*/ } } }, // Config to allow uglify to generate the layer. uglify: { options: { banner: "<%= " + outprop + ".header%>", sourceMap: true }, dist: { src: "<%= " + outprop + ".modules.abs %>", dest: outdir + "<%= " + outprop + ".layerPath %>" } }, // Copy the plugin files to the real output directory. copy: { plugins: { expand: true, cwd: tmpdir, src: "<%= " + outprop + ".plugins.rel %>", dest: outdir, dot: true } }, // Erase temp directory and previous build clean: { erase: [outdir],//.concat(libDirsBuild), finish: [tmpdir] } }); // The main build task. grunt.registerTask("amdbuild", function (amdloader) { function useAmdDepsScan(name) { var layerToGetDeps = ["delite/layer", "decor/layer", "deliteful/layer", "ecma402/layer", "dtreemap/layer"]; return layerToGetDeps.indexOf(name) >= 0; } // Create tasks list var tasksList = []; var name = this.name; var layers = grunt.config(name).layers; layers.forEach(function (layer) { if (useAmdDepsScan(layer.name)) { tasksList.push("amddepsscan:" + layer.name + ":" + name + ":" + amdloader); } else { tasksList.push("amddirscan:" + layer.name + ":" + name + ":" + amdloader); } tasksList.push("amdserialize:" + layer.name + ":" + name + ":" + amdloader + ":" + outprop); tasksList.push("uglify"); tasksList.push("correctSourceMap:" + layer.name + ":" + name + ":" + outdir); // Remove references to useless html template before copying plugins files. tasksList.push("filterPluginFiles:\\.(html|json)\\.js$:" + outprop); tasksList.push("copy:plugins"); }); tasksList.push("updateBowers:" + name + ":" + outdir); tasksList.push("addBoot:" + name + ":" + outdir); tasksList.push("copyMetaFiles:" + name + ":" + outdir); tasksList.push("updateSamples:" + name + ":" + outdir); tasksList.push("copyBuildResults:" + name + ":" + outdir); grunt.task.run(tasksList); }); // Load the plugin that provides the "amd" task. grunt.loadNpmTasks("grunt-amd-build"); grunt.loadTasks("./tasks/"); // Load vendor plugins. grunt.loadNpmTasks("grunt-contrib-uglify"); grunt.loadNpmTasks("grunt-contrib-concat"); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-clean'); // Default task. grunt.registerTask("default", ["clean:erase", "amdbuild:amdloader", "amdreportjson:amdbuild", "clean:finish"]); };
// FILE IS GENERATED BY COMBINING THE SOURCES IN THE "classes" DIRECTORY SO DON'T MODIFY THIS FILE DIRECTLY (function(win) { var whiteSpaceRe = /^\s*|\s*$/g, undef, isRegExpBroken = 'B'.replace(/A(.)|B/, '$1') === '$1'; var tinymce = { majorVersion : '3', minorVersion : '5b3', releaseDate : '2012-03-29', _init : function() { var t = this, d = document, na = navigator, ua = na.userAgent, i, nl, n, base, p, v; t.isOpera = win.opera && opera.buildNumber; t.isWebKit = /WebKit/.test(ua); t.isIE = !t.isWebKit && !t.isOpera && (/MSIE/gi).test(ua) && (/Explorer/gi).test(na.appName); t.isIE6 = t.isIE && /MSIE [56]/.test(ua); t.isIE7 = t.isIE && /MSIE [7]/.test(ua); t.isIE8 = t.isIE && /MSIE [8]/.test(ua); t.isIE9 = t.isIE && /MSIE [9]/.test(ua); t.isGecko = !t.isWebKit && /Gecko/.test(ua); t.isMac = ua.indexOf('Mac') != -1; t.isAir = /adobeair/i.test(ua); t.isIDevice = /(iPad|iPhone)/.test(ua); t.isIOS5 = t.isIDevice && ua.match(/AppleWebKit\/(\d*)/)[1]>=534; // TinyMCE .NET webcontrol might be setting the values for TinyMCE if (win.tinyMCEPreInit) { t.suffix = tinyMCEPreInit.suffix; t.baseURL = tinyMCEPreInit.base; t.query = tinyMCEPreInit.query; return; } // Get suffix and base t.suffix = ''; // If base element found, add that infront of baseURL nl = d.getElementsByTagName('base'); for (i=0; i<nl.length; i++) { v = nl[i].href; if (v) { // Host only value like http://site.com or http://site.com:8008 if (/^https?:\/\/[^\/]+$/.test(v)) v += '/'; base = v ? v.match(/.*\//)[0] : ''; // Get only directory } } function getBase(n) { if (n.src && /tiny_mce(|_gzip|_jquery|_prototype|_full)(_dev|_src)?.js/.test(n.src)) { if (/_(src|dev)\.js/g.test(n.src)) t.suffix = '_src'; if ((p = n.src.indexOf('?')) != -1) t.query = n.src.substring(p + 1); t.baseURL = n.src.substring(0, n.src.lastIndexOf('/')); // If path to script is relative and a base href was found add that one infront // the src property will always be an absolute one on non IE browsers and IE 8 // so this logic will basically only be executed on older IE versions if (base && t.baseURL.indexOf('://') == -1 && t.baseURL.indexOf('/') !== 0) t.baseURL = base + t.baseURL; return t.baseURL; } return null; }; // Check document nl = d.getElementsByTagName('script'); for (i=0; i<nl.length; i++) { if (getBase(nl[i])) return; } // Check head n = d.getElementsByTagName('head')[0]; if (n) { nl = n.getElementsByTagName('script'); for (i=0; i<nl.length; i++) { if (getBase(nl[i])) return; } } return; }, is : function(o, t) { if (!t) return o !== undef; if (t == 'array' && (o.hasOwnProperty && o instanceof Array)) return true; return typeof(o) == t; }, makeMap : function(items, delim, map) { var i; items = items || []; delim = delim || ','; if (typeof(items) == "string") items = items.split(delim); map = map || {}; i = items.length; while (i--) map[items[i]] = {}; return map; }, each : function(o, cb, s) { var n, l; if (!o) return 0; s = s || o; if (o.length !== undef) { // Indexed arrays, needed for Safari for (n=0, l = o.length; n < l; n++) { if (cb.call(s, o[n], n, o) === false) return 0; } } else { // Hashtables for (n in o) { if (o.hasOwnProperty(n)) { if (cb.call(s, o[n], n, o) === false) return 0; } } } return 1; }, map : function(a, f) { var o = []; tinymce.each(a, function(v) { o.push(f(v)); }); return o; }, grep : function(a, f) { var o = []; tinymce.each(a, function(v) { if (!f || f(v)) o.push(v); }); return o; }, inArray : function(a, v) { var i, l; if (a) { for (i = 0, l = a.length; i < l; i++) { if (a[i] === v) return i; } } return -1; }, extend : function(obj, ext) { var i, l, name, args = arguments, value; for (i = 1, l = args.length; i < l; i++) { ext = args[i]; for (name in ext) { if (ext.hasOwnProperty(name)) { value = ext[name]; if (value !== undef) { obj[name] = value; } } } } return obj; }, trim : function(s) { return (s ? '' + s : '').replace(whiteSpaceRe, ''); }, create : function(s, p, root) { var t = this, sp, ns, cn, scn, c, de = 0; // Parse : <prefix> <class>:<super class> s = /^((static) )?([\w.]+)(:([\w.]+))?/.exec(s); cn = s[3].match(/(^|\.)(\w+)$/i)[2]; // Class name // Create namespace for new class ns = t.createNS(s[3].replace(/\.\w+$/, ''), root); // Class already exists if (ns[cn]) return; // Make pure static class if (s[2] == 'static') { ns[cn] = p; if (this.onCreate) this.onCreate(s[2], s[3], ns[cn]); return; } // Create default constructor if (!p[cn]) { p[cn] = function() {}; de = 1; } // Add constructor and methods ns[cn] = p[cn]; t.extend(ns[cn].prototype, p); // Extend if (s[5]) { sp = t.resolve(s[5]).prototype; scn = s[5].match(/\.(\w+)$/i)[1]; // Class name // Extend constructor c = ns[cn]; if (de) { // Add passthrough constructor ns[cn] = function() { return sp[scn].apply(this, arguments); }; } else { // Add inherit constructor ns[cn] = function() { this.parent = sp[scn]; return c.apply(this, arguments); }; } ns[cn].prototype[cn] = ns[cn]; // Add super methods t.each(sp, function(f, n) { ns[cn].prototype[n] = sp[n]; }); // Add overridden methods t.each(p, function(f, n) { // Extend methods if needed if (sp[n]) { ns[cn].prototype[n] = function() { this.parent = sp[n]; return f.apply(this, arguments); }; } else { if (n != cn) ns[cn].prototype[n] = f; } }); } // Add static methods t.each(p['static'], function(f, n) { ns[cn][n] = f; }); if (this.onCreate) this.onCreate(s[2], s[3], ns[cn].prototype); }, walk : function(o, f, n, s) { s = s || this; if (o) { if (n) o = o[n]; tinymce.each(o, function(o, i) { if (f.call(s, o, i, n) === false) return false; tinymce.walk(o, f, n, s); }); } }, createNS : function(n, o) { var i, v; o = o || win; n = n.split('.'); for (i=0; i<n.length; i++) { v = n[i]; if (!o[v]) o[v] = {}; o = o[v]; } return o; }, resolve : function(n, o) { var i, l; o = o || win; n = n.split('.'); for (i = 0, l = n.length; i < l; i++) { o = o[n[i]]; if (!o) break; } return o; }, addUnload : function(f, s) { var t = this, unload; unload = function() { var li = t.unloads, o, n; if (li) { // Call unload handlers for (n in li) { o = li[n]; if (o && o.func) o.func.call(o.scope, 1); // Send in one arg to distinct unload and user destroy } // Detach unload function if (win.detachEvent) { win.detachEvent('onbeforeunload', fakeUnload); win.detachEvent('onunload', unload); } else if (win.removeEventListener) win.removeEventListener('unload', unload, false); // Destroy references t.unloads = o = li = w = unload = 0; // Run garbarge collector on IE if (win.CollectGarbage) CollectGarbage(); } }; function fakeUnload() { var d = document; function stop() { // Prevent memory leak d.detachEvent('onstop', stop); // Call unload handler if (unload) unload(); d = 0; }; // Is there things still loading, then do some magic if (d.readyState == 'interactive') { // Fire unload when the currently loading page is stopped if (d) d.attachEvent('onstop', stop); // Remove onstop listener after a while to prevent the unload function // to execute if the user presses cancel in an onbeforeunload // confirm dialog and then presses the browser stop button win.setTimeout(function() { if (d) d.detachEvent('onstop', stop); }, 0); } }; f = {func : f, scope : s || this}; if (!t.unloads) { // Attach unload handler if (win.attachEvent) { win.attachEvent('onunload', unload); win.attachEvent('onbeforeunload', fakeUnload); } else if (win.addEventListener) win.addEventListener('unload', unload, false); // Setup initial unload handler array t.unloads = [f]; } else t.unloads.push(f); return f; }, removeUnload : function(f) { var u = this.unloads, r = null; tinymce.each(u, function(o, i) { if (o && o.func == f) { u.splice(i, 1); r = f; return false; } }); return r; }, explode : function(s, d) { if (!s || tinymce.is(s, 'array')) { return s; } return tinymce.map(s.split(d || ','), tinymce.trim); }, _addVer : function(u) { var v; if (!this.query) return u; v = (u.indexOf('?') == -1 ? '?' : '&') + this.query; if (u.indexOf('#') == -1) return u + v; return u.replace('#', v + '#'); }, // Fix function for IE 9 where regexps isn't working correctly // Todo: remove me once MS fixes the bug _replace : function(find, replace, str) { // On IE9 we have to fake $x replacement if (isRegExpBroken) { return str.replace(find, function() { var val = replace, args = arguments, i; for (i = 0; i < args.length - 2; i++) { if (args[i] === undef) { val = val.replace(new RegExp('\\$' + i, 'g'), ''); } else { val = val.replace(new RegExp('\\$' + i, 'g'), args[i]); } } return val; }); } return str.replace(find, replace); } }; // Initialize the API tinymce._init(); // Expose tinymce namespace to the global namespace (window) win.tinymce = win.tinyMCE = tinymce; // Describe the different namespaces })(window); tinymce.create('tinymce.util.Dispatcher', { scope : null, listeners : null, Dispatcher : function(s) { this.scope = s || this; this.listeners = []; }, add : function(cb, s) { this.listeners.push({cb : cb, scope : s || this.scope}); return cb; }, addToTop : function(cb, s) { this.listeners.unshift({cb : cb, scope : s || this.scope}); return cb; }, remove : function(cb) { var l = this.listeners, o = null; tinymce.each(l, function(c, i) { if (cb == c.cb) { o = cb; l.splice(i, 1); return false; } }); return o; }, dispatch : function() { var s, a = arguments, i, li = this.listeners, c; // Needs to be a real loop since the listener count might change while looping // And this is also more efficient for (i = 0; i<li.length; i++) { c = li[i]; s = c.cb.apply(c.scope, a.length > 0 ? a : [c.scope]); if (s === false) break; } return s; } }); (function() { var each = tinymce.each; tinymce.create('tinymce.util.URI', { URI : function(u, s) { var t = this, o, a, b, base_url; // Trim whitespace u = tinymce.trim(u); // Default settings s = t.settings = s || {}; // Strange app protocol that isn't http/https or local anchor // For example: mailto,skype,tel etc. if (/^([\w\-]+):([^\/]{2})/i.test(u) || /^\s*#/.test(u)) { t.source = u; return; } // Absolute path with no host, fake host and protocol if (u.indexOf('/') === 0 && u.indexOf('//') !== 0) u = (s.base_uri ? s.base_uri.protocol || 'http' : 'http') + '://mce_host' + u; // Relative path http:// or protocol relative //path if (!/^[\w\-]*:?\/\//.test(u)) { base_url = s.base_uri ? s.base_uri.path : new tinymce.util.URI(location.href).directory; u = ((s.base_uri && s.base_uri.protocol) || 'http') + '://mce_host' + t.toAbsPath(base_url, u); } // Parse URL (Credits goes to Steave, http://blog.stevenlevithan.com/archives/parseuri) u = u.replace(/@@/g, '(mce_at)'); // Zope 3 workaround, they use @@something u = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@\/]*):?([^:@\/]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(u); each(["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"], function(v, i) { var s = u[i]; // Zope 3 workaround, they use @@something if (s) s = s.replace(/\(mce_at\)/g, '@@'); t[v] = s; }); b = s.base_uri; if (b) { if (!t.protocol) t.protocol = b.protocol; if (!t.userInfo) t.userInfo = b.userInfo; if (!t.port && t.host === 'mce_host') t.port = b.port; if (!t.host || t.host === 'mce_host') t.host = b.host; t.source = ''; } //t.path = t.path || '/'; }, setPath : function(p) { var t = this; p = /^(.*?)\/?(\w+)?$/.exec(p); // Update path parts t.path = p[0]; t.directory = p[1]; t.file = p[2]; // Rebuild source t.source = ''; t.getURI(); }, toRelative : function(u) { var t = this, o; if (u === "./") return u; u = new tinymce.util.URI(u, {base_uri : t}); // Not on same domain/port or protocol if ((u.host != 'mce_host' && t.host != u.host && u.host) || t.port != u.port || t.protocol != u.protocol) return u.getURI(); var tu = t.getURI(), uu = u.getURI(); // Allow usage of the base_uri when relative_urls = true if(tu == uu || (tu.charAt(tu.length - 1) == "/" && tu.substr(0, tu.length - 1) == uu)) return tu; o = t.toRelPath(t.path, u.path); // Add query if (u.query) o += '?' + u.query; // Add anchor if (u.anchor) o += '#' + u.anchor; return o; }, toAbsolute : function(u, nh) { u = new tinymce.util.URI(u, {base_uri : this}); return u.getURI(this.host == u.host && this.protocol == u.protocol ? nh : 0); }, toRelPath : function(base, path) { var items, bp = 0, out = '', i, l; // Split the paths base = base.substring(0, base.lastIndexOf('/')); base = base.split('/'); items = path.split('/'); if (base.length >= items.length) { for (i = 0, l = base.length; i < l; i++) { if (i >= items.length || base[i] != items[i]) { bp = i + 1; break; } } } if (base.length < items.length) { for (i = 0, l = items.length; i < l; i++) { if (i >= base.length || base[i] != items[i]) { bp = i + 1; break; } } } if (bp === 1) return path; for (i = 0, l = base.length - (bp - 1); i < l; i++) out += "../"; for (i = bp - 1, l = items.length; i < l; i++) { if (i != bp - 1) out += "/" + items[i]; else out += items[i]; } return out; }, toAbsPath : function(base, path) { var i, nb = 0, o = [], tr, outPath; // Split paths tr = /\/$/.test(path) ? '/' : ''; base = base.split('/'); path = path.split('/'); // Remove empty chunks each(base, function(k) { if (k) o.push(k); }); base = o; // Merge relURLParts chunks for (i = path.length - 1, o = []; i >= 0; i--) { // Ignore empty or . if (path[i].length === 0 || path[i] === ".") continue; // Is parent if (path[i] === '..') { nb++; continue; } // Move up if (nb > 0) { nb--; continue; } o.push(path[i]); } i = base.length - nb; // If /a/b/c or / if (i <= 0) outPath = o.reverse().join('/'); else outPath = base.slice(0, i).join('/') + '/' + o.reverse().join('/'); // Add front / if it's needed if (outPath.indexOf('/') !== 0) outPath = '/' + outPath; // Add traling / if it's needed if (tr && outPath.lastIndexOf('/') !== outPath.length - 1) outPath += tr; return outPath; }, getURI : function(nh) { var s, t = this; // Rebuild source if (!t.source || nh) { s = ''; if (!nh) { if (t.protocol) s += t.protocol + '://'; if (t.userInfo) s += t.userInfo + '@'; if (t.host) s += t.host; if (t.port) s += ':' + t.port; } if (t.path) s += t.path; if (t.query) s += '?' + t.query; if (t.anchor) s += '#' + t.anchor; t.source = s; } return t.source; } }); })(); (function() { var each = tinymce.each; tinymce.create('static tinymce.util.Cookie', { getHash : function(n) { var v = this.get(n), h; if (v) { each(v.split('&'), function(v) { v = v.split('='); h = h || {}; h[unescape(v[0])] = unescape(v[1]); }); } return h; }, setHash : function(n, v, e, p, d, s) { var o = ''; each(v, function(v, k) { o += (!o ? '' : '&') + escape(k) + '=' + escape(v); }); this.set(n, o, e, p, d, s); }, get : function(n) { var c = document.cookie, e, p = n + "=", b; // Strict mode if (!c) return; b = c.indexOf("; " + p); if (b == -1) { b = c.indexOf(p); if (b !== 0) return null; } else b += 2; e = c.indexOf(";", b); if (e == -1) e = c.length; return unescape(c.substring(b + p.length, e)); }, set : function(n, v, e, p, d, s) { document.cookie = n + "=" + escape(v) + ((e) ? "; expires=" + e.toGMTString() : "") + ((p) ? "; path=" + escape(p) : "") + ((d) ? "; domain=" + d : "") + ((s) ? "; secure" : ""); }, remove : function(n, p) { var d = new Date(); d.setTime(d.getTime() - 1000); this.set(n, '', d, p, d); } }); })(); (function() { function serialize(o, quote) { var i, v, t, name; quote = quote || '"'; if (o == null) return 'null'; t = typeof o; if (t == 'string') { v = '\bb\tt\nn\ff\rr\""\'\'\\\\'; return quote + o.replace(/([\u0080-\uFFFF\x00-\x1f\"\'\\])/g, function(a, b) { // Make sure single quotes never get encoded inside double quotes for JSON compatibility if (quote === '"' && a === "'") return a; i = v.indexOf(b); if (i + 1) return '\\' + v.charAt(i + 1); a = b.charCodeAt().toString(16); return '\\u' + '0000'.substring(a.length) + a; }) + quote; } if (t == 'object') { if (o.hasOwnProperty && o instanceof Array) { for (i=0, v = '['; i<o.length; i++) v += (i > 0 ? ',' : '') + serialize(o[i], quote); return v + ']'; } v = '{'; for (name in o) { if (o.hasOwnProperty(name)) { v += typeof o[name] != 'function' ? (v.length > 1 ? ',' + quote : quote) + name + quote +':' + serialize(o[name], quote) : ''; } } return v + '}'; } return '' + o; }; tinymce.util.JSON = { serialize: serialize, parse: function(s) { try { return eval('(' + s + ')'); } catch (ex) { // Ignore } } }; })(); tinymce.create('static tinymce.util.XHR', { send : function(o) { var x, t, w = window, c = 0; function ready() { if (!o.async || x.readyState == 4 || c++ > 10000) { if (o.success && c < 10000 && x.status == 200) o.success.call(o.success_scope, '' + x.responseText, x, o); else if (o.error) o.error.call(o.error_scope, c > 10000 ? 'TIMED_OUT' : 'GENERAL', x, o); x = null; } else w.setTimeout(ready, 10); }; // Default settings o.scope = o.scope || this; o.success_scope = o.success_scope || o.scope; o.error_scope = o.error_scope || o.scope; o.async = o.async === false ? false : true; o.data = o.data || ''; function get(s) { x = 0; try { x = new ActiveXObject(s); } catch (ex) { } return x; }; x = w.XMLHttpRequest ? new XMLHttpRequest() : get('Microsoft.XMLHTTP') || get('Msxml2.XMLHTTP'); if (x) { if (x.overrideMimeType) x.overrideMimeType(o.content_type); x.open(o.type || (o.data ? 'POST' : 'GET'), o.url, o.async); if (o.content_type) x.setRequestHeader('Content-Type', o.content_type); x.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); x.send(o.data); // Syncronous request if (!o.async) return ready(); // Wait for response, onReadyStateChange can not be used since it leaks memory in IE t = w.setTimeout(ready, 10); } } }); (function() { var extend = tinymce.extend, JSON = tinymce.util.JSON, XHR = tinymce.util.XHR; tinymce.create('tinymce.util.JSONRequest', { JSONRequest : function(s) { this.settings = extend({ }, s); this.count = 0; }, send : function(o) { var ecb = o.error, scb = o.success; o = extend(this.settings, o); o.success = function(c, x) { c = JSON.parse(c); if (typeof(c) == 'undefined') { c = { error : 'JSON Parse error.' }; } if (c.error) ecb.call(o.error_scope || o.scope, c.error, x); else scb.call(o.success_scope || o.scope, c.result); }; o.error = function(ty, x) { if (ecb) ecb.call(o.error_scope || o.scope, ty, x); }; o.data = JSON.serialize({ id : o.id || 'c' + (this.count++), method : o.method, params : o.params }); // JSON content type for Ruby on rails. Bug: #1883287 o.content_type = 'application/json'; XHR.send(o); }, 'static' : { sendRPC : function(o) { return new tinymce.util.JSONRequest().send(o); } } }); }()); (function(tinymce){ tinymce.VK = { BACKSPACE: 8, DELETE: 46, DOWN: 40, ENTER: 13, LEFT: 37, RIGHT: 39, SPACEBAR: 32, TAB: 9, UP: 38, modifierPressed: function (e) { return e.shiftKey || e.ctrlKey || e.altKey; } }; })(tinymce); tinymce.util.Quirks = function(editor) { var VK = tinymce.VK, BACKSPACE = VK.BACKSPACE, DELETE = VK.DELETE, dom = editor.dom, selection = editor.selection, settings = editor.settings; function setEditorCommandState(cmd, state) { try { editor.getDoc().execCommand(cmd, false, state); } catch (ex) { // Ignore } } function cleanupStylesWhenDeleting() { function removeMergedFormatSpans(isDelete) { var rng, blockElm, node, clonedSpan; rng = selection.getRng(); // Find root block blockElm = dom.getParent(rng.startContainer, dom.isBlock); // On delete clone the root span of the next block element if (isDelete) blockElm = dom.getNext(blockElm, dom.isBlock); // Locate root span element and clone it since it would otherwise get merged by the "apple-style-span" on delete/backspace if (blockElm) { node = blockElm.firstChild; // Ignore empty text nodes while (node && node.nodeType == 3 && node.nodeValue.length === 0) node = node.nextSibling; if (node && node.nodeName === 'SPAN') { clonedSpan = node.cloneNode(false); } } // Do the backspace/delete action editor.getDoc().execCommand(isDelete ? 'ForwardDelete' : 'Delete', false, null); // Find all odd apple-style-spans blockElm = dom.getParent(rng.startContainer, dom.isBlock); tinymce.each(dom.select('span.Apple-style-span,font.Apple-style-span', blockElm), function(span) { var bm = selection.getBookmark(); if (clonedSpan) { dom.replace(clonedSpan.cloneNode(false), span, true); } else { dom.remove(span, true); } // Restore the selection selection.moveToBookmark(bm); }); }; editor.onKeyDown.add(function(editor, e) { var isDelete; if (e.isDefaultPrevented()) { return; } isDelete = e.keyCode == DELETE; if ((isDelete || e.keyCode == BACKSPACE) && !VK.modifierPressed(e)) { e.preventDefault(); removeMergedFormatSpans(isDelete); } }); editor.addCommand('Delete', function() {removeMergedFormatSpans();}); }; function emptyEditorWhenDeleting() { function serializeRng(rng) { var body = dom.create("body"); var contents = rng.cloneContents(); body.appendChild(contents); return selection.serializer.serialize(body, {format: 'html'}); } function allContentsSelected(rng) { var selection = serializeRng(rng); var allRng = dom.createRng(); allRng.selectNode(editor.getBody()); var allSelection = serializeRng(allRng); return selection === allSelection; } editor.onKeyDown.addToTop(function(editor, e) { var keyCode = e.keyCode; if (keyCode == DELETE || keyCode == BACKSPACE) { var rng = selection.getRng(true); if (!rng.collapsed && allContentsSelected(rng)) { editor.setContent('', {format : 'raw'}); editor.nodeChanged(); e.preventDefault(); } } }); }; function inputMethodFocus() { dom.bind(editor.getBody(), 'focusin', function() { selection.setRng(selection.getRng()); }); }; function removeHrOnBackspace() { editor.onKeyDown.add(function(editor, e) { if (e.keyCode === BACKSPACE) { if (selection.isCollapsed() && selection.getRng(true).startOffset === 0) { var node = selection.getNode(); var previousSibling = node.previousSibling; if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === "hr") { dom.remove(previousSibling); tinymce.dom.Event.cancel(e); } } } }) } function focusBody() { // Fix for a focus bug in FF 3.x where the body element // wouldn't get proper focus if the user clicked on the HTML element if (!Range.prototype.getClientRects) { // Detect getClientRects got introduced in FF 4 editor.onMouseDown.add(function(editor, e) { if (e.target.nodeName === "HTML") { var body = editor.getBody(); // Blur the body it's focused but not correctly focused body.blur(); // Refocus the body after a little while setTimeout(function() { body.focus(); }, 0); } }); } }; function selectControlElements() { editor.onClick.add(function(editor, e) { e = e.target; // Workaround for bug, http://bugs.webkit.org/show_bug.cgi?id=12250 // WebKit can't even do simple things like selecting an image // Needs tobe the setBaseAndExtend or it will fail to select floated images if (/^(IMG|HR)$/.test(e.nodeName)) { selection.getSel().setBaseAndExtent(e, 0, e, 1); } if (e.nodeName == 'A' && dom.hasClass(e, 'mceItemAnchor')) { selection.select(e); } editor.nodeChanged(); }); }; function removeStylesWhenDeletingAccrossBlockElements() { function getAttributeApplyFunction() { var template = dom.getAttribs(selection.getStart().cloneNode(false)); return function() { var target = selection.getStart(); if (target !== editor.getBody()) { dom.setAttrib(target, "style", null); tinymce.each(template, function(attr) { target.setAttributeNode(attr.cloneNode(true)); }); } }; } function isSelectionAcrossElements() { return !selection.isCollapsed() && selection.getStart() != selection.getEnd(); } function blockEvent(editor, e) { e.preventDefault(); return false; } editor.onKeyPress.add(function(editor, e) { var applyAttributes; if ((e.keyCode == 8 || e.keyCode == 46) && isSelectionAcrossElements()) { applyAttributes = getAttributeApplyFunction(); editor.getDoc().execCommand('delete', false, null); applyAttributes(); e.preventDefault(); return false; } }); dom.bind(editor.getDoc(), 'cut', function(e) { var applyAttributes; if (isSelectionAcrossElements()) { applyAttributes = getAttributeApplyFunction(); editor.onKeyUp.addToTop(blockEvent); setTimeout(function() { applyAttributes(); editor.onKeyUp.remove(blockEvent); }, 0); } }); } function selectionChangeNodeChanged() { var lastRng, selectionTimer; dom.bind(editor.getDoc(), 'selectionchange', function() { if (selectionTimer) { clearTimeout(selectionTimer); selectionTimer = 0; } selectionTimer = window.setTimeout(function() { var rng = selection.getRng(); // Compare the ranges to see if it was a real change or not if (!lastRng || !tinymce.dom.RangeUtils.compareRanges(rng, lastRng)) { editor.nodeChanged(); lastRng = rng; } }, 50); }); } function ensureBodyHasRoleApplication() { document.body.setAttribute("role", "application"); } function disableBackspaceIntoATable() { editor.onKeyDown.add(function(editor, e) { if (e.keyCode === BACKSPACE) { if (selection.isCollapsed() && selection.getRng(true).startOffset === 0) { var previousSibling = selection.getNode().previousSibling; if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === "table") { return tinymce.dom.Event.cancel(e); } } } }) } function addNewLinesBeforeBrInPre() { var documentMode = editor.getDoc().documentMode; // IE8+ rendering mode does the right thing with BR in PRE if (documentMode && documentMode > 7) { return; } // Enable display: none in area and add a specific class that hides all BR elements in PRE to // avoid the caret from getting stuck at the BR elements while pressing the right arrow key setEditorCommandState('RespectVisibilityInDesign', true); dom.addClass(editor.getBody(), 'mceHideBrInPre'); // Adds a \n before all BR elements in PRE to get them visual editor.parser.addNodeFilter('pre', function(nodes, name) { var i = nodes.length, brNodes, j, brElm, sibling; while (i--) { brNodes = nodes[i].getAll('br'); j = brNodes.length; while (j--) { brElm = brNodes[j]; // Add \n before BR in PRE elements on older IE:s so the new lines get rendered sibling = brElm.prev; if (sibling && sibling.type === 3 && sibling.value.charAt(sibling.value - 1) != '\n') { sibling.value += '\n'; } else { brElm.parent.insert(new tinymce.html.Node('#text', 3), brElm, true).value = '\n'; } } } }); // Removes any \n before BR elements in PRE since other browsers and in contentEditable=false mode they will be visible editor.serializer.addNodeFilter('pre', function(nodes, name) { var i = nodes.length, brNodes, j, brElm, sibling; while (i--) { brNodes = nodes[i].getAll('br'); j = brNodes.length; while (j--) { brElm = brNodes[j]; sibling = brElm.prev; if (sibling && sibling.type == 3) { sibling.value = sibling.value.replace(/\r?\n$/, ''); } } } }); } function removePreSerializedStylesWhenSelectingControls() { dom.bind(editor.getBody(), 'mouseup', function(e) { var value, node = selection.getNode(); // Moved styles to attributes on IMG eements if (node.nodeName == 'IMG') { // Convert style width to width attribute if (value = dom.getStyle(node, 'width')) { dom.setAttrib(node, 'width', value.replace(/[^0-9%]+/g, '')); dom.setStyle(node, 'width', ''); } // Convert style height to height attribute if (value = dom.getStyle(node, 'height')) { dom.setAttrib(node, 'height', value.replace(/[^0-9%]+/g, '')); dom.setStyle(node, 'height', ''); } } }); } function keepInlineElementOnDeleteBackspace() { editor.onKeyDown.add(function(editor, e) { var isDelete, rng, container, offset, brElm, sibling, collapsed; if (e.isDefaultPrevented()) { return; } isDelete = e.keyCode == DELETE; if ((isDelete || e.keyCode == BACKSPACE) && !VK.modifierPressed(e)) { rng = selection.getRng(); container = rng.startContainer; offset = rng.startOffset; collapsed = rng.collapsed; // Override delete if the start container is a text node and is at the beginning of text or // just before/after the last character to be deleted in collapsed mode if (container.nodeType == 3 && container.nodeValue.length > 0 && ((offset === 0 && !collapsed) || (collapsed && offset === (isDelete ? 0 : 1)))) { nonEmptyElements = editor.schema.getNonEmptyElements(); // Prevent default logic since it's broken e.preventDefault(); // Insert a BR before the text node this will prevent the containing element from being deleted/converted brElm = dom.create('br', {id: '__tmp'}); container.parentNode.insertBefore(brElm, container); // Do the browser delete editor.getDoc().execCommand(isDelete ? 'ForwardDelete' : 'Delete', false, null); // Check if the previous sibling is empty after deleting for example: <p><b></b>|</p> container = selection.getRng().startContainer; sibling = container.previousSibling; if (sibling && sibling.nodeType == 1 && !dom.isBlock(sibling) && dom.isEmpty(sibling) && !nonEmptyElements[sibling.nodeName.toLowerCase()]) { dom.remove(sibling); } // Remove the temp element we inserted dom.remove('__tmp'); } } }); } function removeBlockQuoteOnBackSpace() { // Add block quote deletion handler editor.onKeyDown.add(function(editor, e) { var rng, container, offset, root, parent; if (e.keyCode != VK.BACKSPACE) { return; } rng = selection.getRng(); container = rng.startContainer; offset = rng.startOffset; root = dom.getRoot(); parent = container; if (!rng.collapsed || offset !== 0) { return; } while (parent && parent.parentNode.firstChild == parent && parent.parentNode != root) { parent = parent.parentNode; } // Is the cursor at the beginning of a blockquote? if (parent.tagName === 'BLOCKQUOTE') { // Remove the blockquote editor.formatter.toggle('blockquote', null, parent); // Move the caret to the beginning of container rng.setStart(container, 0); rng.setEnd(container, 0); selection.setRng(rng); selection.collapse(false); } }); }; function setGeckoEditingOptions() { function setOpts() { editor._refreshContentEditable(); setEditorCommandState("StyleWithCSS", false); setEditorCommandState("enableInlineTableEditing", false); if (!settings.object_resizing) { setEditorCommandState("enableObjectResizing", false); } }; if (!settings.readonly) { editor.onBeforeExecCommand.add(setOpts); editor.onMouseDown.add(setOpts); } }; function addBrAfterLastLinks() { function fixLinks(editor, o) { tinymce.each(dom.select('a'), function(node) { var parentNode = node.parentNode, root = dom.getRoot(); if (parentNode.lastChild === node) { while (parentNode && !dom.isBlock(parentNode)) { if (parentNode.parentNode.lastChild !== parentNode || parentNode === root) { return; } parentNode = parentNode.parentNode; } dom.add(parentNode, 'br', {'data-mce-bogus' : 1}); } }); }; editor.onExecCommand.add(function(editor, cmd) { if (cmd === 'CreateLink') { fixLinks(editor); } }); editor.onSetContent.add(selection.onSetContent.add(fixLinks)); }; function removeGhostSelection() { function repaint(sender, args) { if (!sender || !args.initial) { editor.execCommand('mceRepaint'); } }; editor.onUndo.add(repaint); editor.onRedo.add(repaint); editor.onSetContent.add(repaint); }; function deleteImageOnBackSpace() { editor.onKeyDown.add(function(editor, e) { if (e.keyCode == 8 && selection.getNode().nodeName == 'IMG') { e.preventDefault(); editor.undoManager.beforeChange(); dom.remove(selection.getNode()); editor.undoManager.add(); } }); }; // All browsers disableBackspaceIntoATable(); removeBlockQuoteOnBackSpace(); // WebKit if (tinymce.isWebKit) { keepInlineElementOnDeleteBackspace(); cleanupStylesWhenDeleting(); emptyEditorWhenDeleting(); inputMethodFocus(); selectControlElements(); // iOS if (tinymce.isIDevice) { selectionChangeNodeChanged(); } } // IE if (tinymce.isIE) { removeHrOnBackspace(); emptyEditorWhenDeleting(); ensureBodyHasRoleApplication(); addNewLinesBeforeBrInPre(); removePreSerializedStylesWhenSelectingControls(); deleteImageOnBackSpace(); } // Gecko if (tinymce.isGecko) { removeHrOnBackspace(); focusBody(); removeStylesWhenDeletingAccrossBlockElements(); setGeckoEditingOptions(); addBrAfterLastLinks(); removeGhostSelection(); } }; (function(tinymce) { var namedEntities, baseEntities, reverseEntities, attrsCharsRegExp = /[&<>\"\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g, textCharsRegExp = /[<>&\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g, rawCharsRegExp = /[<>&\"\']/g, entityRegExp = /&(#x|#)?([\w]+);/g, asciiMap = { 128 : "\u20AC", 130 : "\u201A", 131 : "\u0192", 132 : "\u201E", 133 : "\u2026", 134 : "\u2020", 135 : "\u2021", 136 : "\u02C6", 137 : "\u2030", 138 : "\u0160", 139 : "\u2039", 140 : "\u0152", 142 : "\u017D", 145 : "\u2018", 146 : "\u2019", 147 : "\u201C", 148 : "\u201D", 149 : "\u2022", 150 : "\u2013", 151 : "\u2014", 152 : "\u02DC", 153 : "\u2122", 154 : "\u0161", 155 : "\u203A", 156 : "\u0153", 158 : "\u017E", 159 : "\u0178" }; // Raw entities baseEntities = { '\"' : '&quot;', // Needs to be escaped since the YUI compressor would otherwise break the code "'" : '&#39;', '<' : '&lt;', '>' : '&gt;', '&' : '&amp;' }; // Reverse lookup table for raw entities reverseEntities = { '&lt;' : '<', '&gt;' : '>', '&amp;' : '&', '&quot;' : '"', '&apos;' : "'" }; // Decodes text by using the browser function nativeDecode(text) { var elm; elm = document.createElement("div"); elm.innerHTML = text; return elm.textContent || elm.innerText || text; }; // Build a two way lookup table for the entities function buildEntitiesLookup(items, radix) { var i, chr, entity, lookup = {}; if (items) { items = items.split(','); radix = radix || 10; // Build entities lookup table for (i = 0; i < items.length; i += 2) { chr = String.fromCharCode(parseInt(items[i], radix)); // Only add non base entities if (!baseEntities[chr]) { entity = '&' + items[i + 1] + ';'; lookup[chr] = entity; lookup[entity] = chr; } } return lookup; } }; // Unpack entities lookup where the numbers are in radix 32 to reduce the size namedEntities = buildEntitiesLookup( '50,nbsp,51,iexcl,52,cent,53,pound,54,curren,55,yen,56,brvbar,57,sect,58,uml,59,copy,' + '5a,ordf,5b,laquo,5c,not,5d,shy,5e,reg,5f,macr,5g,deg,5h,plusmn,5i,sup2,5j,sup3,5k,acute,' + '5l,micro,5m,para,5n,middot,5o,cedil,5p,sup1,5q,ordm,5r,raquo,5s,frac14,5t,frac12,5u,frac34,' + '5v,iquest,60,Agrave,61,Aacute,62,Acirc,63,Atilde,64,Auml,65,Aring,66,AElig,67,Ccedil,' + '68,Egrave,69,Eacute,6a,Ecirc,6b,Euml,6c,Igrave,6d,Iacute,6e,Icirc,6f,Iuml,6g,ETH,6h,Ntilde,' + '6i,Ograve,6j,Oacute,6k,Ocirc,6l,Otilde,6m,Ouml,6n,times,6o,Oslash,6p,Ugrave,6q,Uacute,' + '6r,Ucirc,6s,Uuml,6t,Yacute,6u,THORN,6v,szlig,70,agrave,71,aacute,72,acirc,73,atilde,74,auml,' + '75,aring,76,aelig,77,ccedil,78,egrave,79,eacute,7a,ecirc,7b,euml,7c,igrave,7d,iacute,7e,icirc,' + '7f,iuml,7g,eth,7h,ntilde,7i,ograve,7j,oacute,7k,ocirc,7l,otilde,7m,ouml,7n,divide,7o,oslash,' + '7p,ugrave,7q,uacute,7r,ucirc,7s,uuml,7t,yacute,7u,thorn,7v,yuml,ci,fnof,sh,Alpha,si,Beta,' + 'sj,Gamma,sk,Delta,sl,Epsilon,sm,Zeta,sn,Eta,so,Theta,sp,Iota,sq,Kappa,sr,Lambda,ss,Mu,' + 'st,Nu,su,Xi,sv,Omicron,t0,Pi,t1,Rho,t3,Sigma,t4,Tau,t5,Upsilon,t6,Phi,t7,Chi,t8,Psi,' + 't9,Omega,th,alpha,ti,beta,tj,gamma,tk,delta,tl,epsilon,tm,zeta,tn,eta,to,theta,tp,iota,' + 'tq,kappa,tr,lambda,ts,mu,tt,nu,tu,xi,tv,omicron,u0,pi,u1,rho,u2,sigmaf,u3,sigma,u4,tau,' + 'u5,upsilon,u6,phi,u7,chi,u8,psi,u9,omega,uh,thetasym,ui,upsih,um,piv,812,bull,816,hellip,' + '81i,prime,81j,Prime,81u,oline,824,frasl,88o,weierp,88h,image,88s,real,892,trade,89l,alefsym,' + '8cg,larr,8ch,uarr,8ci,rarr,8cj,darr,8ck,harr,8dl,crarr,8eg,lArr,8eh,uArr,8ei,rArr,8ej,dArr,' + '8ek,hArr,8g0,forall,8g2,part,8g3,exist,8g5,empty,8g7,nabla,8g8,isin,8g9,notin,8gb,ni,8gf,prod,' + '8gh,sum,8gi,minus,8gn,lowast,8gq,radic,8gt,prop,8gu,infin,8h0,ang,8h7,and,8h8,or,8h9,cap,8ha,cup,' + '8hb,int,8hk,there4,8hs,sim,8i5,cong,8i8,asymp,8j0,ne,8j1,equiv,8j4,le,8j5,ge,8k2,sub,8k3,sup,8k4,' + 'nsub,8k6,sube,8k7,supe,8kl,oplus,8kn,otimes,8l5,perp,8m5,sdot,8o8,lceil,8o9,rceil,8oa,lfloor,8ob,' + 'rfloor,8p9,lang,8pa,rang,9ea,loz,9j0,spades,9j3,clubs,9j5,hearts,9j6,diams,ai,OElig,aj,oelig,b0,' + 'Scaron,b1,scaron,bo,Yuml,m6,circ,ms,tilde,802,ensp,803,emsp,809,thinsp,80c,zwnj,80d,zwj,80e,lrm,' + '80f,rlm,80j,ndash,80k,mdash,80o,lsquo,80p,rsquo,80q,sbquo,80s,ldquo,80t,rdquo,80u,bdquo,810,dagger,' + '811,Dagger,81g,permil,81p,lsaquo,81q,rsaquo,85c,euro', 32); tinymce.html = tinymce.html || {}; tinymce.html.Entities = { encodeRaw : function(text, attr) { return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) { return baseEntities[chr] || chr; }); }, encodeAllRaw : function(text) { return ('' + text).replace(rawCharsRegExp, function(chr) { return baseEntities[chr] || chr; }); }, encodeNumeric : function(text, attr) { return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) { // Multi byte sequence convert it to a single entity if (chr.length > 1) return '&#' + (((chr.charCodeAt(0) - 0xD800) * 0x400) + (chr.charCodeAt(1) - 0xDC00) + 0x10000) + ';'; return baseEntities[chr] || '&#' + chr.charCodeAt(0) + ';'; }); }, encodeNamed : function(text, attr, entities) { entities = entities || namedEntities; return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) { return baseEntities[chr] || entities[chr] || chr; }); }, getEncodeFunc : function(name, entities) { var Entities = tinymce.html.Entities; entities = buildEntitiesLookup(entities) || namedEntities; function encodeNamedAndNumeric(text, attr) { return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) { return baseEntities[chr] || entities[chr] || '&#' + chr.charCodeAt(0) + ';' || chr; }); }; function encodeCustomNamed(text, attr) { return Entities.encodeNamed(text, attr, entities); }; // Replace + with , to be compatible with previous TinyMCE versions name = tinymce.makeMap(name.replace(/\+/g, ',')); // Named and numeric encoder if (name.named && name.numeric) return encodeNamedAndNumeric; // Named encoder if (name.named) { // Custom names if (entities) return encodeCustomNamed; return Entities.encodeNamed; } // Numeric if (name.numeric) return Entities.encodeNumeric; // Raw encoder return Entities.encodeRaw; }, decode : function(text) { return text.replace(entityRegExp, function(all, numeric, value) { if (numeric) { value = parseInt(value, numeric.length === 2 ? 16 : 10); // Support upper UTF if (value > 0xFFFF) { value -= 0x10000; return String.fromCharCode(0xD800 + (value >> 10), 0xDC00 + (value & 0x3FF)); } else return asciiMap[value] || String.fromCharCode(value); } return reverseEntities[all] || namedEntities[all] || nativeDecode(all); }); } }; })(tinymce); tinymce.html.Styles = function(settings, schema) { var rgbRegExp = /rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*\)/gi, urlOrStrRegExp = /(?:url(?:(?:\(\s*\"([^\"]+)\"\s*\))|(?:\(\s*\'([^\']+)\'\s*\))|(?:\(\s*([^)\s]+)\s*\))))|(?:\'([^\']+)\')|(?:\"([^\"]+)\")/gi, styleRegExp = /\s*([^:]+):\s*([^;]+);?/g, trimRightRegExp = /\s+$/, urlColorRegExp = /rgb/, undef, i, encodingLookup = {}, encodingItems; settings = settings || {}; encodingItems = '\\" \\\' \\; \\: ; : \uFEFF'.split(' '); for (i = 0; i < encodingItems.length; i++) { encodingLookup[encodingItems[i]] = '\uFEFF' + i; encodingLookup['\uFEFF' + i] = encodingItems[i]; } function toHex(match, r, g, b) { function hex(val) { val = parseInt(val).toString(16); return val.length > 1 ? val : '0' + val; // 0 -> 00 }; return '#' + hex(r) + hex(g) + hex(b); }; return { toHex : function(color) { return color.replace(rgbRegExp, toHex); }, parse : function(css) { var styles = {}, matches, name, value, isEncoded, urlConverter = settings.url_converter, urlConverterScope = settings.url_converter_scope || this; function compress(prefix, suffix) { var top, right, bottom, left; // Get values and check it it needs compressing top = styles[prefix + '-top' + suffix]; if (!top) return; right = styles[prefix + '-right' + suffix]; if (top != right) return; bottom = styles[prefix + '-bottom' + suffix]; if (right != bottom) return; left = styles[prefix + '-left' + suffix]; if (bottom != left) return; // Compress styles[prefix + suffix] = left; delete styles[prefix + '-top' + suffix]; delete styles[prefix + '-right' + suffix]; delete styles[prefix + '-bottom' + suffix]; delete styles[prefix + '-left' + suffix]; }; function canCompress(key) { var value = styles[key], i; if (!value || value.indexOf(' ') < 0) return; value = value.split(' '); i = value.length; while (i--) { if (value[i] !== value[0]) return false; } styles[key] = value[0]; return true; }; function compress2(target, a, b, c) { if (!canCompress(a)) return; if (!canCompress(b)) return; if (!canCompress(c)) return; // Compress styles[target] = styles[a] + ' ' + styles[b] + ' ' + styles[c]; delete styles[a]; delete styles[b]; delete styles[c]; }; // Encodes the specified string by replacing all \" \' ; : with _<num> function encode(str) { isEncoded = true; return encodingLookup[str]; }; // Decodes the specified string by replacing all _<num> with it's original value \" \' etc // It will also decode the \" \' if keep_slashes is set to fale or omitted function decode(str, keep_slashes) { if (isEncoded) { str = str.replace(/\uFEFF[0-9]/g, function(str) { return encodingLookup[str]; }); } if (!keep_slashes) str = str.replace(/\\([\'\";:])/g, "$1"); return str; }; function processUrl(match, url, url2, url3, str, str2) { str = str || str2; if (str) { str = decode(str); // Force strings into single quote format return "'" + str.replace(/\'/g, "\\'") + "'"; } url = decode(url || url2 || url3); // Convert the URL to relative/absolute depending on config if (urlConverter) url = urlConverter.call(urlConverterScope, url, 'style'); // Output new URL format return "url('" + url.replace(/\'/g, "\\'") + "')"; }; if (css) { // Encode \" \' % and ; and : inside strings so they don't interfere with the style parsing css = css.replace(/\\[\"\';:\uFEFF]/g, encode).replace(/\"[^\"]+\"|\'[^\']+\'/g, function(str) { return str.replace(/[;:]/g, encode); }); // Parse styles while (matches = styleRegExp.exec(css)) { name = matches[1].replace(trimRightRegExp, '').toLowerCase(); value = matches[2].replace(trimRightRegExp, ''); if (name && value.length > 0) { // Opera will produce 700 instead of bold in their style values if (name === 'font-weight' && value === '700') value = 'bold'; else if (name === 'color' || name === 'background-color') // Lowercase colors like RED value = value.toLowerCase(); // Convert RGB colors to HEX value = value.replace(rgbRegExp, toHex); // Convert URLs and force them into url('value') format value = value.replace(urlOrStrRegExp, processUrl); styles[name] = isEncoded ? decode(value, true) : value; } styleRegExp.lastIndex = matches.index + matches[0].length; } // Compress the styles to reduce it's size for example IE will expand styles compress("border", ""); compress("border", "-width"); compress("border", "-color"); compress("border", "-style"); compress("padding", ""); compress("margin", ""); compress2('border', 'border-width', 'border-style', 'border-color'); // Remove pointless border, IE produces these if (styles.border === 'medium none') delete styles.border; } return styles; }, serialize : function(styles, element_name) { var css = '', name, value; function serializeStyles(name) { var styleList, i, l, value; styleList = schema.styles[name]; if (styleList) { for (i = 0, l = styleList.length; i < l; i++) { name = styleList[i]; value = styles[name]; if (value !== undef && value.length > 0) css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';'; } } }; // Serialize styles according to schema if (element_name && schema && schema.styles) { // Serialize global styles and element specific styles serializeStyles('*'); serializeStyles(element_name); } else { // Output the styles in the order they are inside the object for (name in styles) { value = styles[name]; if (value !== undef && value.length > 0) css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';'; } } return css; } }; }; (function(tinymce) { var mapCache = {}, makeMap = tinymce.makeMap, each = tinymce.each; function split(str, delim) { return str.split(delim || ','); }; function unpack(lookup, data) { var key, elements = {}; function replace(value) { return value.replace(/[A-Z]+/g, function(key) { return replace(lookup[key]); }); }; // Unpack lookup for (key in lookup) { if (lookup.hasOwnProperty(key)) lookup[key] = replace(lookup[key]); } // Unpack and parse data into object map replace(data).replace(/#/g, '#text').replace(/(\w+)\[([^\]]+)\]\[([^\]]*)\]/g, function(str, name, attributes, children) { attributes = split(attributes, '|'); elements[name] = { attributes : makeMap(attributes), attributesOrder : attributes, children : makeMap(children, '|', {'#comment' : {}}) } }); return elements; }; function getHTML5() { var html5 = mapCache.html5; if (!html5) { html5 = mapCache.html5 = unpack({ A : 'id|accesskey|class|dir|draggable|item|hidden|itemprop|role|spellcheck|style|subject|title', B : '#|a|abbr|area|audio|b|bdo|br|button|canvas|cite|code|command|datalist|del|dfn|em|embed|i|iframe|img|input|ins|kbd|keygen|label|link|map|mark|meta|meter|noscript|object|output|progress|q|ruby|samp|script|select|small|span|strong|sub|sup|svg|textarea|time|var|video', C : '#|a|abbr|area|address|article|aside|audio|b|bdo|blockquote|br|button|canvas|cite|code|command|datalist|del|details|dfn|dialog|div|dl|em|embed|fieldset|figure|footer|form|h1|h2|h3|h4|h5|h6|header|hgroup|hr|i|iframe|img|input|ins|kbd|keygen|label|link|map|mark|menu|meta|meter|nav|noscript|ol|object|output|p|pre|progress|q|ruby|samp|script|section|select|small|span|strong|style|sub|sup|svg|table|textarea|time|ul|var|video' }, 'html[A|manifest][body|head]' + 'head[A][base|command|link|meta|noscript|script|style|title]' + 'title[A][#]' + 'base[A|href|target][]' + 'link[A|href|rel|media|type|sizes][]' + 'meta[A|http-equiv|name|content|charset][]' + 'style[A|type|media|scoped][#]' + 'script[A|charset|type|src|defer|async][#]' + 'noscript[A][C]' + 'body[A][C]' + 'section[A][C]' + 'nav[A][C]' + 'article[A][C]' + 'aside[A][C]' + 'h1[A][B]' + 'h2[A][B]' + 'h3[A][B]' + 'h4[A][B]' + 'h5[A][B]' + 'h6[A][B]' + 'hgroup[A][h1|h2|h3|h4|h5|h6]' + 'header[A][C]' + 'footer[A][C]' + 'address[A][C]' + 'p[A][B]' + 'br[A][]' + 'pre[A][B]' + 'dialog[A][dd|dt]' + 'blockquote[A|cite][C]' + 'ol[A|start|reversed][li]' + 'ul[A][li]' + 'li[A|value][C]' + 'dl[A][dd|dt]' + 'dt[A][B]' + 'dd[A][C]' + 'a[A|href|target|ping|rel|media|type][C]' + 'em[A][B]' + 'strong[A][B]' + 'small[A][B]' + 'cite[A][B]' + 'q[A|cite][B]' + 'dfn[A][B]' + 'abbr[A][B]' + 'code[A][B]' + 'var[A][B]' + 'samp[A][B]' + 'kbd[A][B]' + 'sub[A][B]' + 'sup[A][B]' + 'i[A][B]' + 'b[A][B]' + 'mark[A][B]' + 'progress[A|value|max][B]' + 'meter[A|value|min|max|low|high|optimum][B]' + 'time[A|datetime][B]' + 'ruby[A][B|rt|rp]' + 'rt[A][B]' + 'rp[A][B]' + 'bdo[A][B]' + 'span[A][B]' + 'ins[A|cite|datetime][B]' + 'del[A|cite|datetime][B]' + 'figure[A][C|legend|figcaption]' + 'figcaption[A][C]' + 'img[A|alt|src|height|width|usemap|ismap][]' + 'iframe[A|name|src|height|width|sandbox|seamless][]' + 'embed[A|src|height|width|type][]' + 'object[A|data|type|height|width|usemap|name|form|classid][param]' + 'param[A|name|value][]' + 'details[A|open][C|legend]' + 'command[A|type|label|icon|disabled|checked|radiogroup][]' + 'menu[A|type|label][C|li]' + 'legend[A][C|B]' + 'div[A][C]' + 'source[A|src|type|media][]' + 'audio[A|src|autobuffer|autoplay|loop|controls][source]' + 'video[A|src|autobuffer|autoplay|loop|controls|width|height|poster][source]' + 'hr[A][]' + 'form[A|accept-charset|action|autocomplete|enctype|method|name|novalidate|target][C]' + 'fieldset[A|disabled|form|name][C|legend]' + 'label[A|form|for][B]' + 'input[A|type|accept|alt|autocomplete|checked|disabled|form|formaction|formenctype|formmethod|formnovalidate|formtarget|height|list|max|maxlength|min|multiple|pattern|placeholder|readonly|required|size|src|step|width|files|value][]' + 'button[A|autofocus|disabled|form|formaction|formenctype|formmethod|formnovalidate|formtarget|name|value|type][B]' + 'select[A|autofocus|disabled|form|multiple|name|size][option|optgroup]' + 'datalist[A][B|option]' + 'optgroup[A|disabled|label][option]' + 'option[A|disabled|selected|label|value][]' + 'textarea[A|autofocus|disabled|form|maxlength|name|placeholder|readonly|required|rows|cols|wrap][]' + 'keygen[A|autofocus|challenge|disabled|form|keytype|name][]' + 'output[A|for|form|name][B]' + 'canvas[A|width|height][]' + 'map[A|name][B|C]' + 'area[A|shape|coords|href|alt|target|media|rel|ping|type][]' + 'mathml[A][]' + 'svg[A][]' + 'table[A|summary][caption|colgroup|thead|tfoot|tbody|tr]' + 'caption[A][C]' + 'colgroup[A|span][col]' + 'col[A|span][]' + 'thead[A][tr]' + 'tfoot[A][tr]' + 'tbody[A][tr]' + 'tr[A][th|td]' + 'th[A|headers|rowspan|colspan|scope][B]' + 'td[A|headers|rowspan|colspan][C]' ); } return html5; }; function getHTML4() { var html4 = mapCache.html4; if (!html4) { // This is the XHTML 1.0 transitional elements with it's attributes and children packed to reduce it's size html4 = mapCache.html4 = unpack({ Z : 'H|K|N|O|P', Y : 'X|form|R|Q', ZG : 'E|span|width|align|char|charoff|valign', X : 'p|T|div|U|W|isindex|fieldset|table', ZF : 'E|align|char|charoff|valign', W : 'pre|hr|blockquote|address|center|noframes', ZE : 'abbr|axis|headers|scope|rowspan|colspan|align|char|charoff|valign|nowrap|bgcolor|width|height', ZD : '[E][S]', U : 'ul|ol|dl|menu|dir', ZC : 'p|Y|div|U|W|table|br|span|bdo|object|applet|img|map|K|N|Q', T : 'h1|h2|h3|h4|h5|h6', ZB : 'X|S|Q', S : 'R|P', ZA : 'a|G|J|M|O|P', R : 'a|H|K|N|O', Q : 'noscript|P', P : 'ins|del|script', O : 'input|select|textarea|label|button', N : 'M|L', M : 'em|strong|dfn|code|q|samp|kbd|var|cite|abbr|acronym', L : 'sub|sup', K : 'J|I', J : 'tt|i|b|u|s|strike', I : 'big|small|font|basefont', H : 'G|F', G : 'br|span|bdo', F : 'object|applet|img|map|iframe', E : 'A|B|C', D : 'accesskey|tabindex|onfocus|onblur', C : 'onclick|ondblclick|onmousedown|onmouseup|onmouseover|onmousemove|onmouseout|onkeypress|onkeydown|onkeyup', B : 'lang|xml:lang|dir', A : 'id|class|style|title' }, 'script[id|charset|type|language|src|defer|xml:space][]' + 'style[B|id|type|media|title|xml:space][]' + 'object[E|declare|classid|codebase|data|type|codetype|archive|standby|width|height|usemap|name|tabindex|align|border|hspace|vspace][#|param|Y]' + 'param[id|name|value|valuetype|type][]' + 'p[E|align][#|S]' + 'a[E|D|charset|type|name|href|hreflang|rel|rev|shape|coords|target][#|Z]' + 'br[A|clear][]' + 'span[E][#|S]' + 'bdo[A|C|B][#|S]' + 'applet[A|codebase|archive|code|object|alt|name|width|height|align|hspace|vspace][#|param|Y]' + 'h1[E|align][#|S]' + 'img[E|src|alt|name|longdesc|width|height|usemap|ismap|align|border|hspace|vspace][]' + 'map[B|C|A|name][X|form|Q|area]' + 'h2[E|align][#|S]' + 'iframe[A|longdesc|name|src|frameborder|marginwidth|marginheight|scrolling|align|width|height][#|Y]' + 'h3[E|align][#|S]' + 'tt[E][#|S]' + 'i[E][#|S]' + 'b[E][#|S]' + 'u[E][#|S]' + 's[E][#|S]' + 'strike[E][#|S]' + 'big[E][#|S]' + 'small[E][#|S]' + 'font[A|B|size|color|face][#|S]' + 'basefont[id|size|color|face][]' + 'em[E][#|S]' + 'strong[E][#|S]' + 'dfn[E][#|S]' + 'code[E][#|S]' + 'q[E|cite][#|S]' + 'samp[E][#|S]' + 'kbd[E][#|S]' + 'var[E][#|S]' + 'cite[E][#|S]' + 'abbr[E][#|S]' + 'acronym[E][#|S]' + 'sub[E][#|S]' + 'sup[E][#|S]' + 'input[E|D|type|name|value|checked|disabled|readonly|size|maxlength|src|alt|usemap|onselect|onchange|accept|align][]' + 'select[E|name|size|multiple|disabled|tabindex|onfocus|onblur|onchange][optgroup|option]' + 'optgroup[E|disabled|label][option]' + 'option[E|selected|disabled|label|value][]' + 'textarea[E|D|name|rows|cols|disabled|readonly|onselect|onchange][]' + 'label[E|for|accesskey|onfocus|onblur][#|S]' + 'button[E|D|name|value|type|disabled][#|p|T|div|U|W|table|G|object|applet|img|map|K|N|Q]' + 'h4[E|align][#|S]' + 'ins[E|cite|datetime][#|Y]' + 'h5[E|align][#|S]' + 'del[E|cite|datetime][#|Y]' + 'h6[E|align][#|S]' + 'div[E|align][#|Y]' + 'ul[E|type|compact][li]' + 'li[E|type|value][#|Y]' + 'ol[E|type|compact|start][li]' + 'dl[E|compact][dt|dd]' + 'dt[E][#|S]' + 'dd[E][#|Y]' + 'menu[E|compact][li]' + 'dir[E|compact][li]' + 'pre[E|width|xml:space][#|ZA]' + 'hr[E|align|noshade|size|width][]' + 'blockquote[E|cite][#|Y]' + 'address[E][#|S|p]' + 'center[E][#|Y]' + 'noframes[E][#|Y]' + 'isindex[A|B|prompt][]' + 'fieldset[E][#|legend|Y]' + 'legend[E|accesskey|align][#|S]' + 'table[E|summary|width|border|frame|rules|cellspacing|cellpadding|align|bgcolor][caption|col|colgroup|thead|tfoot|tbody|tr]' + 'caption[E|align][#|S]' + 'col[ZG][]' + 'colgroup[ZG][col]' + 'thead[ZF][tr]' + 'tr[ZF|bgcolor][th|td]' + 'th[E|ZE][#|Y]' + 'form[E|action|method|name|enctype|onsubmit|onreset|accept|accept-charset|target][#|X|R|Q]' + 'noscript[E][#|Y]' + 'td[E|ZE][#|Y]' + 'tfoot[ZF][tr]' + 'tbody[ZF][tr]' + 'area[E|D|shape|coords|href|nohref|alt|target][]' + 'base[id|href|target][]' + 'body[E|onload|onunload|background|bgcolor|text|link|vlink|alink][#|Y]' ); } return html4; }; tinymce.html.Schema = function(settings) { var self = this, elements = {}, children = {}, patternElements = [], validStyles, schemaItems; var whiteSpaceElementsMap, selfClosingElementsMap, shortEndedElementsMap, boolAttrMap, blockElementsMap, nonEmptyElementsMap, customElementsMap = {}; // Creates an lookup table map object for the specified option or the default value function createLookupTable(option, default_value, extend) { var value = settings[option]; if (!value) { // Get cached default map or make it if needed value = mapCache[option]; if (!value) { value = makeMap(default_value, ' ', makeMap(default_value.toUpperCase(), ' ')); value = tinymce.extend(value, extend); mapCache[option] = value; } } else { // Create custom map value = makeMap(value, ',', makeMap(value.toUpperCase(), ' ')); } return value; }; settings = settings || {}; schemaItems = settings.schema == "html5" ? getHTML5() : getHTML4(); // Allow all elements and attributes if verify_html is set to false if (settings.verify_html === false) settings.valid_elements = '*[*]'; // Build styles list if (settings.valid_styles) { validStyles = {}; // Convert styles into a rule list each(settings.valid_styles, function(value, key) { validStyles[key] = tinymce.explode(value); }); } // Setup map objects whiteSpaceElementsMap = createLookupTable('whitespace_elements', 'pre script style textarea'); selfClosingElementsMap = createLookupTable('self_closing_elements', 'colgroup dd dt li options p td tfoot th thead tr'); shortEndedElementsMap = createLookupTable('short_ended_elements', 'area base basefont br col frame hr img input isindex link meta param embed source'); boolAttrMap = createLookupTable('boolean_attributes', 'checked compact declare defer disabled ismap multiple nohref noresize noshade nowrap readonly selected autoplay loop controls'); nonEmptyElementsMap = createLookupTable('non_empty_elements', 'td th iframe video audio object', shortEndedElementsMap); blockElementsMap = createLookupTable('block_elements', 'h1 h2 h3 h4 h5 h6 hr p div address pre form table tbody thead tfoot ' + 'th tr td li ol ul caption blockquote center dl dt dd dir fieldset ' + 'noscript menu isindex samp header footer article section hgroup aside nav figure'); // Converts a wildcard expression string to a regexp for example *a will become /.*a/. function patternToRegExp(str) { return new RegExp('^' + str.replace(/([?+*])/g, '.$1') + '$'); }; // Parses the specified valid_elements string and adds to the current rules // This function is a bit hard to read since it's heavily optimized for speed function addValidElements(valid_elements) { var ei, el, ai, al, yl, matches, element, attr, attrData, elementName, attrName, attrType, attributes, attributesOrder, prefix, outputName, globalAttributes, globalAttributesOrder, transElement, key, childKey, value, elementRuleRegExp = /^([#+\-])?([^\[\/]+)(?:\/([^\[]+))?(?:\[([^\]]+)\])?$/, attrRuleRegExp = /^([!\-])?(\w+::\w+|[^=:<]+)?(?:([=:<])(.*))?$/, hasPatternsRegExp = /[*?+]/; if (valid_elements) { // Split valid elements into an array with rules valid_elements = split(valid_elements); if (elements['@']) { globalAttributes = elements['@'].attributes; globalAttributesOrder = elements['@'].attributesOrder; } // Loop all rules for (ei = 0, el = valid_elements.length; ei < el; ei++) { // Parse element rule matches = elementRuleRegExp.exec(valid_elements[ei]); if (matches) { // Setup local names for matches prefix = matches[1]; elementName = matches[2]; outputName = matches[3]; attrData = matches[4]; // Create new attributes and attributesOrder attributes = {}; attributesOrder = []; // Create the new element element = { attributes : attributes, attributesOrder : attributesOrder }; // Padd empty elements prefix if (prefix === '#') element.paddEmpty = true; // Remove empty elements prefix if (prefix === '-') element.removeEmpty = true; // Copy attributes from global rule into current rule if (globalAttributes) { for (key in globalAttributes) attributes[key] = globalAttributes[key]; attributesOrder.push.apply(attributesOrder, globalAttributesOrder); } // Attributes defined if (attrData) { attrData = split(attrData, '|'); for (ai = 0, al = attrData.length; ai < al; ai++) { matches = attrRuleRegExp.exec(attrData[ai]); if (matches) { attr = {}; attrType = matches[1]; attrName = matches[2].replace(/::/g, ':'); prefix = matches[3]; value = matches[4]; // Required if (attrType === '!') { element.attributesRequired = element.attributesRequired || []; element.attributesRequired.push(attrName); attr.required = true; } // Denied from global if (attrType === '-') { delete attributes[attrName]; attributesOrder.splice(tinymce.inArray(attributesOrder, attrName), 1); continue; } // Default value if (prefix) { // Default value if (prefix === '=') { element.attributesDefault = element.attributesDefault || []; element.attributesDefault.push({name: attrName, value: value}); attr.defaultValue = value; } // Forced value if (prefix === ':') { element.attributesForced = element.attributesForced || []; element.attributesForced.push({name: attrName, value: value}); attr.forcedValue = value; } // Required values if (prefix === '<') attr.validValues = makeMap(value, '?'); } // Check for attribute patterns if (hasPatternsRegExp.test(attrName)) { element.attributePatterns = element.attributePatterns || []; attr.pattern = patternToRegExp(attrName); element.attributePatterns.push(attr); } else { // Add attribute to order list if it doesn't already exist if (!attributes[attrName]) attributesOrder.push(attrName); attributes[attrName] = attr; } } } } // Global rule, store away these for later usage if (!globalAttributes && elementName == '@') { globalAttributes = attributes; globalAttributesOrder = attributesOrder; } // Handle substitute elements such as b/strong if (outputName) { element.outputName = elementName; elements[outputName] = element; } // Add pattern or exact element if (hasPatternsRegExp.test(elementName)) { element.pattern = patternToRegExp(elementName); patternElements.push(element); } else elements[elementName] = element; } } } }; function setValidElements(valid_elements) { elements = {}; patternElements = []; addValidElements(valid_elements); each(schemaItems, function(element, name) { children[name] = element.children; }); }; // Adds custom non HTML elements to the schema function addCustomElements(custom_elements) { var customElementRegExp = /^(~)?(.+)$/; if (custom_elements) { each(split(custom_elements), function(rule) { var matches = customElementRegExp.exec(rule), inline = matches[1] === '~', cloneName = inline ? 'span' : 'div', name = matches[2]; children[name] = children[cloneName]; customElementsMap[name] = cloneName; // If it's not marked as inline then add it to valid block elements if (!inline) blockElementsMap[name] = {}; // Add custom elements at span/div positions each(children, function(element, child) { if (element[cloneName]) element[name] = element[cloneName]; }); }); } }; // Adds valid children to the schema object function addValidChildren(valid_children) { var childRuleRegExp = /^([+\-]?)(\w+)\[([^\]]+)\]$/; if (valid_children) { each(split(valid_children), function(rule) { var matches = childRuleRegExp.exec(rule), parent, prefix; if (matches) { prefix = matches[1]; // Add/remove items from default if (prefix) parent = children[matches[2]]; else parent = children[matches[2]] = {'#comment' : {}}; parent = children[matches[2]]; each(split(matches[3], '|'), function(child) { if (prefix === '-') delete parent[child]; else parent[child] = {}; }); } }); } }; function getElementRule(name) { var element = elements[name], i; // Exact match found if (element) return element; // No exact match then try the patterns i = patternElements.length; while (i--) { element = patternElements[i]; if (element.pattern.test(name)) return element; } }; if (!settings.valid_elements) { // No valid elements defined then clone the elements from the schema spec each(schemaItems, function(element, name) { elements[name] = { attributes : element.attributes, attributesOrder : element.attributesOrder }; children[name] = element.children; }); // Switch these on HTML4 if (settings.schema != "html5") { each(split('strong/b,em/i'), function(item) { item = split(item, '/'); elements[item[1]].outputName = item[0]; }); } // Add default alt attribute for images elements.img.attributesDefault = [{name: 'alt', value: ''}]; // Remove these if they are empty by default each(split('ol,ul,sub,sup,blockquote,span,font,a,table,tbody,tr,strong,em,b,i'), function(name) { if (elements[name]) { elements[name].removeEmpty = true; } }); // Padd these by default each(split('p,h1,h2,h3,h4,h5,h6,th,td,pre,div,address,caption'), function(name) { elements[name].paddEmpty = true; }); } else setValidElements(settings.valid_elements); addCustomElements(settings.custom_elements); addValidChildren(settings.valid_children); addValidElements(settings.extended_valid_elements); // Todo: Remove this when we fix list handling to be valid addValidChildren('+ol[ul|ol],+ul[ul|ol]'); // Delete invalid elements if (settings.invalid_elements) { tinymce.each(tinymce.explode(settings.invalid_elements), function(item) { if (elements[item]) delete elements[item]; }); } // If the user didn't allow span only allow internal spans if (!getElementRule('span')) addValidElements('span[!data-mce-type|*]'); self.children = children; self.styles = validStyles; self.getBoolAttrs = function() { return boolAttrMap; }; self.getBlockElements = function() { return blockElementsMap; }; self.getShortEndedElements = function() { return shortEndedElementsMap; }; self.getSelfClosingElements = function() { return selfClosingElementsMap; }; self.getNonEmptyElements = function() { return nonEmptyElementsMap; }; self.getWhiteSpaceElements = function() { return whiteSpaceElementsMap; }; self.isValidChild = function(name, child) { var parent = children[name]; return !!(parent && parent[child]); }; self.getElementRule = getElementRule; self.getCustomElements = function() { return customElementsMap; }; self.addValidElements = addValidElements; self.setValidElements = setValidElements; self.addCustomElements = addCustomElements; self.addValidChildren = addValidChildren; }; })(tinymce); (function(tinymce) { tinymce.html.SaxParser = function(settings, schema) { var self = this, noop = function() {}; settings = settings || {}; self.schema = schema = schema || new tinymce.html.Schema(); if (settings.fix_self_closing !== false) settings.fix_self_closing = true; // Add handler functions from settings and setup default handlers tinymce.each('comment cdata text start end pi doctype'.split(' '), function(name) { if (name) self[name] = settings[name] || noop; }); self.parse = function(html) { var self = this, matches, index = 0, value, endRegExp, stack = [], attrList, i, text, name, isInternalElement, removeInternalElements, shortEndedElements, fillAttrsMap, isShortEnded, validate, elementRule, isValidElement, attr, attribsValue, invalidPrefixRegExp, validAttributesMap, validAttributePatterns, attributesRequired, attributesDefault, attributesForced, selfClosing, tokenRegExp, attrRegExp, specialElements, attrValue, idCount = 0, decode = tinymce.html.Entities.decode, fixSelfClosing, isIE; function processEndTag(name) { var pos, i; // Find position of parent of the same type pos = stack.length; while (pos--) { if (stack[pos].name === name) break; } // Found parent if (pos >= 0) { // Close all the open elements for (i = stack.length - 1; i >= pos; i--) { name = stack[i]; if (name.valid) self.end(name.name); } // Remove the open elements from the stack stack.length = pos; } }; function parseAttribute(match, name, value, val2, val3) { var attrRule, i; name = name.toLowerCase(); value = name in fillAttrsMap ? name : decode(value || val2 || val3 || ''); // Handle boolean attribute than value attribute // Validate name and value if (validate && !isInternalElement && name.indexOf('data-') !== 0) { attrRule = validAttributesMap[name]; // Find rule by pattern matching if (!attrRule && validAttributePatterns) { i = validAttributePatterns.length; while (i--) { attrRule = validAttributePatterns[i]; if (attrRule.pattern.test(name)) break; } // No rule matched if (i === -1) attrRule = null; } // No attribute rule found if (!attrRule) return; // Validate value if (attrRule.validValues && !(value in attrRule.validValues)) return; } // Add attribute to list and map attrList.map[name] = value; attrList.push({ name: name, value: value }); }; // Precompile RegExps and map objects tokenRegExp = new RegExp('<(?:' + '(?:!--([\\w\\W]*?)-->)|' + // Comment '(?:!\\[CDATA\\[([\\w\\W]*?)\\]\\]>)|' + // CDATA '(?:!DOCTYPE([\\w\\W]*?)>)|' + // DOCTYPE '(?:\\?([^\\s\\/<>]+) ?([\\w\\W]*?)[?/]>)|' + // PI '(?:\\/([^>]+)>)|' + // End element '(?:([A-Za-z0-9\\-\\:]+)((?:\\s+[^"\'>]+(?:(?:"[^"]*")|(?:\'[^\']*\')|[^>]*))*|\\/|\\s+)>)' + // Start element ')', 'g'); attrRegExp = /([\w:\-]+)(?:\s*=\s*(?:(?:\"((?:\\.|[^\"])*)\")|(?:\'((?:\\.|[^\'])*)\')|([^>\s]+)))?/g; specialElements = { 'script' : /<\/script[^>]*>/gi, 'style' : /<\/style[^>]*>/gi, 'noscript' : /<\/noscript[^>]*>/gi }; // Setup lookup tables for empty elements and boolean attributes shortEndedElements = schema.getShortEndedElements(); selfClosing = schema.getSelfClosingElements(); fillAttrsMap = schema.getBoolAttrs(); validate = settings.validate; removeInternalElements = settings.remove_internals; fixSelfClosing = settings.fix_self_closing; isIE = tinymce.isIE; invalidPrefixRegExp = /^:/; while (matches = tokenRegExp.exec(html)) { // Text if (index < matches.index) self.text(decode(html.substr(index, matches.index - index))); if (value = matches[6]) { // End element value = value.toLowerCase(); // IE will add a ":" in front of elements it doesn't understand like custom elements or HTML5 elements if (isIE && invalidPrefixRegExp.test(value)) value = value.substr(1); processEndTag(value); } else if (value = matches[7]) { // Start element value = value.toLowerCase(); // IE will add a ":" in front of elements it doesn't understand like custom elements or HTML5 elements if (isIE && invalidPrefixRegExp.test(value)) value = value.substr(1); isShortEnded = value in shortEndedElements; // Is self closing tag for example an <li> after an open <li> if (fixSelfClosing && selfClosing[value] && stack.length > 0 && stack[stack.length - 1].name === value) processEndTag(value); // Validate element if (!validate || (elementRule = schema.getElementRule(value))) { isValidElement = true; // Grab attributes map and patters when validation is enabled if (validate) { validAttributesMap = elementRule.attributes; validAttributePatterns = elementRule.attributePatterns; } // Parse attributes if (attribsValue = matches[8]) { isInternalElement = attribsValue.indexOf('data-mce-type') !== -1; // Check if the element is an internal element // If the element has internal attributes then remove it if we are told to do so if (isInternalElement && removeInternalElements) isValidElement = false; attrList = []; attrList.map = {}; attribsValue.replace(attrRegExp, parseAttribute); } else { attrList = []; attrList.map = {}; } // Process attributes if validation is enabled if (validate && !isInternalElement) { attributesRequired = elementRule.attributesRequired; attributesDefault = elementRule.attributesDefault; attributesForced = elementRule.attributesForced; // Handle forced attributes if (attributesForced) { i = attributesForced.length; while (i--) { attr = attributesForced[i]; name = attr.name; attrValue = attr.value; if (attrValue === '{$uid}') attrValue = 'mce_' + idCount++; attrList.map[name] = attrValue; attrList.push({name: name, value: attrValue}); } } // Handle default attributes if (attributesDefault) { i = attributesDefault.length; while (i--) { attr = attributesDefault[i]; name = attr.name; if (!(name in attrList.map)) { attrValue = attr.value; if (attrValue === '{$uid}') attrValue = 'mce_' + idCount++; attrList.map[name] = attrValue; attrList.push({name: name, value: attrValue}); } } } // Handle required attributes if (attributesRequired) { i = attributesRequired.length; while (i--) { if (attributesRequired[i] in attrList.map) break; } // None of the required attributes where found if (i === -1) isValidElement = false; } // Invalidate element if it's marked as bogus if (attrList.map['data-mce-bogus']) isValidElement = false; } if (isValidElement) self.start(value, attrList, isShortEnded); } else isValidElement = false; // Treat script, noscript and style a bit different since they may include code that looks like elements if (endRegExp = specialElements[value]) { endRegExp.lastIndex = index = matches.index + matches[0].length; if (matches = endRegExp.exec(html)) { if (isValidElement) text = html.substr(index, matches.index - index); index = matches.index + matches[0].length; } else { text = html.substr(index); index = html.length; } if (isValidElement && text.length > 0) self.text(text, true); if (isValidElement) self.end(value); tokenRegExp.lastIndex = index; continue; } // Push value on to stack if (!isShortEnded) { if (!attribsValue || attribsValue.indexOf('/') != attribsValue.length - 1) stack.push({name: value, valid: isValidElement}); else if (isValidElement) self.end(value); } } else if (value = matches[1]) { // Comment self.comment(value); } else if (value = matches[2]) { // CDATA self.cdata(value); } else if (value = matches[3]) { // DOCTYPE self.doctype(value); } else if (value = matches[4]) { // PI self.pi(value, matches[5]); } index = matches.index + matches[0].length; } // Text if (index < html.length) self.text(decode(html.substr(index))); // Close any open elements for (i = stack.length - 1; i >= 0; i--) { value = stack[i]; if (value.valid) self.end(value.name); } }; } })(tinymce); (function(tinymce) { var whiteSpaceRegExp = /^[ \t\r\n]*$/, typeLookup = { '#text' : 3, '#comment' : 8, '#cdata' : 4, '#pi' : 7, '#doctype' : 10, '#document-fragment' : 11 }; // Walks the tree left/right function walk(node, root_node, prev) { var sibling, parent, startName = prev ? 'lastChild' : 'firstChild', siblingName = prev ? 'prev' : 'next'; // Walk into nodes if it has a start if (node[startName]) return node[startName]; // Return the sibling if it has one if (node !== root_node) { sibling = node[siblingName]; if (sibling) return sibling; // Walk up the parents to look for siblings for (parent = node.parent; parent && parent !== root_node; parent = parent.parent) { sibling = parent[siblingName]; if (sibling) return sibling; } } }; function Node(name, type) { this.name = name; this.type = type; if (type === 1) { this.attributes = []; this.attributes.map = {}; } } tinymce.extend(Node.prototype, { replace : function(node) { var self = this; if (node.parent) node.remove(); self.insert(node, self); self.remove(); return self; }, attr : function(name, value) { var self = this, attrs, i, undef; if (typeof name !== "string") { for (i in name) self.attr(i, name[i]); return self; } if (attrs = self.attributes) { if (value !== undef) { // Remove attribute if (value === null) { if (name in attrs.map) { delete attrs.map[name]; i = attrs.length; while (i--) { if (attrs[i].name === name) { attrs = attrs.splice(i, 1); return self; } } } return self; } // Set attribute if (name in attrs.map) { // Set attribute i = attrs.length; while (i--) { if (attrs[i].name === name) { attrs[i].value = value; break; } } } else attrs.push({name: name, value: value}); attrs.map[name] = value; return self; } else { return attrs.map[name]; } } }, clone : function() { var self = this, clone = new Node(self.name, self.type), i, l, selfAttrs, selfAttr, cloneAttrs; // Clone element attributes if (selfAttrs = self.attributes) { cloneAttrs = []; cloneAttrs.map = {}; for (i = 0, l = selfAttrs.length; i < l; i++) { selfAttr = selfAttrs[i]; // Clone everything except id if (selfAttr.name !== 'id') { cloneAttrs[cloneAttrs.length] = {name: selfAttr.name, value: selfAttr.value}; cloneAttrs.map[selfAttr.name] = selfAttr.value; } } clone.attributes = cloneAttrs; } clone.value = self.value; clone.shortEnded = self.shortEnded; return clone; }, wrap : function(wrapper) { var self = this; self.parent.insert(wrapper, self); wrapper.append(self); return self; }, unwrap : function() { var self = this, node, next; for (node = self.firstChild; node; ) { next = node.next; self.insert(node, self, true); node = next; } self.remove(); }, remove : function() { var self = this, parent = self.parent, next = self.next, prev = self.prev; if (parent) { if (parent.firstChild === self) { parent.firstChild = next; if (next) next.prev = null; } else { prev.next = next; } if (parent.lastChild === self) { parent.lastChild = prev; if (prev) prev.next = null; } else { next.prev = prev; } self.parent = self.next = self.prev = null; } return self; }, append : function(node) { var self = this, last; if (node.parent) node.remove(); last = self.lastChild; if (last) { last.next = node; node.prev = last; self.lastChild = node; } else self.lastChild = self.firstChild = node; node.parent = self; return node; }, insert : function(node, ref_node, before) { var parent; if (node.parent) node.remove(); parent = ref_node.parent || this; if (before) { if (ref_node === parent.firstChild) parent.firstChild = node; else ref_node.prev.next = node; node.prev = ref_node.prev; node.next = ref_node; ref_node.prev = node; } else { if (ref_node === parent.lastChild) parent.lastChild = node; else ref_node.next.prev = node; node.next = ref_node.next; node.prev = ref_node; ref_node.next = node; } node.parent = parent; return node; }, getAll : function(name) { var self = this, node, collection = []; for (node = self.firstChild; node; node = walk(node, self)) { if (node.name === name) collection.push(node); } return collection; }, empty : function() { var self = this, nodes, i, node; // Remove all children if (self.firstChild) { nodes = []; // Collect the children for (node = self.firstChild; node; node = walk(node, self)) nodes.push(node); // Remove the children i = nodes.length; while (i--) { node = nodes[i]; node.parent = node.firstChild = node.lastChild = node.next = node.prev = null; } } self.firstChild = self.lastChild = null; return self; }, isEmpty : function(elements) { var self = this, node = self.firstChild, i, name; if (node) { do { if (node.type === 1) { // Ignore bogus elements if (node.attributes.map['data-mce-bogus']) continue; // Keep empty elements like <img /> if (elements[node.name]) return false; // Keep elements with data attributes or name attribute like <a name="1"></a> i = node.attributes.length; while (i--) { name = node.attributes[i].name; if (name === "name" || name.indexOf('data-') === 0) return false; } } // Keep comments if (node.type === 8) return false; // Keep non whitespace text nodes if ((node.type === 3 && !whiteSpaceRegExp.test(node.value))) return false; } while (node = walk(node, self)); } return true; }, walk : function(prev) { return walk(this, null, prev); } }); tinymce.extend(Node, { create : function(name, attrs) { var node, attrName; // Create node node = new Node(name, typeLookup[name] || 1); // Add attributes if needed if (attrs) { for (attrName in attrs) node.attr(attrName, attrs[attrName]); } return node; } }); tinymce.html.Node = Node; })(tinymce); (function(tinymce) { var Node = tinymce.html.Node; tinymce.html.DomParser = function(settings, schema) { var self = this, nodeFilters = {}, attributeFilters = [], matchedNodes = {}, matchedAttributes = {}; settings = settings || {}; settings.validate = "validate" in settings ? settings.validate : true; settings.root_name = settings.root_name || 'body'; self.schema = schema = schema || new tinymce.html.Schema(); function fixInvalidChildren(nodes) { var ni, node, parent, parents, newParent, currentNode, tempNode, childNode, i, childClone, nonEmptyElements, nonSplitableElements, sibling, nextNode; nonSplitableElements = tinymce.makeMap('tr,td,th,tbody,thead,tfoot,table'); nonEmptyElements = schema.getNonEmptyElements(); for (ni = 0; ni < nodes.length; ni++) { node = nodes[ni]; // Already removed if (!node.parent) continue; // Get list of all parent nodes until we find a valid parent to stick the child into parents = [node]; for (parent = node.parent; parent && !schema.isValidChild(parent.name, node.name) && !nonSplitableElements[parent.name]; parent = parent.parent) parents.push(parent); // Found a suitable parent if (parent && parents.length > 1) { // Reverse the array since it makes looping easier parents.reverse(); // Clone the related parent and insert that after the moved node newParent = currentNode = self.filterNode(parents[0].clone()); // Start cloning and moving children on the left side of the target node for (i = 0; i < parents.length - 1; i++) { if (schema.isValidChild(currentNode.name, parents[i].name)) { tempNode = self.filterNode(parents[i].clone()); currentNode.append(tempNode); } else tempNode = currentNode; for (childNode = parents[i].firstChild; childNode && childNode != parents[i + 1]; ) { nextNode = childNode.next; tempNode.append(childNode); childNode = nextNode; } currentNode = tempNode; } if (!newParent.isEmpty(nonEmptyElements)) { parent.insert(newParent, parents[0], true); parent.insert(node, newParent); } else { parent.insert(node, parents[0], true); } // Check if the element is empty by looking through it's contents and special treatment for <p><br /></p> parent = parents[0]; if (parent.isEmpty(nonEmptyElements) || parent.firstChild === parent.lastChild && parent.firstChild.name === 'br') { parent.empty().remove(); } } else if (node.parent) { // If it's an LI try to find a UL/OL for it or wrap it if (node.name === 'li') { sibling = node.prev; if (sibling && (sibling.name === 'ul' || sibling.name === 'ul')) { sibling.append(node); continue; } sibling = node.next; if (sibling && (sibling.name === 'ul' || sibling.name === 'ul')) { sibling.insert(node, sibling.firstChild, true); continue; } node.wrap(self.filterNode(new Node('ul', 1))); continue; } // Try wrapping the element in a DIV if (schema.isValidChild(node.parent.name, 'div') && schema.isValidChild('div', node.name)) { node.wrap(self.filterNode(new Node('div', 1))); } else { // We failed wrapping it, then remove or unwrap it if (node.name === 'style' || node.name === 'script') node.empty().remove(); else node.unwrap(); } } } }; self.filterNode = function(node) { var i, name, list; // Run element filters if (name in nodeFilters) { list = matchedNodes[name]; if (list) list.push(node); else matchedNodes[name] = [node]; } // Run attribute filters i = attributeFilters.length; while (i--) { name = attributeFilters[i].name; if (name in node.attributes.map) { list = matchedAttributes[name]; if (list) list.push(node); else matchedAttributes[name] = [node]; } } return node; }; self.addNodeFilter = function(name, callback) { tinymce.each(tinymce.explode(name), function(name) { var list = nodeFilters[name]; if (!list) nodeFilters[name] = list = []; list.push(callback); }); }; self.addAttributeFilter = function(name, callback) { tinymce.each(tinymce.explode(name), function(name) { var i; for (i = 0; i < attributeFilters.length; i++) { if (attributeFilters[i].name === name) { attributeFilters[i].callbacks.push(callback); return; } } attributeFilters.push({name: name, callbacks: [callback]}); }); }; self.parse = function(html, args) { var parser, rootNode, node, nodes, i, l, fi, fl, list, name, validate, blockElements, startWhiteSpaceRegExp, invalidChildren = [], isInWhiteSpacePreservedElement, endWhiteSpaceRegExp, allWhiteSpaceRegExp, whiteSpaceElements, children, nonEmptyElements, rootBlockName; args = args || {}; matchedNodes = {}; matchedAttributes = {}; blockElements = tinymce.extend(tinymce.makeMap('script,style,head,html,body,title,meta,param'), schema.getBlockElements()); nonEmptyElements = schema.getNonEmptyElements(); children = schema.children; validate = settings.validate; rootBlockName = "forced_root_block" in args ? args.forced_root_block : settings.forced_root_block; whiteSpaceElements = schema.getWhiteSpaceElements(); startWhiteSpaceRegExp = /^[ \t\r\n]+/; endWhiteSpaceRegExp = /[ \t\r\n]+$/; allWhiteSpaceRegExp = /[ \t\r\n]+/g; function addRootBlocks() { var node = rootNode.firstChild, next, rootBlockNode; while (node) { next = node.next; if (node.type == 3 || (node.type == 1 && node.name !== 'p' && !blockElements[node.name] && !node.attr('data-mce-type'))) { if (!rootBlockNode) { // Create a new root block element rootBlockNode = createNode(rootBlockName, 1); rootNode.insert(rootBlockNode, node); rootBlockNode.append(node); } else rootBlockNode.append(node); } else { rootBlockNode = null; } node = next; }; }; function createNode(name, type) { var node = new Node(name, type), list; if (name in nodeFilters) { list = matchedNodes[name]; if (list) list.push(node); else matchedNodes[name] = [node]; } return node; }; function removeWhitespaceBefore(node) { var textNode, textVal, sibling; for (textNode = node.prev; textNode && textNode.type === 3; ) { textVal = textNode.value.replace(endWhiteSpaceRegExp, ''); if (textVal.length > 0) { textNode.value = textVal; textNode = textNode.prev; } else { sibling = textNode.prev; textNode.remove(); textNode = sibling; } } }; parser = new tinymce.html.SaxParser({ validate : validate, fix_self_closing : !validate, // Let the DOM parser handle <li> in <li> or <p> in <p> for better results cdata: function(text) { node.append(createNode('#cdata', 4)).value = text; }, text: function(text, raw) { var textNode; // Trim all redundant whitespace on non white space elements if (!isInWhiteSpacePreservedElement) { text = text.replace(allWhiteSpaceRegExp, ' '); if (node.lastChild && blockElements[node.lastChild.name]) text = text.replace(startWhiteSpaceRegExp, ''); } // Do we need to create the node if (text.length !== 0) { textNode = createNode('#text', 3); textNode.raw = !!raw; node.append(textNode).value = text; } }, comment: function(text) { node.append(createNode('#comment', 8)).value = text; }, pi: function(name, text) { node.append(createNode(name, 7)).value = text; removeWhitespaceBefore(node); }, doctype: function(text) { var newNode; newNode = node.append(createNode('#doctype', 10)); newNode.value = text; removeWhitespaceBefore(node); }, start: function(name, attrs, empty) { var newNode, attrFiltersLen, elementRule, textNode, attrName, text, sibling, parent; elementRule = validate ? schema.getElementRule(name) : {}; if (elementRule) { newNode = createNode(elementRule.outputName || name, 1); newNode.attributes = attrs; newNode.shortEnded = empty; node.append(newNode); // Check if node is valid child of the parent node is the child is // unknown we don't collect it since it's probably a custom element parent = children[node.name]; if (parent && children[newNode.name] && !parent[newNode.name]) invalidChildren.push(newNode); attrFiltersLen = attributeFilters.length; while (attrFiltersLen--) { attrName = attributeFilters[attrFiltersLen].name; if (attrName in attrs.map) { list = matchedAttributes[attrName]; if (list) list.push(newNode); else matchedAttributes[attrName] = [newNode]; } } // Trim whitespace before block if (blockElements[name]) removeWhitespaceBefore(newNode); // Change current node if the element wasn't empty i.e not <br /> or <img /> if (!empty) node = newNode; // Check if we are inside a whitespace preserved element if (!isInWhiteSpacePreservedElement && whiteSpaceElements[name]) { isInWhiteSpacePreservedElement = true; } } }, end: function(name) { var textNode, elementRule, text, sibling, tempNode; elementRule = validate ? schema.getElementRule(name) : {}; if (elementRule) { if (blockElements[name]) { if (!isInWhiteSpacePreservedElement) { // Trim whitespace at beginning of block for (textNode = node.firstChild; textNode && textNode.type === 3; ) { text = textNode.value.replace(startWhiteSpaceRegExp, ''); if (text.length > 0) { textNode.value = text; textNode = textNode.next; } else { sibling = textNode.next; textNode.remove(); textNode = sibling; } } // Trim whitespace at end of block for (textNode = node.lastChild; textNode && textNode.type === 3; ) { text = textNode.value.replace(endWhiteSpaceRegExp, ''); if (text.length > 0) { textNode.value = text; textNode = textNode.prev; } else { sibling = textNode.prev; textNode.remove(); textNode = sibling; } } } // Trim start white space textNode = node.prev; if (textNode && textNode.type === 3) { text = textNode.value.replace(startWhiteSpaceRegExp, ''); if (text.length > 0) textNode.value = text; else textNode.remove(); } } // Check if we exited a whitespace preserved element if (isInWhiteSpacePreservedElement && whiteSpaceElements[name]) { isInWhiteSpacePreservedElement = false; } // Handle empty nodes if (elementRule.removeEmpty || elementRule.paddEmpty) { if (node.isEmpty(nonEmptyElements)) { if (elementRule.paddEmpty) node.empty().append(new Node('#text', '3')).value = '\u00a0'; else { // Leave nodes that have a name like <a name="name"> if (!node.attributes.map.name) { tempNode = node.parent; node.empty().remove(); node = tempNode; return; } } } } node = node.parent; } } }, schema); rootNode = node = new Node(args.context || settings.root_name, 11); parser.parse(html); // Fix invalid children or report invalid children in a contextual parsing if (validate && invalidChildren.length) { if (!args.context) fixInvalidChildren(invalidChildren); else args.invalid = true; } // Wrap nodes in the root into block elements if the root is body if (rootBlockName && rootNode.name == 'body') addRootBlocks(); // Run filters only when the contents is valid if (!args.invalid) { // Run node filters for (name in matchedNodes) { list = nodeFilters[name]; nodes = matchedNodes[name]; // Remove already removed children fi = nodes.length; while (fi--) { if (!nodes[fi].parent) nodes.splice(fi, 1); } for (i = 0, l = list.length; i < l; i++) list[i](nodes, name, args); } // Run attribute filters for (i = 0, l = attributeFilters.length; i < l; i++) { list = attributeFilters[i]; if (list.name in matchedAttributes) { nodes = matchedAttributes[list.name]; // Remove already removed children fi = nodes.length; while (fi--) { if (!nodes[fi].parent) nodes.splice(fi, 1); } for (fi = 0, fl = list.callbacks.length; fi < fl; fi++) list.callbacks[fi](nodes, list.name, args); } } } return rootNode; }; // Remove <br> at end of block elements Gecko and WebKit injects BR elements to // make it possible to place the caret inside empty blocks. This logic tries to remove // these elements and keep br elements that where intended to be there intact if (settings.remove_trailing_brs) { self.addNodeFilter('br', function(nodes, name) { var i, l = nodes.length, node, blockElements = tinymce.extend({}, schema.getBlockElements()), nonEmptyElements = schema.getNonEmptyElements(), parent, lastParent, prev, prevName; // Remove brs from body element as well blockElements.body = 1; // Must loop forwards since it will otherwise remove all brs in <p>a<br><br><br></p> for (i = 0; i < l; i++) { node = nodes[i]; parent = node.parent; if (blockElements[node.parent.name] && node === parent.lastChild) { // Loop all nodes to the left of the current node and check for other BR elements // excluding bookmarks since they are invisible prev = node.prev; while (prev) { prevName = prev.name; // Ignore bookmarks if (prevName !== "span" || prev.attr('data-mce-type') !== 'bookmark') { // Found a non BR element if (prevName !== "br") break; // Found another br it's a <br><br> structure then don't remove anything if (prevName === 'br') { node = null; break; } } prev = prev.prev; } if (node) { node.remove(); // Is the parent to be considered empty after we removed the BR if (parent.isEmpty(nonEmptyElements)) { elementRule = schema.getElementRule(parent.name); // Remove or padd the element depending on schema rule if (elementRule) { if (elementRule.removeEmpty) parent.remove(); else if (elementRule.paddEmpty) parent.empty().append(new tinymce.html.Node('#text', 3)).value = '\u00a0'; } } } } else { // Replaces BR elements inside inline elements like <p><b><i><br></i></b></p> so they become <p><b><i>&nbsp;</i></b></p> lastParent = node; while (parent.firstChild === lastParent && parent.lastChild === lastParent) { lastParent = parent; if (blockElements[parent.name]) { break; } parent = parent.parent; } if (lastParent === parent) { textNode = new tinymce.html.Node('#text', 3); textNode.value = '\u00a0'; node.replace(textNode); } } } }); } // Force anchor names closed, unless the setting "allow_html_in_named_anchor" is explicitly included. if (!settings.allow_html_in_named_anchor) { self.addAttributeFilter('name', function(nodes, name) { var i = nodes.length, sibling, prevSibling, parent, node; while (i--) { node = nodes[i]; if (node.name === 'a' && node.firstChild) { parent = node.parent; // Move children after current node sibling = node.lastChild; do { prevSibling = sibling.prev; parent.insert(sibling, node); sibling = prevSibling; } while (sibling); } } }); } } })(tinymce); tinymce.html.Writer = function(settings) { var html = [], indent, indentBefore, indentAfter, encode, htmlOutput; settings = settings || {}; indent = settings.indent; indentBefore = tinymce.makeMap(settings.indent_before || ''); indentAfter = tinymce.makeMap(settings.indent_after || ''); encode = tinymce.html.Entities.getEncodeFunc(settings.entity_encoding || 'raw', settings.entities); htmlOutput = settings.element_format == "html"; return { start: function(name, attrs, empty) { var i, l, attr, value; if (indent && indentBefore[name] && html.length > 0) { value = html[html.length - 1]; if (value.length > 0 && value !== '\n') html.push('\n'); } html.push('<', name); if (attrs) { for (i = 0, l = attrs.length; i < l; i++) { attr = attrs[i]; html.push(' ', attr.name, '="', encode(attr.value, true), '"'); } } if (!empty || htmlOutput) html[html.length] = '>'; else html[html.length] = ' />'; if (empty && indent && indentAfter[name] && html.length > 0) { value = html[html.length - 1]; if (value.length > 0 && value !== '\n') html.push('\n'); } }, end: function(name) { var value; /*if (indent && indentBefore[name] && html.length > 0) { value = html[html.length - 1]; if (value.length > 0 && value !== '\n') html.push('\n'); }*/ html.push('</', name, '>'); if (indent && indentAfter[name] && html.length > 0) { value = html[html.length - 1]; if (value.length > 0 && value !== '\n') html.push('\n'); } }, text: function(text, raw) { if (text.length > 0) html[html.length] = raw ? text : encode(text); }, cdata: function(text) { html.push('<![CDATA[', text, ']]>'); }, comment: function(text) { html.push('<!--', text, '-->'); }, pi: function(name, text) { if (text) html.push('<?', name, ' ', text, '?>'); else html.push('<?', name, '?>'); if (indent) html.push('\n'); }, doctype: function(text) { html.push('<!DOCTYPE', text, '>', indent ? '\n' : ''); }, reset: function() { html.length = 0; }, getContent: function() { return html.join('').replace(/\n$/, ''); } }; }; (function(tinymce) { tinymce.html.Serializer = function(settings, schema) { var self = this, writer = new tinymce.html.Writer(settings); settings = settings || {}; settings.validate = "validate" in settings ? settings.validate : true; self.schema = schema = schema || new tinymce.html.Schema(); self.writer = writer; self.serialize = function(node) { var handlers, validate; validate = settings.validate; handlers = { // #text 3: function(node, raw) { writer.text(node.value, node.raw); }, // #comment 8: function(node) { writer.comment(node.value); }, // Processing instruction 7: function(node) { writer.pi(node.name, node.value); }, // Doctype 10: function(node) { writer.doctype(node.value); }, // CDATA 4: function(node) { writer.cdata(node.value); }, // Document fragment 11: function(node) { if ((node = node.firstChild)) { do { walk(node); } while (node = node.next); } } }; writer.reset(); function walk(node) { var handler = handlers[node.type], name, isEmpty, attrs, attrName, attrValue, sortedAttrs, i, l, elementRule; if (!handler) { name = node.name; isEmpty = node.shortEnded; attrs = node.attributes; // Sort attributes if (validate && attrs && attrs.length > 1) { sortedAttrs = []; sortedAttrs.map = {}; elementRule = schema.getElementRule(node.name); for (i = 0, l = elementRule.attributesOrder.length; i < l; i++) { attrName = elementRule.attributesOrder[i]; if (attrName in attrs.map) { attrValue = attrs.map[attrName]; sortedAttrs.map[attrName] = attrValue; sortedAttrs.push({name: attrName, value: attrValue}); } } for (i = 0, l = attrs.length; i < l; i++) { attrName = attrs[i].name; if (!(attrName in sortedAttrs.map)) { attrValue = attrs.map[attrName]; sortedAttrs.map[attrName] = attrValue; sortedAttrs.push({name: attrName, value: attrValue}); } } attrs = sortedAttrs; } writer.start(node.name, attrs, isEmpty); if (!isEmpty) { if ((node = node.firstChild)) { do { walk(node); } while (node = node.next); } writer.end(name); } } else handler(node); } // Serialize element and treat all non elements as fragments if (node.type == 1 && !settings.inner) walk(node); else handlers[11](node); return writer.getContent(); }; } })(tinymce); // JSLint defined globals /*global tinymce:false, window:false */ tinymce.dom = {}; (function(namespace, expando) { var w3cEventModel = !!document.addEventListener; function addEvent(target, name, callback, capture) { if (target.addEventListener) { target.addEventListener(name, callback, capture || false); } else if (target.attachEvent) { target.attachEvent('on' + name, callback); } } function removeEvent(target, name, callback, capture) { if (target.removeEventListener) { target.removeEventListener(name, callback, capture || false); } else if (target.detachEvent) { target.detachEvent('on' + name, callback); } } function fix(original_event, data) { var name, event = data || {}; // Dummy function that gets replaced on the delegation state functions function returnFalse() { return false; } // Dummy function that gets replaced on the delegation state functions function returnTrue() { return true; } // Copy all properties from the original event for (name in original_event) { // layerX/layerY is deprecated in Chrome and produces a warning if (name !== "layerX" && name !== "layerY") { event[name] = original_event[name]; } } // Normalize target IE uses srcElement if (!event.target) { event.target = event.srcElement || document; } // Add preventDefault method event.preventDefault = function() { event.isDefaultPrevented = returnTrue; // Execute preventDefault on the original event object if (original_event) { if (original_event.preventDefault) { original_event.preventDefault(); } else { original_event.returnValue = false; // IE } } }; // Add stopPropagation event.stopPropagation = function() { event.isPropagationStopped = returnTrue; // Execute stopPropagation on the original event object if (original_event) { if (original_event.stopPropagation) { original_event.stopPropagation(); } else { original_event.cancelBubble = true; // IE } } }; // Add stopImmediatePropagation event.stopImmediatePropagation = function() { event.isImmediatePropagationStopped = returnTrue; event.stopPropagation(); }; // Add event delegation states if (!event.isDefaultPrevented) { event.isDefaultPrevented = returnFalse; event.isPropagationStopped = returnFalse; event.isImmediatePropagationStopped = returnFalse; } return event; } function bindOnReady(win, callback, event_utils) { var doc = win.document, event = {type: 'ready'}; // Gets called when the DOM is ready function readyHandler() { if (!event_utils.domLoaded) { event_utils.domLoaded = true; callback(event); } } // Use W3C method if (w3cEventModel) { addEvent(win, 'DOMContentLoaded', readyHandler); } else { // Use IE method addEvent(doc, "readystatechange", function() { if (doc.readyState === "complete") { removeEvent(doc, "readystatechange", arguments.callee); readyHandler(); } }); // Wait until we can scroll, when we can the DOM is initialized if (doc.documentElement.doScroll && win === win.top) { (function() { try { // If IE is used, use the trick by Diego Perini licensed under MIT by request to the author. // http://javascript.nwbox.com/IEContentLoaded/ doc.documentElement.doScroll("left"); } catch (ex) { setTimeout(arguments.callee, 0); return; } readyHandler(); })(); } } // Fallback if any of the above methods should fail for some odd reason addEvent(win, 'load', readyHandler); } function EventUtils(proxy) { var self = this, events = {}, count, isFocusBlurBound, hasFocusIn, hasMouseEnterLeave, mouseEnterLeave; hasMouseEnterLeave = "onmouseenter" in document.documentElement; hasFocusIn = "onfocusin" in document.documentElement; mouseEnterLeave = {mouseenter: 'mouseover', mouseleave: 'mouseout'}; count = 1; // State if the DOMContentLoaded was executed or not self.domLoaded = false; self.events = events; function executeHandlers(evt, id) { var callbackList, i, l, callback; callbackList = events[id][evt.type]; if (callbackList) { for (i = 0, l = callbackList.length; i < l; i++) { callback = callbackList[i]; // Check if callback exists might be removed if a unbind is called inside the callback if (callback && callback.func.call(callback.scope, evt) === false) { evt.preventDefault(); } // Should we stop propagation to immediate listeners if (evt.isImmediatePropagationStopped()) { return; } } } } self.bind = function(target, names, callback, scope) { var id, callbackList, i, name, fakeName, nativeHandler, capture, win = window; // Native event handler function patches the event and executes the callbacks for the expando function defaultNativeHandler(evt) { executeHandlers(fix(evt || win.event), id); } // Don't bind to text nodes or comments if (!target || target.nodeType === 3 || target.nodeType === 8) { return; } // Create or get events id for the target if (!target[expando]) { id = count++; target[expando] = id; events[id] = {}; } else { id = target[expando]; if (!events[id]) { events[id] = {}; } } // Setup the specified scope or use the target as a default scope = scope || target; // Split names and bind each event, enables you to bind multiple events with one call names = names.split(' '); i = names.length; while (i--) { name = names[i]; nativeHandler = defaultNativeHandler; fakeName = capture = false; // Use ready instead of DOMContentLoaded if (name === "DOMContentLoaded") { name = "ready"; } // DOM is already ready if ((self.domLoaded || target.readyState == 'complete') && name === "ready") { self.domLoaded = true; callback.call(scope, fix({type: name})); continue; } // Handle mouseenter/mouseleaver if (!hasMouseEnterLeave) { fakeName = mouseEnterLeave[name]; if (fakeName) { nativeHandler = function(evt) { var current, related; current = evt.currentTarget; related = evt.relatedTarget; // Check if related is inside the current target if it's not then the event should be ignored since it's a mouseover/mouseout inside the element if (related && current.contains) { // Use contains for performance related = current.contains(related); } else { while (related && related !== current) { related = related.parentNode; } } // Fire fake event if (!related) { evt = fix(evt || win.event); evt.type = evt.type === 'mouseout' ? 'mouseleave' : 'mouseenter'; evt.target = current; executeHandlers(evt, id); } }; } } // Fake bubbeling of focusin/focusout if (!hasFocusIn && (name === "focusin" || name === "focusout")) { capture = true; fakeName = name === "focusin" ? "focus" : "blur"; nativeHandler = function(evt) { evt = fix(evt || win.event); evt.type = evt.type === 'focus' ? 'focusin' : 'focusout'; executeHandlers(evt, id); }; } // Setup callback list and bind native event callbackList = events[id][name]; if (!callbackList) { events[id][name] = callbackList = [{func: callback, scope: scope}]; callbackList.fakeName = fakeName; callbackList.capture = capture; // Add the nativeHandler to the callback list so that we can later unbind it callbackList.nativeHandler = nativeHandler; if (!w3cEventModel) { callbackList.proxyHandler = proxy(id); } // Check if the target has native events support if (name === "ready") { bindOnReady(target, nativeHandler, self); } else { addEvent(target, fakeName || name, w3cEventModel ? nativeHandler : callbackList.proxyHandler, capture); } } else { // If it already has an native handler then just push the callback callbackList.push({func: callback, scope: scope}); } } target = callbackList = 0; // Clean memory for IE return callback; }; self.unbind = function(target, names, callback) { var id, callbackList, i, ci, name, eventMap; // Don't bind to text nodes or comments if (!target || target.nodeType === 3 || target.nodeType === 8) { return self; } // Unbind event or events if the target has the expando id = target[expando]; if (id) { eventMap = events[id]; // Specific callback if (names) { names = names.split(' '); i = names.length; while (i--) { name = names[i]; callbackList = eventMap[name]; // Unbind the event if it exists in the map if (callbackList) { // Remove specified callback if (callback) { ci = callbackList.length; while (ci--) { if (callbackList[ci].func === callback) { callbackList.splice(ci, 1); } } } // Remove all callbacks if there isn't a specified callback or there is no callbacks left if (!callback || callbackList.length === 0) { delete eventMap[name]; removeEvent(target, callbackList.fakeName || name, w3cEventModel ? callbackList.nativeHandler : callbackList.proxyHandler, callbackList.capture); } } } } else { // All events for a specific element for (name in eventMap) { callbackList = eventMap[name]; removeEvent(target, callbackList.fakeName || name, w3cEventModel ? callbackList.nativeHandler : callbackList.proxyHandler, callbackList.capture); } eventMap = {}; } // Check if object is empty, if it isn't then we won't remove the expando map for (name in eventMap) { return self; } // Delete event object delete events[id]; // Remove expando from target try { // IE will fail here since it can't delete properties from window delete target[expando]; } catch (ex) { // IE will set it to null target[expando] = null; } } return self; }; self.fire = function(target, name, args) { var id, event; // Don't bind to text nodes or comments if (!target || target.nodeType === 3 || target.nodeType === 8) { return self; } // Build event object by patching the args event = fix(null, args); event.type = name; do { // Found an expando that means there is listeners to execute id = target[expando]; if (id) { executeHandlers(event, id); } // Walk up the DOM target = target.parentNode || target.ownerDocument || target.defaultView || target.parentWindow; } while (target && !event.isPropagationStopped()); return self; }; self.clean = function(target) { var i, children, unbind = self.unbind; // Don't bind to text nodes or comments if (!target || target.nodeType === 3 || target.nodeType === 8) { return self; } // Unbind any element on the specificed target if (target[expando]) { unbind(target); } // Target doesn't have getElementsByTagName it's probably a window object then use it's document to find the children if (!target.getElementsByTagName) { target = target.document; } // Remove events from each child element if (target && target.getElementsByTagName) { unbind(target); children = target.getElementsByTagName('*'); i = children.length; while (i--) { target = children[i]; if (target[expando]) { unbind(target); } } } return self; }; self.callNativeHandler = function(id, evt) { if (events) { events[id][evt.type].nativeHandler(evt); } }; self.destory = function() { events = {}; }; // Legacy function calls self.add = function(target, events, func, scope) { // Old API supported direct ID assignment if (typeof(target) === "string") { target = document.getElementById(target); } // Old API supported multiple targets if (target && target instanceof Array) { var i = target; while (i--) { self.add(target[i], events, func, scope); } return; } // Old API called ready init if (events === "init") { events = "ready"; } return self.bind(target, events instanceof Array ? events.join(' ') : events, func, scope); }; self.remove = function(target, events, func) { // Old API supported direct ID assignment if (typeof(target) === "string") { target = document.getElementById(target); } // Old API supported multiple targets if (target instanceof Array) { var i = target; while (i--) { self.remove(target[i], events, func, scope); } return self; } return self.unbind(target, events instanceof Array ? events.join(' ') : events, func); }; self.clear = function(target) { // Old API supported direct ID assignment if (typeof(target) === "string") { target = document.getElementById(target); } return self.clean(target); }; self.cancel = function(e) { if (e) { self.prevent(e); self.stop(e); } return false; }; self.prevent = function(e) { e.preventDefault(); return false; }; self.stop = function(e) { e.stopPropagation(); return false; }; } namespace.EventUtils = EventUtils; namespace.Event = new EventUtils(function(id) { return function(evt) { tinymce.dom.Event.callNativeHandler(id, evt); }; }); // Bind ready event when tinymce script is loaded namespace.Event.bind(window, 'ready', function() {}); namespace = 0; })(tinymce.dom, 'data-mce-expando'); // Namespace and expando tinymce.dom.TreeWalker = function(start_node, root_node) { var node = start_node; function findSibling(node, start_name, sibling_name, shallow) { var sibling, parent; if (node) { // Walk into nodes if it has a start if (!shallow && node[start_name]) return node[start_name]; // Return the sibling if it has one if (node != root_node) { sibling = node[sibling_name]; if (sibling) return sibling; // Walk up the parents to look for siblings for (parent = node.parentNode; parent && parent != root_node; parent = parent.parentNode) { sibling = parent[sibling_name]; if (sibling) return sibling; } } } }; this.current = function() { return node; }; this.next = function(shallow) { return (node = findSibling(node, 'firstChild', 'nextSibling', shallow)); }; this.prev = function(shallow) { return (node = findSibling(node, 'lastChild', 'previousSibling', shallow)); }; }; (function(tinymce) { // Shorten names var each = tinymce.each, is = tinymce.is, isWebKit = tinymce.isWebKit, isIE = tinymce.isIE, Entities = tinymce.html.Entities, simpleSelectorRe = /^([a-z0-9],?)+$/i, whiteSpaceRegExp = /^[ \t\r\n]*$/; tinymce.create('tinymce.dom.DOMUtils', { doc : null, root : null, files : null, pixelStyles : /^(top|left|bottom|right|width|height|borderWidth)$/, props : { "for" : "htmlFor", "class" : "className", className : "className", checked : "checked", disabled : "disabled", maxlength : "maxLength", readonly : "readOnly", selected : "selected", value : "value", id : "id", name : "name", type : "type" }, DOMUtils : function(d, s) { var t = this, globalStyle, name, blockElementsMap; t.doc = d; t.win = window; t.files = {}; t.cssFlicker = false; t.counter = 0; t.stdMode = !tinymce.isIE || d.documentMode >= 8; t.boxModel = !tinymce.isIE || d.compatMode == "CSS1Compat" || t.stdMode; t.hasOuterHTML = "outerHTML" in d.createElement("a"); t.settings = s = tinymce.extend({ keep_values : false, hex_colors : 1 }, s); t.schema = s.schema; t.styles = new tinymce.html.Styles({ url_converter : s.url_converter, url_converter_scope : s.url_converter_scope }, s.schema); // Fix IE6SP2 flicker and check it failed for pre SP2 if (tinymce.isIE6) { try { d.execCommand('BackgroundImageCache', false, true); } catch (e) { t.cssFlicker = true; } } t.fixDoc(d); t.events = s.ownEvents ? new tinymce.dom.EventUtils(s.proxy) : tinymce.dom.Event; tinymce.addUnload(t.destroy, t); blockElementsMap = s.schema ? s.schema.getBlockElements() : {}; t.isBlock = function(node) { // This function is called in module pattern style since it might be executed with the wrong this scope var type = node.nodeType; // If it's a node then check the type and use the nodeName if (type) return !!(type === 1 && blockElementsMap[node.nodeName]); return !!blockElementsMap[node]; }; }, fixDoc: function(doc) { var settings = this.settings, name; if (isIE && settings.schema) { // Add missing HTML 4/5 elements to IE ('abbr article aside audio canvas ' + 'details figcaption figure footer ' + 'header hgroup mark menu meter nav ' + 'output progress section summary ' + 'time video').replace(/\w+/g, function(name) { doc.createElement(name); }); // Create all custom elements for (name in settings.schema.getCustomElements()) { doc.createElement(name); } } }, clone: function(node, deep) { var self = this, clone, doc; // TODO: Add feature detection here in the future if (!isIE || node.nodeType !== 1 || deep) { return node.cloneNode(deep); } doc = self.doc; // Make a HTML5 safe shallow copy if (!deep) { clone = doc.createElement(node.nodeName); // Copy attribs each(self.getAttribs(node), function(attr) { self.setAttrib(clone, attr.nodeName, self.getAttrib(node, attr.nodeName)); }); return clone; } /* // Setup HTML5 patched document fragment if (!self.frag) { self.frag = doc.createDocumentFragment(); self.fixDoc(self.frag); } // Make a deep copy by adding it to the document fragment then removing it this removed the :section clone = doc.createElement('div'); self.frag.appendChild(clone); clone.innerHTML = node.outerHTML; self.frag.removeChild(clone); */ return clone.firstChild; }, getRoot : function() { var t = this, s = t.settings; return (s && t.get(s.root_element)) || t.doc.body; }, getViewPort : function(w) { var d, b; w = !w ? this.win : w; d = w.document; b = this.boxModel ? d.documentElement : d.body; // Returns viewport size excluding scrollbars return { x : w.pageXOffset || b.scrollLeft, y : w.pageYOffset || b.scrollTop, w : w.innerWidth || b.clientWidth, h : w.innerHeight || b.clientHeight }; }, getRect : function(e) { var p, t = this, sr; e = t.get(e); p = t.getPos(e); sr = t.getSize(e); return { x : p.x, y : p.y, w : sr.w, h : sr.h }; }, getSize : function(e) { var t = this, w, h; e = t.get(e); w = t.getStyle(e, 'width'); h = t.getStyle(e, 'height'); // Non pixel value, then force offset/clientWidth if (w.indexOf('px') === -1) w = 0; // Non pixel value, then force offset/clientWidth if (h.indexOf('px') === -1) h = 0; return { w : parseInt(w, 10) || e.offsetWidth || e.clientWidth, h : parseInt(h, 10) || e.offsetHeight || e.clientHeight }; }, getParent : function(n, f, r) { return this.getParents(n, f, r, false); }, getParents : function(n, f, r, c) { var t = this, na, se = t.settings, o = []; n = t.get(n); c = c === undefined; if (se.strict_root) r = r || t.getRoot(); // Wrap node name as func if (is(f, 'string')) { na = f; if (f === '*') { f = function(n) {return n.nodeType == 1;}; } else { f = function(n) { return t.is(n, na); }; } } while (n) { if (n == r || !n.nodeType || n.nodeType === 9) break; if (!f || f(n)) { if (c) o.push(n); else return n; } n = n.parentNode; } return c ? o : null; }, get : function(e) { var n; if (e && this.doc && typeof(e) == 'string') { n = e; e = this.doc.getElementById(e); // IE and Opera returns meta elements when they match the specified input ID, but getElementsByName seems to do the trick if (e && e.id !== n) return this.doc.getElementsByName(n)[1]; } return e; }, getNext : function(node, selector) { return this._findSib(node, selector, 'nextSibling'); }, getPrev : function(node, selector) { return this._findSib(node, selector, 'previousSibling'); }, select : function(pa, s) { var t = this; return tinymce.dom.Sizzle(pa, t.get(s) || t.get(t.settings.root_element) || t.doc, []); }, is : function(n, selector) { var i; // If it isn't an array then try to do some simple selectors instead of Sizzle for to boost performance if (n.length === undefined) { // Simple all selector if (selector === '*') return n.nodeType == 1; // Simple selector just elements if (simpleSelectorRe.test(selector)) { selector = selector.toLowerCase().split(/,/); n = n.nodeName.toLowerCase(); for (i = selector.length - 1; i >= 0; i--) { if (selector[i] == n) return true; } return false; } } return tinymce.dom.Sizzle.matches(selector, n.nodeType ? [n] : n).length > 0; }, add : function(p, n, a, h, c) { var t = this; return this.run(p, function(p) { var e, k; e = is(n, 'string') ? t.doc.createElement(n) : n; t.setAttribs(e, a); if (h) { if (h.nodeType) e.appendChild(h); else t.setHTML(e, h); } return !c ? p.appendChild(e) : e; }); }, create : function(n, a, h) { return this.add(this.doc.createElement(n), n, a, h, 1); }, createHTML : function(n, a, h) { var o = '', t = this, k; o += '<' + n; for (k in a) { if (a.hasOwnProperty(k)) o += ' ' + k + '="' + t.encode(a[k]) + '"'; } // A call to tinymce.is doesn't work for some odd reason on IE9 possible bug inside their JS runtime if (typeof(h) != "undefined") return o + '>' + h + '</' + n + '>'; return o + ' />'; }, remove : function(node, keep_children) { return this.run(node, function(node) { var child, parent = node.parentNode; if (!parent) return null; if (keep_children) { while (child = node.firstChild) { // IE 8 will crash if you don't remove completely empty text nodes if (!tinymce.isIE || child.nodeType !== 3 || child.nodeValue) parent.insertBefore(child, node); else node.removeChild(child); } } return parent.removeChild(node); }); }, setStyle : function(n, na, v) { var t = this; return t.run(n, function(e) { var s, i; s = e.style; // Camelcase it, if needed na = na.replace(/-(\D)/g, function(a, b){ return b.toUpperCase(); }); // Default px suffix on these if (t.pixelStyles.test(na) && (tinymce.is(v, 'number') || /^[\-0-9\.]+$/.test(v))) v += 'px'; switch (na) { case 'opacity': // IE specific opacity if (isIE) { s.filter = v === '' ? '' : "alpha(opacity=" + (v * 100) + ")"; if (!n.currentStyle || !n.currentStyle.hasLayout) s.display = 'inline-block'; } // Fix for older browsers s[na] = s['-moz-opacity'] = s['-khtml-opacity'] = v || ''; break; case 'float': isIE ? s.styleFloat = v : s.cssFloat = v; break; default: s[na] = v || ''; } // Force update of the style data if (t.settings.update_styles) t.setAttrib(e, 'data-mce-style'); }); }, getStyle : function(n, na, c) { n = this.get(n); if (!n) return; // Gecko if (this.doc.defaultView && c) { // Remove camelcase na = na.replace(/[A-Z]/g, function(a){ return '-' + a; }); try { return this.doc.defaultView.getComputedStyle(n, null).getPropertyValue(na); } catch (ex) { // Old safari might fail return null; } } // Camelcase it, if needed na = na.replace(/-(\D)/g, function(a, b){ return b.toUpperCase(); }); if (na == 'float') na = isIE ? 'styleFloat' : 'cssFloat'; // IE & Opera if (n.currentStyle && c) return n.currentStyle[na]; return n.style ? n.style[na] : undefined; }, setStyles : function(e, o) { var t = this, s = t.settings, ol; ol = s.update_styles; s.update_styles = 0; each(o, function(v, n) { t.setStyle(e, n, v); }); // Update style info s.update_styles = ol; if (s.update_styles) t.setAttrib(e, s.cssText); }, removeAllAttribs: function(e) { return this.run(e, function(e) { var i, attrs = e.attributes; for (i = attrs.length - 1; i >= 0; i--) { e.removeAttributeNode(attrs.item(i)); } }); }, setAttrib : function(e, n, v) { var t = this; // Whats the point if (!e || !n) return; // Strict XML mode if (t.settings.strict) n = n.toLowerCase(); return this.run(e, function(e) { var s = t.settings; var originalValue = e.getAttribute(n); if (v !== null) { switch (n) { case "style": if (!is(v, 'string')) { each(v, function(v, n) { t.setStyle(e, n, v); }); return; } // No mce_style for elements with these since they might get resized by the user if (s.keep_values) { if (v && !t._isRes(v)) e.setAttribute('data-mce-style', v, 2); else e.removeAttribute('data-mce-style', 2); } e.style.cssText = v; break; case "class": e.className = v || ''; // Fix IE null bug break; case "src": case "href": if (s.keep_values) { if (s.url_converter) v = s.url_converter.call(s.url_converter_scope || t, v, n, e); t.setAttrib(e, 'data-mce-' + n, v, 2); } break; case "shape": e.setAttribute('data-mce-style', v); break; } } if (is(v) && v !== null && v.length !== 0) e.setAttribute(n, '' + v, 2); else e.removeAttribute(n, 2); // fire onChangeAttrib event for attributes that have changed if (tinyMCE.activeEditor && originalValue != v) { var ed = tinyMCE.activeEditor; ed.onSetAttrib.dispatch(ed, e, n, v); } }); }, setAttribs : function(e, o) { var t = this; return this.run(e, function(e) { each(o, function(v, n) { t.setAttrib(e, n, v); }); }); }, getAttrib : function(e, n, dv) { var v, t = this, undef; e = t.get(e); if (!e || e.nodeType !== 1) return dv === undef ? false : dv; if (!is(dv)) dv = ''; // Try the mce variant for these if (/^(src|href|style|coords|shape)$/.test(n)) { v = e.getAttribute("data-mce-" + n); if (v) return v; } if (isIE && t.props[n]) { v = e[t.props[n]]; v = v && v.nodeValue ? v.nodeValue : v; } if (!v) v = e.getAttribute(n, 2); // Check boolean attribs if (/^(checked|compact|declare|defer|disabled|ismap|multiple|nohref|noshade|nowrap|readonly|selected)$/.test(n)) { if (e[t.props[n]] === true && v === '') return n; return v ? n : ''; } // Inner input elements will override attributes on form elements if (e.nodeName === "FORM" && e.getAttributeNode(n)) return e.getAttributeNode(n).nodeValue; if (n === 'style') { v = v || e.style.cssText; if (v) { v = t.serializeStyle(t.parseStyle(v), e.nodeName); if (t.settings.keep_values && !t._isRes(v)) e.setAttribute('data-mce-style', v); } } // Remove Apple and WebKit stuff if (isWebKit && n === "class" && v) v = v.replace(/(apple|webkit)\-[a-z\-]+/gi, ''); // Handle IE issues if (isIE) { switch (n) { case 'rowspan': case 'colspan': // IE returns 1 as default value if (v === 1) v = ''; break; case 'size': // IE returns +0 as default value for size if (v === '+0' || v === 20 || v === 0) v = ''; break; case 'width': case 'height': case 'vspace': case 'checked': case 'disabled': case 'readonly': if (v === 0) v = ''; break; case 'hspace': // IE returns -1 as default value if (v === -1) v = ''; break; case 'maxlength': case 'tabindex': // IE returns default value if (v === 32768 || v === 2147483647 || v === '32768') v = ''; break; case 'multiple': case 'compact': case 'noshade': case 'nowrap': if (v === 65535) return n; return dv; case 'shape': v = v.toLowerCase(); break; default: // IE has odd anonymous function for event attributes if (n.indexOf('on') === 0 && v) v = tinymce._replace(/^function\s+\w+\(\)\s+\{\s+(.*)\s+\}$/, '$1', '' + v); } } return (v !== undef && v !== null && v !== '') ? '' + v : dv; }, getPos : function(n, ro) { var t = this, x = 0, y = 0, e, d = t.doc, r; n = t.get(n); ro = ro || d.body; if (n) { // Use getBoundingClientRect if it exists since it's faster than looping offset nodes if (n.getBoundingClientRect) { n = n.getBoundingClientRect(); e = t.boxModel ? d.documentElement : d.body; // Add scroll offsets from documentElement or body since IE with the wrong box model will use d.body and so do WebKit // Also remove the body/documentelement clientTop/clientLeft on IE 6, 7 since they offset the position x = n.left + (d.documentElement.scrollLeft || d.body.scrollLeft) - e.clientTop; y = n.top + (d.documentElement.scrollTop || d.body.scrollTop) - e.clientLeft; return {x : x, y : y}; } r = n; while (r && r != ro && r.nodeType) { x += r.offsetLeft || 0; y += r.offsetTop || 0; r = r.offsetParent; } r = n.parentNode; while (r && r != ro && r.nodeType) { x -= r.scrollLeft || 0; y -= r.scrollTop || 0; r = r.parentNode; } } return {x : x, y : y}; }, parseStyle : function(st) { return this.styles.parse(st); }, serializeStyle : function(o, name) { return this.styles.serialize(o, name); }, loadCSS : function(u) { var t = this, d = t.doc, head; if (!u) u = ''; head = d.getElementsByTagName('head')[0]; each(u.split(','), function(u) { var link; if (t.files[u]) return; t.files[u] = true; link = t.create('link', {rel : 'stylesheet', href : tinymce._addVer(u)}); // IE 8 has a bug where dynamically loading stylesheets would produce a 1 item remaining bug // This fix seems to resolve that issue by realcing the document ones a stylesheet finishes loading // It's ugly but it seems to work fine. if (isIE && d.documentMode && d.recalc) { link.onload = function() { if (d.recalc) d.recalc(); link.onload = null; }; } head.appendChild(link); }); }, addClass : function(e, c) { return this.run(e, function(e) { var o; if (!c) return 0; if (this.hasClass(e, c)) return e.className; o = this.removeClass(e, c); return e.className = (o != '' ? (o + ' ') : '') + c; }); }, removeClass : function(e, c) { var t = this, re; return t.run(e, function(e) { var v; if (t.hasClass(e, c)) { if (!re) re = new RegExp("(^|\\s+)" + c + "(\\s+|$)", "g"); v = e.className.replace(re, ' '); v = tinymce.trim(v != ' ' ? v : ''); e.className = v; // Empty class attr if (!v) { e.removeAttribute('class'); e.removeAttribute('className'); } return v; } return e.className; }); }, hasClass : function(n, c) { n = this.get(n); if (!n || !c) return false; return (' ' + n.className + ' ').indexOf(' ' + c + ' ') !== -1; }, show : function(e) { return this.setStyle(e, 'display', 'block'); }, hide : function(e) { return this.setStyle(e, 'display', 'none'); }, isHidden : function(e) { e = this.get(e); return !e || e.style.display == 'none' || this.getStyle(e, 'display') == 'none'; }, uniqueId : function(p) { return (!p ? 'mce_' : p) + (this.counter++); }, setHTML : function(element, html) { var self = this; return self.run(element, function(element) { if (isIE) { // Remove all child nodes, IE keeps empty text nodes in DOM while (element.firstChild) element.removeChild(element.firstChild); try { // IE will remove comments from the beginning // unless you padd the contents with something element.innerHTML = '<br />' + html; element.removeChild(element.firstChild); } catch (ex) { // IE sometimes produces an unknown runtime error on innerHTML if it's an block element within a block element for example a div inside a p // This seems to fix this problem // Create new div with HTML contents and a BR infront to keep comments element = self.create('div'); element.innerHTML = '<br />' + html; // Add all children from div to target each (element.childNodes, function(node, i) { // Skip br element if (i) element.appendChild(node); }); } } else element.innerHTML = html; return html; }); }, getOuterHTML : function(elm) { var doc, self = this; elm = self.get(elm); if (!elm) return null; if (elm.nodeType === 1 && self.hasOuterHTML) return elm.outerHTML; doc = (elm.ownerDocument || self.doc).createElement("body"); doc.appendChild(elm.cloneNode(true)); return doc.innerHTML; }, setOuterHTML : function(e, h, d) { var t = this; function setHTML(e, h, d) { var n, tp; tp = d.createElement("body"); tp.innerHTML = h; n = tp.lastChild; while (n) { t.insertAfter(n.cloneNode(true), e); n = n.previousSibling; } t.remove(e); }; return this.run(e, function(e) { e = t.get(e); // Only set HTML on elements if (e.nodeType == 1) { d = d || e.ownerDocument || t.doc; if (isIE) { try { // Try outerHTML for IE it sometimes produces an unknown runtime error if (isIE && e.nodeType == 1) e.outerHTML = h; else setHTML(e, h, d); } catch (ex) { // Fix for unknown runtime error setHTML(e, h, d); } } else setHTML(e, h, d); } }); }, decode : Entities.decode, encode : Entities.encodeAllRaw, insertAfter : function(node, reference_node) { reference_node = this.get(reference_node); return this.run(node, function(node) { var parent, nextSibling; parent = reference_node.parentNode; nextSibling = reference_node.nextSibling; if (nextSibling) parent.insertBefore(node, nextSibling); else parent.appendChild(node); return node; }); }, replace : function(n, o, k) { var t = this; if (is(o, 'array')) n = n.cloneNode(true); return t.run(o, function(o) { if (k) { each(tinymce.grep(o.childNodes), function(c) { n.appendChild(c); }); } return o.parentNode.replaceChild(n, o); }); }, rename : function(elm, name) { var t = this, newElm; if (elm.nodeName != name.toUpperCase()) { // Rename block element newElm = t.create(name); // Copy attribs to new block each(t.getAttribs(elm), function(attr_node) { t.setAttrib(newElm, attr_node.nodeName, t.getAttrib(elm, attr_node.nodeName)); }); // Replace block t.replace(newElm, elm, 1); } return newElm || elm; }, findCommonAncestor : function(a, b) { var ps = a, pe; while (ps) { pe = b; while (pe && ps != pe) pe = pe.parentNode; if (ps == pe) break; ps = ps.parentNode; } if (!ps && a.ownerDocument) return a.ownerDocument.documentElement; return ps; }, toHex : function(s) { var c = /^\s*rgb\s*?\(\s*?([0-9]+)\s*?,\s*?([0-9]+)\s*?,\s*?([0-9]+)\s*?\)\s*$/i.exec(s); function hex(s) { s = parseInt(s, 10).toString(16); return s.length > 1 ? s : '0' + s; // 0 -> 00 }; if (c) { s = '#' + hex(c[1]) + hex(c[2]) + hex(c[3]); return s; } return s; }, getClasses : function() { var t = this, cl = [], i, lo = {}, f = t.settings.class_filter, ov; if (t.classes) return t.classes; function addClasses(s) { // IE style imports each(s.imports, function(r) { addClasses(r); }); each(s.cssRules || s.rules, function(r) { // Real type or fake it on IE switch (r.type || 1) { // Rule case 1: if (r.selectorText) { each(r.selectorText.split(','), function(v) { v = v.replace(/^\s*|\s*$|^\s\./g, ""); // Is internal or it doesn't contain a class if (/\.mce/.test(v) || !/\.[\w\-]+$/.test(v)) return; // Remove everything but class name ov = v; v = tinymce._replace(/.*\.([a-z0-9_\-]+).*/i, '$1', v); // Filter classes if (f && !(v = f(v, ov))) return; if (!lo[v]) { cl.push({'class' : v}); lo[v] = 1; } }); } break; // Import case 3: addClasses(r.styleSheet); break; } }); }; try { each(t.doc.styleSheets, addClasses); } catch (ex) { // Ignore } if (cl.length > 0) t.classes = cl; return cl; }, run : function(e, f, s) { var t = this, o; if (t.doc && typeof(e) === 'string') e = t.get(e); if (!e) return false; s = s || this; if (!e.nodeType && (e.length || e.length === 0)) { o = []; each(e, function(e, i) { if (e) { if (typeof(e) == 'string') e = t.doc.getElementById(e); o.push(f.call(s, e, i)); } }); return o; } return f.call(s, e); }, getAttribs : function(n) { var o; n = this.get(n); if (!n) return []; if (isIE) { o = []; // Object will throw exception in IE if (n.nodeName == 'OBJECT') return n.attributes; // IE doesn't keep the selected attribute if you clone option elements if (n.nodeName === 'OPTION' && this.getAttrib(n, 'selected')) o.push({specified : 1, nodeName : 'selected'}); // It's crazy that this is faster in IE but it's because it returns all attributes all the time n.cloneNode(false).outerHTML.replace(/<\/?[\w:\-]+ ?|=[\"][^\"]+\"|=\'[^\']+\'|=[\w\-]+|>/gi, '').replace(/[\w:\-]+/gi, function(a) { o.push({specified : 1, nodeName : a}); }); return o; } return n.attributes; }, isEmpty : function(node, elements) { var self = this, i, attributes, type, walker, name, brCount = 0; node = node.firstChild; if (node) { walker = new tinymce.dom.TreeWalker(node, node.parentNode); elements = elements || self.schema ? self.schema.getNonEmptyElements() : null; do { type = node.nodeType; if (type === 1) { // Ignore bogus elements if (node.getAttribute('data-mce-bogus')) continue; // Keep empty elements like <img /> name = node.nodeName.toLowerCase(); if (elements && elements[name]) { // Ignore single BR elements in blocks like <p><br /></p> or <p><span><br /></span></p> if (name === 'br') { brCount++; continue; } return false; } // Keep elements with data-bookmark attributes or name attribute like <a name="1"></a> attributes = self.getAttribs(node); i = node.attributes.length; while (i--) { name = node.attributes[i].nodeName; if (name === "name" || name === 'data-mce-bookmark') return false; } } // Keep comment nodes if (type == 8) return false; // Keep non whitespace text nodes if ((type === 3 && !whiteSpaceRegExp.test(node.nodeValue))) return false; } while (node = walker.next()); } return brCount <= 1; }, destroy : function(s) { var t = this; t.win = t.doc = t.root = t.events = t.frag = null; // Manual destroy then remove unload handler if (!s) tinymce.removeUnload(t.destroy); }, createRng : function() { var d = this.doc; return d.createRange ? d.createRange() : new tinymce.dom.Range(this); }, nodeIndex : function(node, normalized) { var idx = 0, lastNodeType, lastNode, nodeType; if (node) { for (lastNodeType = node.nodeType, node = node.previousSibling, lastNode = node; node; node = node.previousSibling) { nodeType = node.nodeType; // Normalize text nodes if (normalized && nodeType == 3) { if (nodeType == lastNodeType || !node.nodeValue.length) continue; } idx++; lastNodeType = nodeType; } } return idx; }, split : function(pe, e, re) { var t = this, r = t.createRng(), bef, aft, pa; // W3C valid browsers tend to leave empty nodes to the left/right side of the contents, this makes sense // but we don't want that in our code since it serves no purpose for the end user // For example if this is chopped: // <p>text 1<span><b>CHOP</b></span>text 2</p> // would produce: // <p>text 1<span></span></p><b>CHOP</b><p><span></span>text 2</p> // this function will then trim of empty edges and produce: // <p>text 1</p><b>CHOP</b><p>text 2</p> function trim(node) { var i, children = node.childNodes, type = node.nodeType; function surroundedBySpans(node) { var previousIsSpan = node.previousSibling && node.previousSibling.nodeName == 'SPAN'; var nextIsSpan = node.nextSibling && node.nextSibling.nodeName == 'SPAN'; return previousIsSpan && nextIsSpan; } if (type == 1 && node.getAttribute('data-mce-type') == 'bookmark') return; for (i = children.length - 1; i >= 0; i--) trim(children[i]); if (type != 9) { // Keep non whitespace text nodes if (type == 3 && node.nodeValue.length > 0) { // If parent element isn't a block or there isn't any useful contents for example "<p> </p>" // Also keep text nodes with only spaces if surrounded by spans. // eg. "<p><span>a</span> <span>b</span></p>" should keep space between a and b var trimmedLength = tinymce.trim(node.nodeValue).length; if (!t.isBlock(node.parentNode) || trimmedLength > 0 || trimmedLength === 0 && surroundedBySpans(node)) return; } else if (type == 1) { // If the only child is a bookmark then move it up children = node.childNodes; if (children.length == 1 && children[0] && children[0].nodeType == 1 && children[0].getAttribute('data-mce-type') == 'bookmark') node.parentNode.insertBefore(children[0], node); // Keep non empty elements or img, hr etc if (children.length || /^(br|hr|input|img)$/i.test(node.nodeName)) return; } t.remove(node); } return node; }; if (pe && e) { // Get before chunk r.setStart(pe.parentNode, t.nodeIndex(pe)); r.setEnd(e.parentNode, t.nodeIndex(e)); bef = r.extractContents(); // Get after chunk r = t.createRng(); r.setStart(e.parentNode, t.nodeIndex(e) + 1); r.setEnd(pe.parentNode, t.nodeIndex(pe) + 1); aft = r.extractContents(); // Insert before chunk pa = pe.parentNode; pa.insertBefore(trim(bef), pe); // Insert middle chunk if (re) pa.replaceChild(re, e); else pa.insertBefore(e, pe); // Insert after chunk pa.insertBefore(trim(aft), pe); t.remove(pe); return re || e; } }, bind : function(target, name, func, scope) { return this.events.add(target, name, func, scope || this); }, unbind : function(target, name, func) { return this.events.remove(target, name, func); }, fire : function(target, name, evt) { return this.events.fire(target, name, evt); }, // Returns the content editable state of a node getContentEditable: function(node) { var contentEditable; // Check type if (node.nodeType != 1) { return null; } // Check for fake content editable contentEditable = node.getAttribute("data-mce-contenteditable"); if (contentEditable && contentEditable !== "inherit") { return contentEditable; } // Check for real content editable return node.contentEditable !== "inherit" ? node.contentEditable : null; }, _findSib : function(node, selector, name) { var t = this, f = selector; if (node) { // If expression make a function of it using is if (is(f, 'string')) { f = function(node) { return t.is(node, selector); }; } // Loop all siblings for (node = node[name]; node; node = node[name]) { if (f(node)) return node; } } return null; }, _isRes : function(c) { // Is live resizble element return /^(top|left|bottom|right|width|height)/i.test(c) || /;\s*(top|left|bottom|right|width|height)/i.test(c); } /* walk : function(n, f, s) { var d = this.doc, w; if (d.createTreeWalker) { w = d.createTreeWalker(n, NodeFilter.SHOW_TEXT, null, false); while ((n = w.nextNode()) != null) f.call(s || this, n); } else tinymce.walk(n, f, 'childNodes', s); } */ /* toRGB : function(s) { var c = /^\s*?#([0-9A-F]{2})([0-9A-F]{1,2})([0-9A-F]{2})?\s*?$/.exec(s); if (c) { // #FFF -> #FFFFFF if (!is(c[3])) c[3] = c[2] = c[1]; return "rgb(" + parseInt(c[1], 16) + "," + parseInt(c[2], 16) + "," + parseInt(c[3], 16) + ")"; } return s; } */ }); tinymce.DOM = new tinymce.dom.DOMUtils(document, {process_html : 0}); })(tinymce); (function(ns) { // Range constructor function Range(dom) { var t = this, doc = dom.doc, EXTRACT = 0, CLONE = 1, DELETE = 2, TRUE = true, FALSE = false, START_OFFSET = 'startOffset', START_CONTAINER = 'startContainer', END_CONTAINER = 'endContainer', END_OFFSET = 'endOffset', extend = tinymce.extend, nodeIndex = dom.nodeIndex; extend(t, { // Inital states startContainer : doc, startOffset : 0, endContainer : doc, endOffset : 0, collapsed : TRUE, commonAncestorContainer : doc, // Range constants START_TO_START : 0, START_TO_END : 1, END_TO_END : 2, END_TO_START : 3, // Public methods setStart : setStart, setEnd : setEnd, setStartBefore : setStartBefore, setStartAfter : setStartAfter, setEndBefore : setEndBefore, setEndAfter : setEndAfter, collapse : collapse, selectNode : selectNode, selectNodeContents : selectNodeContents, compareBoundaryPoints : compareBoundaryPoints, deleteContents : deleteContents, extractContents : extractContents, cloneContents : cloneContents, insertNode : insertNode, surroundContents : surroundContents, cloneRange : cloneRange }); function createDocumentFragment() { return doc.createDocumentFragment(); }; function setStart(n, o) { _setEndPoint(TRUE, n, o); }; function setEnd(n, o) { _setEndPoint(FALSE, n, o); }; function setStartBefore(n) { setStart(n.parentNode, nodeIndex(n)); }; function setStartAfter(n) { setStart(n.parentNode, nodeIndex(n) + 1); }; function setEndBefore(n) { setEnd(n.parentNode, nodeIndex(n)); }; function setEndAfter(n) { setEnd(n.parentNode, nodeIndex(n) + 1); }; function collapse(ts) { if (ts) { t[END_CONTAINER] = t[START_CONTAINER]; t[END_OFFSET] = t[START_OFFSET]; } else { t[START_CONTAINER] = t[END_CONTAINER]; t[START_OFFSET] = t[END_OFFSET]; } t.collapsed = TRUE; }; function selectNode(n) { setStartBefore(n); setEndAfter(n); }; function selectNodeContents(n) { setStart(n, 0); setEnd(n, n.nodeType === 1 ? n.childNodes.length : n.nodeValue.length); }; function compareBoundaryPoints(h, r) { var sc = t[START_CONTAINER], so = t[START_OFFSET], ec = t[END_CONTAINER], eo = t[END_OFFSET], rsc = r.startContainer, rso = r.startOffset, rec = r.endContainer, reo = r.endOffset; // Check START_TO_START if (h === 0) return _compareBoundaryPoints(sc, so, rsc, rso); // Check START_TO_END if (h === 1) return _compareBoundaryPoints(ec, eo, rsc, rso); // Check END_TO_END if (h === 2) return _compareBoundaryPoints(ec, eo, rec, reo); // Check END_TO_START if (h === 3) return _compareBoundaryPoints(sc, so, rec, reo); }; function deleteContents() { _traverse(DELETE); }; function extractContents() { return _traverse(EXTRACT); }; function cloneContents() { return _traverse(CLONE); }; function insertNode(n) { var startContainer = this[START_CONTAINER], startOffset = this[START_OFFSET], nn, o; // Node is TEXT_NODE or CDATA if ((startContainer.nodeType === 3 || startContainer.nodeType === 4) && startContainer.nodeValue) { if (!startOffset) { // At the start of text startContainer.parentNode.insertBefore(n, startContainer); } else if (startOffset >= startContainer.nodeValue.length) { // At the end of text dom.insertAfter(n, startContainer); } else { // Middle, need to split nn = startContainer.splitText(startOffset); startContainer.parentNode.insertBefore(n, nn); } } else { // Insert element node if (startContainer.childNodes.length > 0) o = startContainer.childNodes[startOffset]; if (o) startContainer.insertBefore(n, o); else startContainer.appendChild(n); } }; function surroundContents(n) { var f = t.extractContents(); t.insertNode(n); n.appendChild(f); t.selectNode(n); }; function cloneRange() { return extend(new Range(dom), { startContainer : t[START_CONTAINER], startOffset : t[START_OFFSET], endContainer : t[END_CONTAINER], endOffset : t[END_OFFSET], collapsed : t.collapsed, commonAncestorContainer : t.commonAncestorContainer }); }; // Private methods function _getSelectedNode(container, offset) { var child; if (container.nodeType == 3 /* TEXT_NODE */) return container; if (offset < 0) return container; child = container.firstChild; while (child && offset > 0) { --offset; child = child.nextSibling; } if (child) return child; return container; }; function _isCollapsed() { return (t[START_CONTAINER] == t[END_CONTAINER] && t[START_OFFSET] == t[END_OFFSET]); }; function _compareBoundaryPoints(containerA, offsetA, containerB, offsetB) { var c, offsetC, n, cmnRoot, childA, childB; // In the first case the boundary-points have the same container. A is before B // if its offset is less than the offset of B, A is equal to B if its offset is // equal to the offset of B, and A is after B if its offset is greater than the // offset of B. if (containerA == containerB) { if (offsetA == offsetB) return 0; // equal if (offsetA < offsetB) return -1; // before return 1; // after } // In the second case a child node C of the container of A is an ancestor // container of B. In this case, A is before B if the offset of A is less than or // equal to the index of the child node C and A is after B otherwise. c = containerB; while (c && c.parentNode != containerA) c = c.parentNode; if (c) { offsetC = 0; n = containerA.firstChild; while (n != c && offsetC < offsetA) { offsetC++; n = n.nextSibling; } if (offsetA <= offsetC) return -1; // before return 1; // after } // In the third case a child node C of the container of B is an ancestor container // of A. In this case, A is before B if the index of the child node C is less than // the offset of B and A is after B otherwise. c = containerA; while (c && c.parentNode != containerB) { c = c.parentNode; } if (c) { offsetC = 0; n = containerB.firstChild; while (n != c && offsetC < offsetB) { offsetC++; n = n.nextSibling; } if (offsetC < offsetB) return -1; // before return 1; // after } // In the fourth case, none of three other cases hold: the containers of A and B // are siblings or descendants of sibling nodes. In this case, A is before B if // the container of A is before the container of B in a pre-order traversal of the // Ranges' context tree and A is after B otherwise. cmnRoot = dom.findCommonAncestor(containerA, containerB); childA = containerA; while (childA && childA.parentNode != cmnRoot) childA = childA.parentNode; if (!childA) childA = cmnRoot; childB = containerB; while (childB && childB.parentNode != cmnRoot) childB = childB.parentNode; if (!childB) childB = cmnRoot; if (childA == childB) return 0; // equal n = cmnRoot.firstChild; while (n) { if (n == childA) return -1; // before if (n == childB) return 1; // after n = n.nextSibling; } }; function _setEndPoint(st, n, o) { var ec, sc; if (st) { t[START_CONTAINER] = n; t[START_OFFSET] = o; } else { t[END_CONTAINER] = n; t[END_OFFSET] = o; } // If one boundary-point of a Range is set to have a root container // other than the current one for the Range, the Range is collapsed to // the new position. This enforces the restriction that both boundary- // points of a Range must have the same root container. ec = t[END_CONTAINER]; while (ec.parentNode) ec = ec.parentNode; sc = t[START_CONTAINER]; while (sc.parentNode) sc = sc.parentNode; if (sc == ec) { // The start position of a Range is guaranteed to never be after the // end position. To enforce this restriction, if the start is set to // be at a position after the end, the Range is collapsed to that // position. if (_compareBoundaryPoints(t[START_CONTAINER], t[START_OFFSET], t[END_CONTAINER], t[END_OFFSET]) > 0) t.collapse(st); } else t.collapse(st); t.collapsed = _isCollapsed(); t.commonAncestorContainer = dom.findCommonAncestor(t[START_CONTAINER], t[END_CONTAINER]); }; function _traverse(how) { var c, endContainerDepth = 0, startContainerDepth = 0, p, depthDiff, startNode, endNode, sp, ep; if (t[START_CONTAINER] == t[END_CONTAINER]) return _traverseSameContainer(how); for (c = t[END_CONTAINER], p = c.parentNode; p; c = p, p = p.parentNode) { if (p == t[START_CONTAINER]) return _traverseCommonStartContainer(c, how); ++endContainerDepth; } for (c = t[START_CONTAINER], p = c.parentNode; p; c = p, p = p.parentNode) { if (p == t[END_CONTAINER]) return _traverseCommonEndContainer(c, how); ++startContainerDepth; } depthDiff = startContainerDepth - endContainerDepth; startNode = t[START_CONTAINER]; while (depthDiff > 0) { startNode = startNode.parentNode; depthDiff--; } endNode = t[END_CONTAINER]; while (depthDiff < 0) { endNode = endNode.parentNode; depthDiff++; } // ascend the ancestor hierarchy until we have a common parent. for (sp = startNode.parentNode, ep = endNode.parentNode; sp != ep; sp = sp.parentNode, ep = ep.parentNode) { startNode = sp; endNode = ep; } return _traverseCommonAncestors(startNode, endNode, how); }; function _traverseSameContainer(how) { var frag, s, sub, n, cnt, sibling, xferNode, start, len; if (how != DELETE) frag = createDocumentFragment(); // If selection is empty, just return the fragment if (t[START_OFFSET] == t[END_OFFSET]) return frag; // Text node needs special case handling if (t[START_CONTAINER].nodeType == 3 /* TEXT_NODE */) { // get the substring s = t[START_CONTAINER].nodeValue; sub = s.substring(t[START_OFFSET], t[END_OFFSET]); // set the original text node to its new value if (how != CLONE) { n = t[START_CONTAINER]; start = t[START_OFFSET]; len = t[END_OFFSET] - t[START_OFFSET]; if (start === 0 && len >= n.nodeValue.length - 1) { n.parentNode.removeChild(n); } else { n.deleteData(start, len); } // Nothing is partially selected, so collapse to start point t.collapse(TRUE); } if (how == DELETE) return; if (sub.length > 0) { frag.appendChild(doc.createTextNode(sub)); } return frag; } // Copy nodes between the start/end offsets. n = _getSelectedNode(t[START_CONTAINER], t[START_OFFSET]); cnt = t[END_OFFSET] - t[START_OFFSET]; while (n && cnt > 0) { sibling = n.nextSibling; xferNode = _traverseFullySelected(n, how); if (frag) frag.appendChild( xferNode ); --cnt; n = sibling; } // Nothing is partially selected, so collapse to start point if (how != CLONE) t.collapse(TRUE); return frag; }; function _traverseCommonStartContainer(endAncestor, how) { var frag, n, endIdx, cnt, sibling, xferNode; if (how != DELETE) frag = createDocumentFragment(); n = _traverseRightBoundary(endAncestor, how); if (frag) frag.appendChild(n); endIdx = nodeIndex(endAncestor); cnt = endIdx - t[START_OFFSET]; if (cnt <= 0) { // Collapse to just before the endAncestor, which // is partially selected. if (how != CLONE) { t.setEndBefore(endAncestor); t.collapse(FALSE); } return frag; } n = endAncestor.previousSibling; while (cnt > 0) { sibling = n.previousSibling; xferNode = _traverseFullySelected(n, how); if (frag) frag.insertBefore(xferNode, frag.firstChild); --cnt; n = sibling; } // Collapse to just before the endAncestor, which // is partially selected. if (how != CLONE) { t.setEndBefore(endAncestor); t.collapse(FALSE); } return frag; }; function _traverseCommonEndContainer(startAncestor, how) { var frag, startIdx, n, cnt, sibling, xferNode; if (how != DELETE) frag = createDocumentFragment(); n = _traverseLeftBoundary(startAncestor, how); if (frag) frag.appendChild(n); startIdx = nodeIndex(startAncestor); ++startIdx; // Because we already traversed it cnt = t[END_OFFSET] - startIdx; n = startAncestor.nextSibling; while (n && cnt > 0) { sibling = n.nextSibling; xferNode = _traverseFullySelected(n, how); if (frag) frag.appendChild(xferNode); --cnt; n = sibling; } if (how != CLONE) { t.setStartAfter(startAncestor); t.collapse(TRUE); } return frag; }; function _traverseCommonAncestors(startAncestor, endAncestor, how) { var n, frag, commonParent, startOffset, endOffset, cnt, sibling, nextSibling; if (how != DELETE) frag = createDocumentFragment(); n = _traverseLeftBoundary(startAncestor, how); if (frag) frag.appendChild(n); commonParent = startAncestor.parentNode; startOffset = nodeIndex(startAncestor); endOffset = nodeIndex(endAncestor); ++startOffset; cnt = endOffset - startOffset; sibling = startAncestor.nextSibling; while (cnt > 0) { nextSibling = sibling.nextSibling; n = _traverseFullySelected(sibling, how); if (frag) frag.appendChild(n); sibling = nextSibling; --cnt; } n = _traverseRightBoundary(endAncestor, how); if (frag) frag.appendChild(n); if (how != CLONE) { t.setStartAfter(startAncestor); t.collapse(TRUE); } return frag; }; function _traverseRightBoundary(root, how) { var next = _getSelectedNode(t[END_CONTAINER], t[END_OFFSET] - 1), parent, clonedParent, prevSibling, clonedChild, clonedGrandParent, isFullySelected = next != t[END_CONTAINER]; if (next == root) return _traverseNode(next, isFullySelected, FALSE, how); parent = next.parentNode; clonedParent = _traverseNode(parent, FALSE, FALSE, how); while (parent) { while (next) { prevSibling = next.previousSibling; clonedChild = _traverseNode(next, isFullySelected, FALSE, how); if (how != DELETE) clonedParent.insertBefore(clonedChild, clonedParent.firstChild); isFullySelected = TRUE; next = prevSibling; } if (parent == root) return clonedParent; next = parent.previousSibling; parent = parent.parentNode; clonedGrandParent = _traverseNode(parent, FALSE, FALSE, how); if (how != DELETE) clonedGrandParent.appendChild(clonedParent); clonedParent = clonedGrandParent; } }; function _traverseLeftBoundary(root, how) { var next = _getSelectedNode(t[START_CONTAINER], t[START_OFFSET]), isFullySelected = next != t[START_CONTAINER], parent, clonedParent, nextSibling, clonedChild, clonedGrandParent; if (next == root) return _traverseNode(next, isFullySelected, TRUE, how); parent = next.parentNode; clonedParent = _traverseNode(parent, FALSE, TRUE, how); while (parent) { while (next) { nextSibling = next.nextSibling; clonedChild = _traverseNode(next, isFullySelected, TRUE, how); if (how != DELETE) clonedParent.appendChild(clonedChild); isFullySelected = TRUE; next = nextSibling; } if (parent == root) return clonedParent; next = parent.nextSibling; parent = parent.parentNode; clonedGrandParent = _traverseNode(parent, FALSE, TRUE, how); if (how != DELETE) clonedGrandParent.appendChild(clonedParent); clonedParent = clonedGrandParent; } }; function _traverseNode(n, isFullySelected, isLeft, how) { var txtValue, newNodeValue, oldNodeValue, offset, newNode; if (isFullySelected) return _traverseFullySelected(n, how); if (n.nodeType == 3 /* TEXT_NODE */) { txtValue = n.nodeValue; if (isLeft) { offset = t[START_OFFSET]; newNodeValue = txtValue.substring(offset); oldNodeValue = txtValue.substring(0, offset); } else { offset = t[END_OFFSET]; newNodeValue = txtValue.substring(0, offset); oldNodeValue = txtValue.substring(offset); } if (how != CLONE) n.nodeValue = oldNodeValue; if (how == DELETE) return; newNode = dom.clone(n, FALSE); newNode.nodeValue = newNodeValue; return newNode; } if (how == DELETE) return; return dom.clone(n, FALSE); }; function _traverseFullySelected(n, how) { if (how != DELETE) return how == CLONE ? dom.clone(n, TRUE) : n; n.parentNode.removeChild(n); }; }; ns.Range = Range; })(tinymce.dom); (function() { function Selection(selection) { var self = this, dom = selection.dom, TRUE = true, FALSE = false; function getPosition(rng, start) { var checkRng, startIndex = 0, endIndex, inside, children, child, offset, index, position = -1, parent; // Setup test range, collapse it and get the parent checkRng = rng.duplicate(); checkRng.collapse(start); parent = checkRng.parentElement(); // Check if the selection is within the right document if (parent.ownerDocument !== selection.dom.doc) return; // IE will report non editable elements as it's parent so look for an editable one while (parent.contentEditable === "false") { parent = parent.parentNode; } // If parent doesn't have any children then return that we are inside the element if (!parent.hasChildNodes()) { return {node : parent, inside : 1}; } // Setup node list and endIndex children = parent.children; endIndex = children.length - 1; // Perform a binary search for the position while (startIndex <= endIndex) { index = Math.floor((startIndex + endIndex) / 2); // Move selection to node and compare the ranges child = children[index]; checkRng.moveToElementText(child); position = checkRng.compareEndPoints(start ? 'StartToStart' : 'EndToEnd', rng); // Before/after or an exact match if (position > 0) { endIndex = index - 1; } else if (position < 0) { startIndex = index + 1; } else { return {node : child}; } } // Check if child position is before or we didn't find a position if (position < 0) { // No element child was found use the parent element and the offset inside that if (!child) { checkRng.moveToElementText(parent); checkRng.collapse(true); child = parent; inside = true; } else checkRng.collapse(false); // Walk character by character in text node until we hit the selected range endpoint, hit the end of document or parent isn't the right one // We need to walk char by char since rng.text or rng.htmlText will trim line endings offset = 0; while (checkRng.compareEndPoints(start ? 'StartToStart' : 'StartToEnd', rng) !== 0) { if (checkRng.move('character', 1) === 0 || parent != checkRng.parentElement()) { break; } offset++; } } else { // Child position is after the selection endpoint checkRng.collapse(true); // Walk character by character in text node until we hit the selected range endpoint, hit the end of document or parent isn't the right one offset = 0; while (checkRng.compareEndPoints(start ? 'StartToStart' : 'StartToEnd', rng) !== 0) { if (checkRng.move('character', -1) === 0 || parent != checkRng.parentElement()) { break; } offset++; } } return {node : child, position : position, offset : offset, inside : inside}; }; // Returns a W3C DOM compatible range object by using the IE Range API function getRange() { var ieRange = selection.getRng(), domRange = dom.createRng(), element, collapsed, tmpRange, element2, bookmark, fail; // If selection is outside the current document just return an empty range element = ieRange.item ? ieRange.item(0) : ieRange.parentElement(); if (element.ownerDocument != dom.doc) return domRange; collapsed = selection.isCollapsed(); // Handle control selection if (ieRange.item) { domRange.setStart(element.parentNode, dom.nodeIndex(element)); domRange.setEnd(domRange.startContainer, domRange.startOffset + 1); return domRange; } function findEndPoint(start) { var endPoint = getPosition(ieRange, start), container, offset, textNodeOffset = 0, sibling, undef, nodeValue; container = endPoint.node; offset = endPoint.offset; if (endPoint.inside && !container.hasChildNodes()) { domRange[start ? 'setStart' : 'setEnd'](container, 0); return; } if (offset === undef) { domRange[start ? 'setStartBefore' : 'setEndAfter'](container); return; } if (endPoint.position < 0) { sibling = endPoint.inside ? container.firstChild : container.nextSibling; if (!sibling) { domRange[start ? 'setStartAfter' : 'setEndAfter'](container); return; } if (!offset) { if (sibling.nodeType == 3) domRange[start ? 'setStart' : 'setEnd'](sibling, 0); else domRange[start ? 'setStartBefore' : 'setEndBefore'](sibling); return; } // Find the text node and offset while (sibling) { nodeValue = sibling.nodeValue; textNodeOffset += nodeValue.length; // We are at or passed the position we where looking for if (textNodeOffset >= offset) { container = sibling; textNodeOffset -= offset; textNodeOffset = nodeValue.length - textNodeOffset; break; } sibling = sibling.nextSibling; } } else { // Find the text node and offset sibling = container.previousSibling; if (!sibling) return domRange[start ? 'setStartBefore' : 'setEndBefore'](container); // If there isn't any text to loop then use the first position if (!offset) { if (container.nodeType == 3) domRange[start ? 'setStart' : 'setEnd'](sibling, container.nodeValue.length); else domRange[start ? 'setStartAfter' : 'setEndAfter'](sibling); return; } while (sibling) { textNodeOffset += sibling.nodeValue.length; // We are at or passed the position we where looking for if (textNodeOffset >= offset) { container = sibling; textNodeOffset -= offset; break; } sibling = sibling.previousSibling; } } domRange[start ? 'setStart' : 'setEnd'](container, textNodeOffset); }; try { // Find start point findEndPoint(true); // Find end point if needed if (!collapsed) findEndPoint(); } catch (ex) { // IE has a nasty bug where text nodes might throw "invalid argument" when you // access the nodeValue or other properties of text nodes. This seems to happend when // text nodes are split into two nodes by a delete/backspace call. So lets detect it and try to fix it. if (ex.number == -2147024809) { // Get the current selection bookmark = self.getBookmark(2); // Get start element tmpRange = ieRange.duplicate(); tmpRange.collapse(true); element = tmpRange.parentElement(); // Get end element if (!collapsed) { tmpRange = ieRange.duplicate(); tmpRange.collapse(false); element2 = tmpRange.parentElement(); element2.innerHTML = element2.innerHTML; } // Remove the broken elements element.innerHTML = element.innerHTML; // Restore the selection self.moveToBookmark(bookmark); // Since the range has moved we need to re-get it ieRange = selection.getRng(); // Find start point findEndPoint(true); // Find end point if needed if (!collapsed) findEndPoint(); } else throw ex; // Throw other errors } return domRange; }; this.getBookmark = function(type) { var rng = selection.getRng(), start, end, bookmark = {}; function getIndexes(node) { var parent, root, children, i, indexes = []; parent = node.parentNode; root = dom.getRoot().parentNode; while (parent != root && parent.nodeType !== 9) { children = parent.children; i = children.length; while (i--) { if (node === children[i]) { indexes.push(i); break; } } node = parent; parent = parent.parentNode; } return indexes; }; function getBookmarkEndPoint(start) { var position; position = getPosition(rng, start); if (position) { return { position : position.position, offset : position.offset, indexes : getIndexes(position.node), inside : position.inside }; } }; // Non ubstructive bookmark if (type === 2) { // Handle text selection if (!rng.item) { bookmark.start = getBookmarkEndPoint(true); if (!selection.isCollapsed()) bookmark.end = getBookmarkEndPoint(); } else bookmark.start = {ctrl : true, indexes : getIndexes(rng.item(0))}; } return bookmark; }; this.moveToBookmark = function(bookmark) { var rng, body = dom.doc.body; function resolveIndexes(indexes) { var node, i, idx, children; node = dom.getRoot(); for (i = indexes.length - 1; i >= 0; i--) { children = node.children; idx = indexes[i]; if (idx <= children.length - 1) { node = children[idx]; } } return node; }; function setBookmarkEndPoint(start) { var endPoint = bookmark[start ? 'start' : 'end'], moveLeft, moveRng, undef; if (endPoint) { moveLeft = endPoint.position > 0; moveRng = body.createTextRange(); moveRng.moveToElementText(resolveIndexes(endPoint.indexes)); offset = endPoint.offset; if (offset !== undef) { moveRng.collapse(endPoint.inside || moveLeft); moveRng.moveStart('character', moveLeft ? -offset : offset); } else moveRng.collapse(start); rng.setEndPoint(start ? 'StartToStart' : 'EndToStart', moveRng); if (start) rng.collapse(true); } }; if (bookmark.start) { if (bookmark.start.ctrl) { rng = body.createControlRange(); rng.addElement(resolveIndexes(bookmark.start.indexes)); rng.select(); } else { rng = body.createTextRange(); setBookmarkEndPoint(true); setBookmarkEndPoint(); rng.select(); } } }; this.addRange = function(rng) { var ieRng, ctrlRng, startContainer, startOffset, endContainer, endOffset, doc = selection.dom.doc, body = doc.body; function setEndPoint(start) { var container, offset, marker, tmpRng, nodes; marker = dom.create('a'); container = start ? startContainer : endContainer; offset = start ? startOffset : endOffset; tmpRng = ieRng.duplicate(); if (container == doc || container == doc.documentElement) { container = body; offset = 0; } if (container.nodeType == 3) { container.parentNode.insertBefore(marker, container); tmpRng.moveToElementText(marker); tmpRng.moveStart('character', offset); dom.remove(marker); ieRng.setEndPoint(start ? 'StartToStart' : 'EndToEnd', tmpRng); } else { nodes = container.childNodes; if (nodes.length) { if (offset >= nodes.length) { dom.insertAfter(marker, nodes[nodes.length - 1]); } else { container.insertBefore(marker, nodes[offset]); } tmpRng.moveToElementText(marker); } else if (container.canHaveHTML) { // Empty node selection for example <div>|</div> // Setting innerHTML with a span marker then remove that marker seems to keep empty block elements open container.innerHTML = '<span>\uFEFF</span>'; marker = container.firstChild; tmpRng.moveToElementText(marker); tmpRng.collapse(FALSE); // Collapse false works better than true for some odd reason } ieRng.setEndPoint(start ? 'StartToStart' : 'EndToEnd', tmpRng); dom.remove(marker); } } // Setup some shorter versions startContainer = rng.startContainer; startOffset = rng.startOffset; endContainer = rng.endContainer; endOffset = rng.endOffset; ieRng = body.createTextRange(); // If single element selection then try making a control selection out of it if (startContainer == endContainer && startContainer.nodeType == 1) { // Trick to place the caret inside an empty block element like <p></p> if (startOffset == endOffset && !startContainer.hasChildNodes()) { if (startContainer.canHaveHTML) { startContainer.innerHTML = '<span>\uFEFF</span><span>\uFEFF</span>'; ieRng.moveToElementText(startContainer.lastChild); ieRng.select(); dom.doc.selection.clear(); startContainer.innerHTML = ''; return; } else { startOffset = dom.nodeIndex(startContainer); startContainer = startContainer.parentNode; } } if (startOffset == endOffset - 1) { try { ctrlRng = body.createControlRange(); ctrlRng.addElement(startContainer.childNodes[startOffset]); ctrlRng.select(); return; } catch (ex) { // Ignore } } } // Set start/end point of selection setEndPoint(true); setEndPoint(); // Select the new range and scroll it into view ieRng.select(); }; // Expose range method this.getRangeAt = getRange; }; // Expose the selection object tinymce.dom.TridentSelection = Selection; })(); /* * Sizzle CSS Selector Engine * Copyright, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * More information: http://sizzlejs.com/ */ (function(){ var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, expando = "sizcache", done = 0, toString = Object.prototype.toString, hasDuplicate = false, baseHasDuplicate = true, rBackslash = /\\/g, rReturn = /\r\n/g, rNonWord = /\W/; // Here we check if the JavaScript engine is using some sort of // optimization where it does not always call our comparision // function. If that is the case, discard the hasDuplicate value. // Thus far that includes Google Chrome. [0, 0].sort(function() { baseHasDuplicate = false; return 0; }); var Sizzle = function( selector, context, results, seed ) { results = results || []; context = context || document; var origContext = context; if ( context.nodeType !== 1 && context.nodeType !== 9 ) { return []; } if ( !selector || typeof selector !== "string" ) { return results; } var m, set, checkSet, extra, ret, cur, pop, i, prune = true, contextXML = Sizzle.isXML( context ), parts = [], soFar = selector; // Reset the position of the chunker regexp (start from head) do { chunker.exec( "" ); m = chunker.exec( soFar ); if ( m ) { soFar = m[3]; parts.push( m[1] ); if ( m[2] ) { extra = m[3]; break; } } } while ( m ); if ( parts.length > 1 && origPOS.exec( selector ) ) { if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { set = posProcess( parts[0] + parts[1], context, seed ); } else { set = Expr.relative[ parts[0] ] ? [ context ] : Sizzle( parts.shift(), context ); while ( parts.length ) { selector = parts.shift(); if ( Expr.relative[ selector ] ) { selector += parts.shift(); } set = posProcess( selector, set, seed ); } } } else { // Take a shortcut and set the context if the root selector is an ID // (but not if it'll be faster if the inner selector is an ID) if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { ret = Sizzle.find( parts.shift(), context, contextXML ); context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0]; } if ( context ) { ret = seed ? { expr: parts.pop(), set: makeArray(seed) } : Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); set = ret.expr ? Sizzle.filter( ret.expr, ret.set ) : ret.set; if ( parts.length > 0 ) { checkSet = makeArray( set ); } else { prune = false; } while ( parts.length ) { cur = parts.pop(); pop = cur; if ( !Expr.relative[ cur ] ) { cur = ""; } else { pop = parts.pop(); } if ( pop == null ) { pop = context; } Expr.relative[ cur ]( checkSet, pop, contextXML ); } } else { checkSet = parts = []; } } if ( !checkSet ) { checkSet = set; } if ( !checkSet ) { Sizzle.error( cur || selector ); } if ( toString.call(checkSet) === "[object Array]" ) { if ( !prune ) { results.push.apply( results, checkSet ); } else if ( context && context.nodeType === 1 ) { for ( i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) { results.push( set[i] ); } } } else { for ( i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && checkSet[i].nodeType === 1 ) { results.push( set[i] ); } } } } else { makeArray( checkSet, results ); } if ( extra ) { Sizzle( extra, origContext, results, seed ); Sizzle.uniqueSort( results ); } return results; }; Sizzle.uniqueSort = function( results ) { if ( sortOrder ) { hasDuplicate = baseHasDuplicate; results.sort( sortOrder ); if ( hasDuplicate ) { for ( var i = 1; i < results.length; i++ ) { if ( results[i] === results[ i - 1 ] ) { results.splice( i--, 1 ); } } } } return results; }; Sizzle.matches = function( expr, set ) { return Sizzle( expr, null, null, set ); }; Sizzle.matchesSelector = function( node, expr ) { return Sizzle( expr, null, null, [node] ).length > 0; }; Sizzle.find = function( expr, context, isXML ) { var set, i, len, match, type, left; if ( !expr ) { return []; } for ( i = 0, len = Expr.order.length; i < len; i++ ) { type = Expr.order[i]; if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { left = match[1]; match.splice( 1, 1 ); if ( left.substr( left.length - 1 ) !== "\\" ) { match[1] = (match[1] || "").replace( rBackslash, "" ); set = Expr.find[ type ]( match, context, isXML ); if ( set != null ) { expr = expr.replace( Expr.match[ type ], "" ); break; } } } } if ( !set ) { set = typeof context.getElementsByTagName !== "undefined" ? context.getElementsByTagName( "*" ) : []; } return { set: set, expr: expr }; }; Sizzle.filter = function( expr, set, inplace, not ) { var match, anyFound, type, found, item, filter, left, i, pass, old = expr, result = [], curLoop = set, isXMLFilter = set && set[0] && Sizzle.isXML( set[0] ); while ( expr && set.length ) { for ( type in Expr.filter ) { if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { filter = Expr.filter[ type ]; left = match[1]; anyFound = false; match.splice(1,1); if ( left.substr( left.length - 1 ) === "\\" ) { continue; } if ( curLoop === result ) { result = []; } if ( Expr.preFilter[ type ] ) { match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); if ( !match ) { anyFound = found = true; } else if ( match === true ) { continue; } } if ( match ) { for ( i = 0; (item = curLoop[i]) != null; i++ ) { if ( item ) { found = filter( item, match, i, curLoop ); pass = not ^ found; if ( inplace && found != null ) { if ( pass ) { anyFound = true; } else { curLoop[i] = false; } } else if ( pass ) { result.push( item ); anyFound = true; } } } } if ( found !== undefined ) { if ( !inplace ) { curLoop = result; } expr = expr.replace( Expr.match[ type ], "" ); if ( !anyFound ) { return []; } break; } } } // Improper expression if ( expr === old ) { if ( anyFound == null ) { Sizzle.error( expr ); } else { break; } } old = expr; } return curLoop; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; var getText = Sizzle.getText = function( elem ) { var i, node, nodeType = elem.nodeType, ret = ""; if ( nodeType ) { if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent || innerText for elements if ( typeof elem.textContent === 'string' ) { return elem.textContent; } else if ( typeof elem.innerText === 'string' ) { // Replace IE's carriage returns return elem.innerText.replace( rReturn, '' ); } else { // Traverse it's children for ( elem = elem.firstChild; elem; elem = elem.nextSibling) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } } else { // If no nodeType, this is expected to be an array for ( i = 0; (node = elem[i]); i++ ) { // Do not traverse comment nodes if ( node.nodeType !== 8 ) { ret += getText( node ); } } } return ret; }; var Expr = Sizzle.selectors = { order: [ "ID", "NAME", "TAG" ], match: { ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/, ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/, TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/, POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/, PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ }, leftMatch: {}, attrMap: { "class": "className", "for": "htmlFor" }, attrHandle: { href: function( elem ) { return elem.getAttribute( "href" ); }, type: function( elem ) { return elem.getAttribute( "type" ); } }, relative: { "+": function(checkSet, part){ var isPartStr = typeof part === "string", isTag = isPartStr && !rNonWord.test( part ), isPartStrNotTag = isPartStr && !isTag; if ( isTag ) { part = part.toLowerCase(); } for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { if ( (elem = checkSet[i]) ) { while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? elem || false : elem === part; } } if ( isPartStrNotTag ) { Sizzle.filter( part, checkSet, true ); } }, ">": function( checkSet, part ) { var elem, isPartStr = typeof part === "string", i = 0, l = checkSet.length; if ( isPartStr && !rNonWord.test( part ) ) { part = part.toLowerCase(); for ( ; i < l; i++ ) { elem = checkSet[i]; if ( elem ) { var parent = elem.parentNode; checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; } } } else { for ( ; i < l; i++ ) { elem = checkSet[i]; if ( elem ) { checkSet[i] = isPartStr ? elem.parentNode : elem.parentNode === part; } } if ( isPartStr ) { Sizzle.filter( part, checkSet, true ); } } }, "": function(checkSet, part, isXML){ var nodeCheck, doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !rNonWord.test( part ) ) { part = part.toLowerCase(); nodeCheck = part; checkFn = dirNodeCheck; } checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML ); }, "~": function( checkSet, part, isXML ) { var nodeCheck, doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !rNonWord.test( part ) ) { part = part.toLowerCase(); nodeCheck = part; checkFn = dirNodeCheck; } checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML ); } }, find: { ID: function( match, context, isXML ) { if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }, NAME: function( match, context ) { if ( typeof context.getElementsByName !== "undefined" ) { var ret = [], results = context.getElementsByName( match[1] ); for ( var i = 0, l = results.length; i < l; i++ ) { if ( results[i].getAttribute("name") === match[1] ) { ret.push( results[i] ); } } return ret.length === 0 ? null : ret; } }, TAG: function( match, context ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( match[1] ); } } }, preFilter: { CLASS: function( match, curLoop, inplace, result, not, isXML ) { match = " " + match[1].replace( rBackslash, "" ) + " "; if ( isXML ) { return match; } for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { if ( elem ) { if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) { if ( !inplace ) { result.push( elem ); } } else if ( inplace ) { curLoop[i] = false; } } } return false; }, ID: function( match ) { return match[1].replace( rBackslash, "" ); }, TAG: function( match, curLoop ) { return match[1].replace( rBackslash, "" ).toLowerCase(); }, CHILD: function( match ) { if ( match[1] === "nth" ) { if ( !match[2] ) { Sizzle.error( match[0] ); } match[2] = match[2].replace(/^\+|\s*/g, ''); // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec( match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); // calculate the numbers (first)n+(last) including if they are negative match[2] = (test[1] + (test[2] || 1)) - 0; match[3] = test[3] - 0; } else if ( match[2] ) { Sizzle.error( match[0] ); } // TODO: Move to normal caching system match[0] = done++; return match; }, ATTR: function( match, curLoop, inplace, result, not, isXML ) { var name = match[1] = match[1].replace( rBackslash, "" ); if ( !isXML && Expr.attrMap[name] ) { match[1] = Expr.attrMap[name]; } // Handle if an un-quoted value was used match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" ); if ( match[2] === "~=" ) { match[4] = " " + match[4] + " "; } return match; }, PSEUDO: function( match, curLoop, inplace, result, not ) { if ( match[1] === "not" ) { // If we're dealing with a complex expression, or a simple one if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { match[3] = Sizzle(match[3], null, null, curLoop); } else { var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); if ( !inplace ) { result.push.apply( result, ret ); } return false; } } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { return true; } return match; }, POS: function( match ) { match.unshift( true ); return match; } }, filters: { enabled: function( elem ) { return elem.disabled === false && elem.type !== "hidden"; }, disabled: function( elem ) { return elem.disabled === true; }, checked: function( elem ) { return elem.checked === true; }, 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; }, parent: function( elem ) { return !!elem.firstChild; }, empty: function( elem ) { return !elem.firstChild; }, has: function( elem, i, match ) { return !!Sizzle( match[3], elem ).length; }, header: function( elem ) { return (/h\d/i).test( elem.nodeName ); }, text: function( elem ) { var attr = elem.getAttribute( "type" ), type = elem.type; // 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" && "text" === type && ( attr === type || attr === null ); }, radio: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type; }, checkbox: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type; }, file: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "file" === elem.type; }, password: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "password" === elem.type; }, submit: function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && "submit" === elem.type; }, image: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "image" === elem.type; }, reset: function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && "reset" === elem.type; }, button: function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && "button" === elem.type || name === "button"; }, input: function( elem ) { return (/input|select|textarea|button/i).test( elem.nodeName ); }, focus: function( elem ) { return elem === elem.ownerDocument.activeElement; } }, setFilters: { first: function( elem, i ) { return i === 0; }, last: function( elem, i, match, array ) { return i === array.length - 1; }, even: function( elem, i ) { return i % 2 === 0; }, odd: function( elem, i ) { return i % 2 === 1; }, lt: function( elem, i, match ) { return i < match[3] - 0; }, gt: function( elem, i, match ) { return i > match[3] - 0; }, nth: function( elem, i, match ) { return match[3] - 0 === i; }, eq: function( elem, i, match ) { return match[3] - 0 === i; } }, filter: { PSEUDO: function( elem, match, i, array ) { var name = match[1], filter = Expr.filters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } else if ( name === "contains" ) { return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0; } else if ( name === "not" ) { var not = match[3]; for ( var j = 0, l = not.length; j < l; j++ ) { if ( not[j] === elem ) { return false; } } return true; } else { Sizzle.error( name ); } }, CHILD: function( elem, match ) { var first, last, doneName, parent, cache, count, diff, type = match[1], node = elem; switch ( type ) { case "only": case "first": while ( (node = node.previousSibling) ) { if ( node.nodeType === 1 ) { return false; } } if ( type === "first" ) { return true; } node = elem; /* falls through */ case "last": while ( (node = node.nextSibling) ) { if ( node.nodeType === 1 ) { return false; } } return true; case "nth": first = match[2]; last = match[3]; if ( first === 1 && last === 0 ) { return true; } doneName = match[0]; parent = elem.parentNode; if ( parent && (parent[ expando ] !== doneName || !elem.nodeIndex) ) { count = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { node.nodeIndex = ++count; } } parent[ expando ] = doneName; } diff = elem.nodeIndex - last; if ( first === 0 ) { return diff === 0; } else { return ( diff % first === 0 && diff / first >= 0 ); } } }, ID: function( elem, match ) { return elem.nodeType === 1 && elem.getAttribute("id") === match; }, TAG: function( elem, match ) { return (match === "*" && elem.nodeType === 1) || !!elem.nodeName && elem.nodeName.toLowerCase() === match; }, CLASS: function( elem, match ) { return (" " + (elem.className || elem.getAttribute("class")) + " ") .indexOf( match ) > -1; }, ATTR: function( elem, match ) { var name = match[1], result = Sizzle.attr ? Sizzle.attr( elem, name ) : Expr.attrHandle[ name ] ? Expr.attrHandle[ name ]( elem ) : elem[ name ] != null ? elem[ name ] : elem.getAttribute( name ), value = result + "", type = match[2], check = match[4]; return result == null ? type === "!=" : !type && Sizzle.attr ? result != null : type === "=" ? value === check : type === "*=" ? value.indexOf(check) >= 0 : type === "~=" ? (" " + value + " ").indexOf(check) >= 0 : !check ? value && result !== false : type === "!=" ? value !== check : type === "^=" ? value.indexOf(check) === 0 : type === "$=" ? value.substr(value.length - check.length) === check : type === "|=" ? value === check || value.substr(0, check.length + 1) === check + "-" : false; }, POS: function( elem, match, i, array ) { var name = match[2], filter = Expr.setFilters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } } } }; var origPOS = Expr.match.POS, fescape = function(all, num){ return "\\" + (num - 0 + 1); }; for ( var type in Expr.match ) { Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) ); Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) ); } // Expose origPOS // "global" as in regardless of relation to brackets/parens Expr.match.globalPOS = origPOS; var makeArray = function( array, results ) { array = Array.prototype.slice.call( array, 0 ); if ( results ) { results.push.apply( results, array ); return results; } return array; }; // Perform a simple check to determine if the browser is capable of // converting a NodeList to an array using builtin methods. // Also verifies that the returned array holds DOM nodes // (which is not the case in the Blackberry browser) try { Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; // Provide a fallback method if it does not work } catch( e ) { makeArray = function( array, results ) { var i = 0, ret = results || []; if ( toString.call(array) === "[object Array]" ) { Array.prototype.push.apply( ret, array ); } else { if ( typeof array.length === "number" ) { for ( var l = array.length; i < l; i++ ) { ret.push( array[i] ); } } else { for ( ; array[i]; i++ ) { ret.push( array[i] ); } } } return ret; }; } var sortOrder, siblingCheck; if ( document.documentElement.compareDocumentPosition ) { sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { return a.compareDocumentPosition ? -1 : 1; } return a.compareDocumentPosition(b) & 4 ? -1 : 1; }; } else { sortOrder = function( a, b ) { // The nodes are identical, we can exit early if ( a === b ) { hasDuplicate = true; return 0; // Fallback to using sourceIndex (in IE) if it's available on both nodes } else if ( a.sourceIndex && b.sourceIndex ) { return a.sourceIndex - b.sourceIndex; } var al, bl, ap = [], bp = [], aup = a.parentNode, bup = b.parentNode, cur = aup; // If the nodes are siblings (or identical) we can do a quick check if ( aup === bup ) { return siblingCheck( a, b ); // If no parents were found then the nodes are disconnected } else if ( !aup ) { return -1; } else if ( !bup ) { return 1; } // Otherwise they're somewhere else in the tree so we need // to build up a full list of the parentNodes for comparison while ( cur ) { ap.unshift( cur ); cur = cur.parentNode; } cur = bup; while ( cur ) { bp.unshift( cur ); cur = cur.parentNode; } al = ap.length; bl = bp.length; // Start walking down the tree looking for a discrepancy for ( var i = 0; i < al && i < bl; i++ ) { if ( ap[i] !== bp[i] ) { return siblingCheck( ap[i], bp[i] ); } } // We ended someplace up the tree so do a sibling check return i === al ? siblingCheck( a, bp[i], -1 ) : siblingCheck( ap[i], b, 1 ); }; siblingCheck = function( a, b, ret ) { if ( a === b ) { return ret; } var cur = a.nextSibling; while ( cur ) { if ( cur === b ) { return -1; } cur = cur.nextSibling; } return 1; }; } // Check to see if the browser returns elements by name when // querying by getElementById (and provide a workaround) (function(){ // We're going to inject a fake input element with a specified name var form = document.createElement("div"), id = "script" + (new Date()).getTime(), root = document.documentElement; form.innerHTML = "<a name='" + id + "'/>"; // Inject it into the root element, check its status, and remove it quickly root.insertBefore( form, root.firstChild ); // The workaround has to do additional checks after a getElementById // Which slows things down for other browsers (hence the branching) if ( document.getElementById( id ) ) { Expr.find.ID = function( match, context, isXML ) { if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : []; } }; Expr.filter.ID = function( elem, match ) { var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return elem.nodeType === 1 && node && node.nodeValue === match; }; } root.removeChild( form ); // release memory in IE root = form = null; })(); (function(){ // Check to see if the browser returns only elements // when doing getElementsByTagName("*") // Create a fake element var div = document.createElement("div"); div.appendChild( document.createComment("") ); // Make sure no comments are found if ( div.getElementsByTagName("*").length > 0 ) { Expr.find.TAG = function( match, context ) { var results = context.getElementsByTagName( match[1] ); // Filter out possible comments if ( match[1] === "*" ) { var tmp = []; for ( var i = 0; results[i]; i++ ) { if ( results[i].nodeType === 1 ) { tmp.push( results[i] ); } } results = tmp; } return results; }; } // Check to see if an attribute returns normalized href attributes div.innerHTML = "<a href='#'></a>"; if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && div.firstChild.getAttribute("href") !== "#" ) { Expr.attrHandle.href = function( elem ) { return elem.getAttribute( "href", 2 ); }; } // release memory in IE div = null; })(); if ( document.querySelectorAll ) { (function(){ var oldSizzle = Sizzle, div = document.createElement("div"), id = "__sizzle__"; div.innerHTML = "<p class='TEST'></p>"; // Safari can't handle uppercase or unicode characters when // in quirks mode. if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { return; } Sizzle = function( query, context, extra, seed ) { context = context || document; // Only use querySelectorAll on non-XML documents // (ID selectors don't work in non-HTML documents) if ( !seed && !Sizzle.isXML(context) ) { // See if we find a selector to speed up var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query ); if ( match && (context.nodeType === 1 || context.nodeType === 9) ) { // Speed-up: Sizzle("TAG") if ( match[1] ) { return makeArray( context.getElementsByTagName( query ), extra ); // Speed-up: Sizzle(".CLASS") } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) { return makeArray( context.getElementsByClassName( match[2] ), extra ); } } if ( context.nodeType === 9 ) { // Speed-up: Sizzle("body") // The body element only exists once, optimize finding it if ( query === "body" && context.body ) { return makeArray( [ context.body ], extra ); // Speed-up: Sizzle("#ID") } else if ( match && match[3] ) { var elem = context.getElementById( match[3] ); // 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 and Opera return items // by name instead of ID if ( elem.id === match[3] ) { return makeArray( [ elem ], extra ); } } else { return makeArray( [], extra ); } } try { return makeArray( context.querySelectorAll(query), extra ); } catch(qsaError) {} // 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 } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { var oldContext = context, old = context.getAttribute( "id" ), nid = old || id, hasParent = context.parentNode, relativeHierarchySelector = /^\s*[+~]/.test( query ); if ( !old ) { context.setAttribute( "id", nid ); } else { nid = nid.replace( /'/g, "\\$&" ); } if ( relativeHierarchySelector && hasParent ) { context = context.parentNode; } try { if ( !relativeHierarchySelector || hasParent ) { return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra ); } } catch(pseudoError) { } finally { if ( !old ) { oldContext.removeAttribute( "id" ); } } } } return oldSizzle(query, context, extra, seed); }; for ( var prop in oldSizzle ) { Sizzle[ prop ] = oldSizzle[ prop ]; } // release memory in IE div = null; })(); } (function(){ var html = document.documentElement, matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector; if ( matches ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9 fails this) var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ), pseudoWorks = false; try { // This should fail with an exception // Gecko does not error, returns false instead matches.call( document.documentElement, "[test!='']:sizzle" ); } catch( pseudoError ) { pseudoWorks = true; } Sizzle.matchesSelector = function( node, expr ) { // Make sure that attribute selectors are quoted expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']"); if ( !Sizzle.isXML( node ) ) { try { if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) { var ret = matches.call( node, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || !disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9, so check for that node.document && node.document.nodeType !== 11 ) { return ret; } } } catch(e) {} } return Sizzle(expr, null, null, [node]).length > 0; }; } })(); (function(){ var div = document.createElement("div"); div.innerHTML = "<div class='test e'></div><div class='test'></div>"; // Opera can't find a second classname (in 9.6) // Also, make sure that getElementsByClassName actually exists if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { return; } // Safari caches class attributes, doesn't catch changes (in 3.2) div.lastChild.className = "e"; if ( div.getElementsByClassName("e").length === 1 ) { return; } Expr.order.splice(1, 0, "CLASS"); Expr.find.CLASS = function( match, context, isXML ) { if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { return context.getElementsByClassName(match[1]); } }; // release memory in IE div = null; })(); function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var match = false; elem = elem[dir]; while ( elem ) { if ( elem[ expando ] === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 && !isXML ){ elem[ expando ] = doneName; elem.sizset = i; } if ( elem.nodeName.toLowerCase() === cur ) { match = elem; break; } elem = elem[dir]; } checkSet[i] = match; } } } function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var match = false; elem = elem[dir]; while ( elem ) { if ( elem[ expando ] === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 ) { if ( !isXML ) { elem[ expando ] = doneName; elem.sizset = i; } if ( typeof cur !== "string" ) { if ( elem === cur ) { match = true; break; } } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { match = elem; break; } } elem = elem[dir]; } checkSet[i] = match; } } } if ( document.documentElement.contains ) { Sizzle.contains = function( a, b ) { return a !== b && (a.contains ? a.contains(b) : true); }; } else if ( document.documentElement.compareDocumentPosition ) { Sizzle.contains = function( a, b ) { return !!(a.compareDocumentPosition(b) & 16); }; } else { Sizzle.contains = function() { return false; }; } 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 : 0).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; var posProcess = function( selector, context, seed ) { var match, tmpSet = [], later = "", root = context.nodeType ? [context] : context; // Position selectors must be done after the filter // And so must :not(positional) so we move all PSEUDOs to the end while ( (match = Expr.match.PSEUDO.exec( selector )) ) { later += match[0]; selector = selector.replace( Expr.match.PSEUDO, "" ); } selector = Expr.relative[selector] ? selector + "*" : selector; for ( var i = 0, l = root.length; i < l; i++ ) { Sizzle( selector, root[i], tmpSet, seed ); } return Sizzle.filter( later, tmpSet ); }; // EXPOSE window.tinymce.dom.Sizzle = Sizzle; })(); (function(tinymce) { tinymce.dom.Element = function(id, settings) { var t = this, dom, el; t.settings = settings = settings || {}; t.id = id; t.dom = dom = settings.dom || tinymce.DOM; // Only IE leaks DOM references, this is a lot faster if (!tinymce.isIE) el = dom.get(t.id); tinymce.each( ('getPos,getRect,getParent,add,setStyle,getStyle,setStyles,' + 'setAttrib,setAttribs,getAttrib,addClass,removeClass,' + 'hasClass,getOuterHTML,setOuterHTML,remove,show,hide,' + 'isHidden,setHTML,get').split(/,/), function(k) { t[k] = function() { var a = [id], i; for (i = 0; i < arguments.length; i++) a.push(arguments[i]); a = dom[k].apply(dom, a); t.update(k); return a; }; } ); tinymce.extend(t, { on : function(n, f, s) { return tinymce.dom.Event.add(t.id, n, f, s); }, getXY : function() { return { x : parseInt(t.getStyle('left')), y : parseInt(t.getStyle('top')) }; }, getSize : function() { var n = dom.get(t.id); return { w : parseInt(t.getStyle('width') || n.clientWidth), h : parseInt(t.getStyle('height') || n.clientHeight) }; }, moveTo : function(x, y) { t.setStyles({left : x, top : y}); }, moveBy : function(x, y) { var p = t.getXY(); t.moveTo(p.x + x, p.y + y); }, resizeTo : function(w, h) { t.setStyles({width : w, height : h}); }, resizeBy : function(w, h) { var s = t.getSize(); t.resizeTo(s.w + w, s.h + h); }, update : function(k) { var b; if (tinymce.isIE6 && settings.blocker) { k = k || ''; // Ignore getters if (k.indexOf('get') === 0 || k.indexOf('has') === 0 || k.indexOf('is') === 0) return; // Remove blocker on remove if (k == 'remove') { dom.remove(t.blocker); return; } if (!t.blocker) { t.blocker = dom.uniqueId(); b = dom.add(settings.container || dom.getRoot(), 'iframe', {id : t.blocker, style : 'position:absolute;', frameBorder : 0, src : 'javascript:""'}); dom.setStyle(b, 'opacity', 0); } else b = dom.get(t.blocker); dom.setStyles(b, { left : t.getStyle('left', 1), top : t.getStyle('top', 1), width : t.getStyle('width', 1), height : t.getStyle('height', 1), display : t.getStyle('display', 1), zIndex : parseInt(t.getStyle('zIndex', 1) || 0) - 1 }); } } }); }; })(tinymce); (function(tinymce) { function trimNl(s) { return s.replace(/[\n\r]+/g, ''); }; // Shorten names var is = tinymce.is, isIE = tinymce.isIE, each = tinymce.each, TreeWalker = tinymce.dom.TreeWalker; tinymce.create('tinymce.dom.Selection', { Selection : function(dom, win, serializer) { var t = this; t.dom = dom; t.win = win; t.serializer = serializer; // Add events each([ 'onBeforeSetContent', 'onBeforeGetContent', 'onSetContent', 'onGetContent' ], function(e) { t[e] = new tinymce.util.Dispatcher(t); }); // No W3C Range support if (!t.win.getSelection) t.tridentSel = new tinymce.dom.TridentSelection(t); if (tinymce.isIE && dom.boxModel) this._fixIESelection(); // Prevent leaks tinymce.addUnload(t.destroy, t); }, setCursorLocation: function(node, offset) { var t = this; var r = t.dom.createRng(); r.setStart(node, offset); r.setEnd(node, offset); t.setRng(r); t.collapse(false); }, getContent : function(s) { var t = this, r = t.getRng(), e = t.dom.create("body"), se = t.getSel(), wb, wa, n; s = s || {}; wb = wa = ''; s.get = true; s.format = s.format || 'html'; s.forced_root_block = ''; t.onBeforeGetContent.dispatch(t, s); if (s.format == 'text') return t.isCollapsed() ? '' : (r.text || (se.toString ? se.toString() : '')); if (r.cloneContents) { n = r.cloneContents(); if (n) e.appendChild(n); } else if (is(r.item) || is(r.htmlText)) { // IE will produce invalid markup if elements are present that // it doesn't understand like custom elements or HTML5 elements. // Adding a BR in front of the contents and then remoiving it seems to fix it though. e.innerHTML = '<br>' + (r.item ? r.item(0).outerHTML : r.htmlText); e.removeChild(e.firstChild); } else e.innerHTML = r.toString(); // Keep whitespace before and after if (/^\s/.test(e.innerHTML)) wb = ' '; if (/\s+$/.test(e.innerHTML)) wa = ' '; s.getInner = true; s.content = t.isCollapsed() ? '' : wb + t.serializer.serialize(e, s) + wa; t.onGetContent.dispatch(t, s); return s.content; }, setContent : function(content, args) { var self = this, rng = self.getRng(), caretNode, doc = self.win.document, frag, temp; args = args || {format : 'html'}; args.set = true; content = args.content = content; // Dispatch before set content event if (!args.no_events) self.onBeforeSetContent.dispatch(self, args); content = args.content; if (rng.insertNode) { // Make caret marker since insertNode places the caret in the beginning of text after insert content += '<span id="__caret">_</span>'; // Delete and insert new node if (rng.startContainer == doc && rng.endContainer == doc) { // WebKit will fail if the body is empty since the range is then invalid and it can't insert contents doc.body.innerHTML = content; } else { rng.deleteContents(); if (doc.body.childNodes.length === 0) { doc.body.innerHTML = content; } else { // createContextualFragment doesn't exists in IE 9 DOMRanges if (rng.createContextualFragment) { rng.insertNode(rng.createContextualFragment(content)); } else { // Fake createContextualFragment call in IE 9 frag = doc.createDocumentFragment(); temp = doc.createElement('div'); frag.appendChild(temp); temp.outerHTML = content; rng.insertNode(frag); } } } // Move to caret marker caretNode = self.dom.get('__caret'); // Make sure we wrap it compleatly, Opera fails with a simple select call rng = doc.createRange(); rng.setStartBefore(caretNode); rng.setEndBefore(caretNode); self.setRng(rng); // Remove the caret position self.dom.remove('__caret'); try { self.setRng(rng); } catch (ex) { // Might fail on Opera for some odd reason } } else { if (rng.item) { // Delete content and get caret text selection doc.execCommand('Delete', false, null); rng = self.getRng(); } // Explorer removes spaces from the beginning of pasted contents if (/^\s+/.test(content)) { rng.pasteHTML('<span id="__mce_tmp">_</span>' + content); self.dom.remove('__mce_tmp'); } else rng.pasteHTML(content); } // Dispatch set content event if (!args.no_events) self.onSetContent.dispatch(self, args); }, getStart : function() { var rng = this.getRng(), startElement, parentElement, checkRng, node; if (rng.duplicate || rng.item) { // Control selection, return first item if (rng.item) return rng.item(0); // Get start element checkRng = rng.duplicate(); checkRng.collapse(1); startElement = checkRng.parentElement(); // Check if range parent is inside the start element, then return the inner parent element // This will fix issues when a single element is selected, IE would otherwise return the wrong start element parentElement = node = rng.parentElement(); while (node = node.parentNode) { if (node == startElement) { startElement = parentElement; break; } } return startElement; } else { startElement = rng.startContainer; if (startElement.nodeType == 1 && startElement.hasChildNodes()) startElement = startElement.childNodes[Math.min(startElement.childNodes.length - 1, rng.startOffset)]; if (startElement && startElement.nodeType == 3) return startElement.parentNode; return startElement; } }, getEnd : function() { var t = this, r = t.getRng(), e, eo; if (r.duplicate || r.item) { if (r.item) return r.item(0); r = r.duplicate(); r.collapse(0); e = r.parentElement(); if (e && e.nodeName == 'BODY') return e.lastChild || e; return e; } else { e = r.endContainer; eo = r.endOffset; if (e.nodeType == 1 && e.hasChildNodes()) e = e.childNodes[eo > 0 ? eo - 1 : eo]; if (e && e.nodeType == 3) return e.parentNode; return e; } }, getBookmark : function(type, normalized) { var t = this, dom = t.dom, rng, rng2, id, collapsed, name, element, index, chr = '\uFEFF', styles; function findIndex(name, element) { var index = 0; each(dom.select(name), function(node, i) { if (node == element) index = i; }); return index; }; function getLocation() { var rng = t.getRng(true), root = dom.getRoot(), bookmark = {}; function getPoint(rng, start) { var container = rng[start ? 'startContainer' : 'endContainer'], offset = rng[start ? 'startOffset' : 'endOffset'], point = [], node, childNodes, after = 0; if (container.nodeType == 3) { if (normalized) { for (node = container.previousSibling; node && node.nodeType == 3; node = node.previousSibling) offset += node.nodeValue.length; } point.push(offset); } else { childNodes = container.childNodes; if (offset >= childNodes.length && childNodes.length) { after = 1; offset = Math.max(0, childNodes.length - 1); } point.push(t.dom.nodeIndex(childNodes[offset], normalized) + after); } for (; container && container != root; container = container.parentNode) point.push(t.dom.nodeIndex(container, normalized)); return point; }; bookmark.start = getPoint(rng, true); if (!t.isCollapsed()) bookmark.end = getPoint(rng); return bookmark; }; if (type == 2) { if (t.tridentSel) return t.tridentSel.getBookmark(type); return getLocation(); } // Handle simple range if (type) return {rng : t.getRng()}; rng = t.getRng(); id = dom.uniqueId(); collapsed = tinyMCE.activeEditor.selection.isCollapsed(); styles = 'overflow:hidden;line-height:0px'; // Explorer method if (rng.duplicate || rng.item) { // Text selection if (!rng.item) { rng2 = rng.duplicate(); try { // Insert start marker rng.collapse(); rng.pasteHTML('<span data-mce-type="bookmark" id="' + id + '_start" style="' + styles + '">' + chr + '</span>'); // Insert end marker if (!collapsed) { rng2.collapse(false); // Detect the empty space after block elements in IE and move the end back one character <p></p>] becomes <p>]</p> rng.moveToElementText(rng2.parentElement()); if (rng.compareEndPoints('StartToEnd', rng2) === 0) rng2.move('character', -1); rng2.pasteHTML('<span data-mce-type="bookmark" id="' + id + '_end" style="' + styles + '">' + chr + '</span>'); } } catch (ex) { // IE might throw unspecified error so lets ignore it return null; } } else { // Control selection element = rng.item(0); name = element.nodeName; return {name : name, index : findIndex(name, element)}; } } else { element = t.getNode(); name = element.nodeName; if (name == 'IMG') return {name : name, index : findIndex(name, element)}; // Can't insert a node into the root of document WebKit defaults to document if (rng.startContainer.nodeType == 9) { return; } // W3C method rng2 = rng.cloneRange(); // Insert end marker if (!collapsed) { rng2.collapse(false); rng2.insertNode(dom.create('span', {'data-mce-type' : "bookmark", id : id + '_end', style : styles}, chr)); } rng.collapse(true); rng.insertNode(dom.create('span', {'data-mce-type' : "bookmark", id : id + '_start', style : styles}, chr)); } t.moveToBookmark({id : id, keep : 1}); return {id : id}; }, moveToBookmark : function(bookmark) { var t = this, dom = t.dom, marker1, marker2, rng, root, startContainer, endContainer, startOffset, endOffset; function setEndPoint(start) { var point = bookmark[start ? 'start' : 'end'], i, node, offset, children; if (point) { offset = point[0]; // Find container node for (node = root, i = point.length - 1; i >= 1; i--) { children = node.childNodes; if (point[i] > children.length - 1) return; node = children[point[i]]; } // Move text offset to best suitable location if (node.nodeType === 3) offset = Math.min(point[0], node.nodeValue.length); // Move element offset to best suitable location if (node.nodeType === 1) offset = Math.min(point[0], node.childNodes.length); // Set offset within container node if (start) rng.setStart(node, offset); else rng.setEnd(node, offset); } return true; }; function restoreEndPoint(suffix) { var marker = dom.get(bookmark.id + '_' + suffix), node, idx, next, prev, keep = bookmark.keep; if (marker) { node = marker.parentNode; if (suffix == 'start') { if (!keep) { idx = dom.nodeIndex(marker); } else { node = marker.firstChild; idx = 1; } startContainer = endContainer = node; startOffset = endOffset = idx; } else { if (!keep) { idx = dom.nodeIndex(marker); } else { node = marker.firstChild; idx = 1; } endContainer = node; endOffset = idx; } if (!keep) { prev = marker.previousSibling; next = marker.nextSibling; // Remove all marker text nodes each(tinymce.grep(marker.childNodes), function(node) { if (node.nodeType == 3) node.nodeValue = node.nodeValue.replace(/\uFEFF/g, ''); }); // Remove marker but keep children if for example contents where inserted into the marker // Also remove duplicated instances of the marker for example by a split operation or by WebKit auto split on paste feature while (marker = dom.get(bookmark.id + '_' + suffix)) dom.remove(marker, 1); // If siblings are text nodes then merge them unless it's Opera since it some how removes the node // and we are sniffing since adding a lot of detection code for a browser with 3% of the market isn't worth the effort. Sorry, Opera but it's just a fact if (prev && next && prev.nodeType == next.nodeType && prev.nodeType == 3 && !tinymce.isOpera) { idx = prev.nodeValue.length; prev.appendData(next.nodeValue); dom.remove(next); if (suffix == 'start') { startContainer = endContainer = prev; startOffset = endOffset = idx; } else { endContainer = prev; endOffset = idx; } } } } }; function addBogus(node) { // Adds a bogus BR element for empty block elements if (dom.isBlock(node) && !node.innerHTML && !isIE) node.innerHTML = '<br data-mce-bogus="1" />'; return node; }; if (bookmark) { if (bookmark.start) { rng = dom.createRng(); root = dom.getRoot(); if (t.tridentSel) return t.tridentSel.moveToBookmark(bookmark); if (setEndPoint(true) && setEndPoint()) { t.setRng(rng); } } else if (bookmark.id) { // Restore start/end points restoreEndPoint('start'); restoreEndPoint('end'); if (startContainer) { rng = dom.createRng(); rng.setStart(addBogus(startContainer), startOffset); rng.setEnd(addBogus(endContainer), endOffset); t.setRng(rng); } } else if (bookmark.name) { t.select(dom.select(bookmark.name)[bookmark.index]); } else if (bookmark.rng) t.setRng(bookmark.rng); } }, select : function(node, content) { var t = this, dom = t.dom, rng = dom.createRng(), idx; function setPoint(node, start) { var walker = new TreeWalker(node, node); do { // Text node if (node.nodeType == 3 && tinymce.trim(node.nodeValue).length !== 0) { if (start) rng.setStart(node, 0); else rng.setEnd(node, node.nodeValue.length); return; } // BR element if (node.nodeName == 'BR') { if (start) rng.setStartBefore(node); else rng.setEndBefore(node); return; } } while (node = (start ? walker.next() : walker.prev())); }; if (node) { idx = dom.nodeIndex(node); rng.setStart(node.parentNode, idx); rng.setEnd(node.parentNode, idx + 1); // Find first/last text node or BR element if (content) { setPoint(node, 1); setPoint(node); } t.setRng(rng); } return node; }, isCollapsed : function() { var t = this, r = t.getRng(), s = t.getSel(); if (!r || r.item) return false; if (r.compareEndPoints) return r.compareEndPoints('StartToEnd', r) === 0; return !s || r.collapsed; }, collapse : function(to_start) { var self = this, rng = self.getRng(), node; // Control range on IE if (rng.item) { node = rng.item(0); rng = self.win.document.body.createTextRange(); rng.moveToElementText(node); } rng.collapse(!!to_start); self.setRng(rng); }, getSel : function() { var t = this, w = this.win; return w.getSelection ? w.getSelection() : w.document.selection; }, getRng : function(w3c) { var t = this, s, r, elm, doc = t.win.document; // Found tridentSel object then we need to use that one if (w3c && t.tridentSel) return t.tridentSel.getRangeAt(0); try { if (s = t.getSel()) r = s.rangeCount > 0 ? s.getRangeAt(0) : (s.createRange ? s.createRange() : doc.createRange()); } catch (ex) { // IE throws unspecified error here if TinyMCE is placed in a frame/iframe } // We have W3C ranges and it's IE then fake control selection since IE9 doesn't handle that correctly yet if (tinymce.isIE && r && r.setStart && doc.selection.createRange().item) { elm = doc.selection.createRange().item(0); r = doc.createRange(); r.setStartBefore(elm); r.setEndAfter(elm); } // No range found then create an empty one // This can occur when the editor is placed in a hidden container element on Gecko // Or on IE when there was an exception if (!r) r = doc.createRange ? doc.createRange() : doc.body.createTextRange(); if (t.selectedRange && t.explicitRange) { if (r.compareBoundaryPoints(r.START_TO_START, t.selectedRange) === 0 && r.compareBoundaryPoints(r.END_TO_END, t.selectedRange) === 0) { // Safari, Opera and Chrome only ever select text which causes the range to change. // This lets us use the originally set range if the selection hasn't been changed by the user. r = t.explicitRange; } else { t.selectedRange = null; t.explicitRange = null; } } return r; }, setRng : function(r) { var s, t = this; if (!t.tridentSel) { s = t.getSel(); if (s) { t.explicitRange = r; try { s.removeAllRanges(); } catch (ex) { // IE9 might throw errors here don't know why } s.addRange(r); // adding range isn't always successful so we need to check range count otherwise an exception can occur t.selectedRange = s.rangeCount > 0 ? s.getRangeAt(0) : null; } } else { // Is W3C Range if (r.cloneRange) { try { t.tridentSel.addRange(r); return; } catch (ex) { //IE9 throws an error here if called before selection is placed in the editor } } // Is IE specific range try { r.select(); } catch (ex) { // Needed for some odd IE bug #1843306 } } }, setNode : function(n) { var t = this; t.setContent(t.dom.getOuterHTML(n)); return n; }, getNode : function() { var t = this, rng = t.getRng(), sel = t.getSel(), elm, start = rng.startContainer, end = rng.endContainer; function skipEmptyTextNodes(n, forwards) { var orig = n; while (n && n.nodeType === 3 && n.length === 0) { n = forwards ? n.nextSibling : n.previousSibling; } return n || orig; }; // Range maybe lost after the editor is made visible again if (!rng) return t.dom.getRoot(); if (rng.setStart) { elm = rng.commonAncestorContainer; // Handle selection a image or other control like element such as anchors if (!rng.collapsed) { if (rng.startContainer == rng.endContainer) { if (rng.endOffset - rng.startOffset < 2) { if (rng.startContainer.hasChildNodes()) elm = rng.startContainer.childNodes[rng.startOffset]; } } // If the anchor node is a element instead of a text node then return this element //if (tinymce.isWebKit && sel.anchorNode && sel.anchorNode.nodeType == 1) // return sel.anchorNode.childNodes[sel.anchorOffset]; // Handle cases where the selection is immediately wrapped around a node and return that node instead of it's parent. // This happens when you double click an underlined word in FireFox. if (start.nodeType === 3 && end.nodeType === 3) { if (start.length === rng.startOffset) { start = skipEmptyTextNodes(start.nextSibling, true); } else { start = start.parentNode; } if (rng.endOffset === 0) { end = skipEmptyTextNodes(end.previousSibling, false); } else { end = end.parentNode; } if (start && start === end) return start; } } if (elm && elm.nodeType == 3) return elm.parentNode; return elm; } return rng.item ? rng.item(0) : rng.parentElement(); }, getSelectedBlocks : function(st, en) { var t = this, dom = t.dom, sb, eb, n, bl = []; sb = dom.getParent(st || t.getStart(), dom.isBlock); eb = dom.getParent(en || t.getEnd(), dom.isBlock); if (sb) bl.push(sb); if (sb && eb && sb != eb) { n = sb; var walker = new TreeWalker(sb, dom.getRoot()); while ((n = walker.next()) && n != eb) { if (dom.isBlock(n)) bl.push(n); } } if (eb && sb != eb) bl.push(eb); return bl; }, normalize : function() { var self = this, rng, normalized, collapsed; function normalizeEndPoint(start) { var container, offset, walker, dom = self.dom, body = dom.getRoot(), node, nonEmptyElementsMap, nodeName; // Walks the dom left/right to find a suitable text node to move the endpoint into // It will only walk within the current parent block or body and will stop if it hits a block or a BR/IMG function findTextNodeRelative(left, startNode) { var walker, lastInlineElement; startNode = startNode || container; walker = new TreeWalker(startNode, dom.getParent(startNode.parentNode, dom.isBlock) || body); // Walk left until we hit a text node we can move to or a block/br/img while (node = walker[left ? 'prev' : 'next']()) { // Found text node that has a length if (node.nodeType === 3 && node.nodeValue.length > 0) { container = node; offset = left ? node.nodeValue.length : 0; normalized = true; return; } // Break if we find a block or a BR/IMG/INPUT etc if (dom.isBlock(node) || nonEmptyElementsMap[node.nodeName.toLowerCase()]) { return; } lastInlineElement = node; } // Only fetch the last inline element when in caret mode for now if (collapsed && lastInlineElement) { container = lastInlineElement; normalized = true; offset = 0; } }; container = rng[(start ? 'start' : 'end') + 'Container']; offset = rng[(start ? 'start' : 'end') + 'Offset']; nonEmptyElementsMap = dom.schema.getNonEmptyElements(); // If the container is a document move it to the body element if (container.nodeType === 9) { container = container.body; offset = 0; } // If the container is body try move it into the closest text node or position if (container === body) { // If start is before/after a image, table etc if (start) { node = container.childNodes[offset > 0 ? offset - 1 : 0]; if (node) { nodeName = node.nodeName.toLowerCase(); if (nonEmptyElementsMap[node.nodeName] || node.nodeName == "TABLE") { return; } } } // Resolve the index if (container.hasChildNodes()) { container = container.childNodes[Math.min(!start && offset > 0 ? offset - 1 : offset, container.childNodes.length - 1)]; offset = 0; // Don't walk into elements that doesn't have any child nodes like a IMG if (container.hasChildNodes()) { // Walk the DOM to find a text node to place the caret at or a BR node = container; walker = new TreeWalker(container, body); do { // Found a text node use that position if (node.nodeType === 3 && node.nodeValue.length > 0) { offset = start ? 0 : node.nodeValue.length; container = node; normalized = true; break; } // Found a BR/IMG element that we can place the caret before if (nonEmptyElementsMap[node.nodeName.toLowerCase()]) { offset = dom.nodeIndex(node); container = node.parentNode; // Put caret after image when moving the end point if (node.nodeName == "IMG" && !start) { offset++; } normalized = true; break; } } while (node = (start ? walker.next() : walker.prev())); } } } // Lean the caret to the left if possible if (collapsed) { // So this: <b>x</b><i>|x</i> // Becomes: <b>x|</b><i>x</i> // Seems that only gecko has issues with this if (container.nodeType === 3 && offset === 0) { findTextNodeRelative(true); } // Lean left into empty inline elements when the caret is before a BR // So this: <i><b></b><i>|<br></i> // Becomes: <i><b>|</b><i><br></i> // Seems that only gecko has issues with this if (container.nodeType === 1 && container.childNodes[offset] && container.childNodes[offset].nodeName === 'BR') { findTextNodeRelative(true, container.childNodes[offset]); } } // Lean the start of the selection right if possible // So this: x[<b>x]</b> // Becomes: x<b>[x]</b> if (start && !collapsed && container.nodeType === 3 && offset === container.nodeValue.length) { findTextNodeRelative(false); } // Set endpoint if it was normalized if (normalized) rng['set' + (start ? 'Start' : 'End')](container, offset); }; // TODO: // Retain selection direction. // Normalize only on non IE browsers for now if (tinymce.isIE) return; rng = self.getRng(); collapsed = rng.collapsed; // Normalize the end points normalizeEndPoint(true); if (!collapsed) normalizeEndPoint(); // Set the selection if it was normalized if (normalized) { // If it was collapsed then make sure it still is if (collapsed) { rng.collapse(true); } //console.log(self.dom.dumpRng(rng)); self.setRng(rng); } }, destroy : function(s) { var t = this; t.win = null; // Manual destroy then remove unload handler if (!s) tinymce.removeUnload(t.destroy); }, // IE has an issue where you can't select/move the caret by clicking outside the body if the document is in standards mode _fixIESelection : function() { var dom = this.dom, doc = dom.doc, body = doc.body, started, startRng, htmlElm; // Return range from point or null if it failed function rngFromPoint(x, y) { var rng = body.createTextRange(); try { rng.moveToPoint(x, y); } catch (ex) { // IE sometimes throws and exception, so lets just ignore it rng = null; } return rng; }; // Fires while the selection is changing function selectionChange(e) { var pointRng; // Check if the button is down or not if (e.button) { // Create range from mouse position pointRng = rngFromPoint(e.x, e.y); if (pointRng) { // Check if pointRange is before/after selection then change the endPoint if (pointRng.compareEndPoints('StartToStart', startRng) > 0) pointRng.setEndPoint('StartToStart', startRng); else pointRng.setEndPoint('EndToEnd', startRng); pointRng.select(); } } else endSelection(); } // Removes listeners function endSelection() { var rng = doc.selection.createRange(); // If the range is collapsed then use the last start range if (startRng && !rng.item && rng.compareEndPoints('StartToEnd', rng) === 0) startRng.select(); dom.unbind(doc, 'mouseup', endSelection); dom.unbind(doc, 'mousemove', selectionChange); startRng = started = 0; }; // Make HTML element unselectable since we are going to handle selection by hand doc.documentElement.unselectable = true; // Detect when user selects outside BODY dom.bind(doc, ['mousedown', 'contextmenu'], function(e) { if (e.target.nodeName === 'HTML') { if (started) endSelection(); // Detect vertical scrollbar, since IE will fire a mousedown on the scrollbar and have target set as HTML htmlElm = doc.documentElement; if (htmlElm.scrollHeight > htmlElm.clientHeight) return; started = 1; // Setup start position startRng = rngFromPoint(e.x, e.y); if (startRng) { // Listen for selection change events dom.bind(doc, 'mouseup', endSelection); dom.bind(doc, 'mousemove', selectionChange); dom.win.focus(); startRng.select(); } } }); } }); })(tinymce); (function(tinymce) { tinymce.dom.Serializer = function(settings, dom, schema) { var onPreProcess, onPostProcess, isIE = tinymce.isIE, each = tinymce.each, htmlParser; // Support the old apply_source_formatting option if (!settings.apply_source_formatting) settings.indent = false; // Default DOM and Schema if they are undefined dom = dom || tinymce.DOM; schema = schema || new tinymce.html.Schema(settings); settings.entity_encoding = settings.entity_encoding || 'named'; settings.remove_trailing_brs = "remove_trailing_brs" in settings ? settings.remove_trailing_brs : true; onPreProcess = new tinymce.util.Dispatcher(self); onPostProcess = new tinymce.util.Dispatcher(self); htmlParser = new tinymce.html.DomParser(settings, schema); // Convert move data-mce-src, data-mce-href and data-mce-style into nodes or process them if needed htmlParser.addAttributeFilter('src,href,style', function(nodes, name) { var i = nodes.length, node, value, internalName = 'data-mce-' + name, urlConverter = settings.url_converter, urlConverterScope = settings.url_converter_scope, undef; while (i--) { node = nodes[i]; value = node.attributes.map[internalName]; if (value !== undef) { // Set external name to internal value and remove internal node.attr(name, value.length > 0 ? value : null); node.attr(internalName, null); } else { // No internal attribute found then convert the value we have in the DOM value = node.attributes.map[name]; if (name === "style") value = dom.serializeStyle(dom.parseStyle(value), node.name); else if (urlConverter) value = urlConverter.call(urlConverterScope, value, name, node.name); node.attr(name, value.length > 0 ? value : null); } } }); // Remove internal classes mceItem<..> htmlParser.addAttributeFilter('class', function(nodes, name) { var i = nodes.length, node, value; while (i--) { node = nodes[i]; value = node.attr('class').replace(/\s*mce(Item\w+|Selected)\s*/g, ''); node.attr('class', value.length > 0 ? value : null); } }); // Remove bookmark elements htmlParser.addAttributeFilter('data-mce-type', function(nodes, name, args) { var i = nodes.length, node; while (i--) { node = nodes[i]; if (node.attributes.map['data-mce-type'] === 'bookmark' && !args.cleanup) node.remove(); } }); // Remove expando attributes htmlParser.addAttributeFilter('data-mce-expando', function(nodes, name, args) { var i = nodes.length; while (i--) { nodes[i].attr(name, null); } }); // Force script into CDATA sections and remove the mce- prefix also add comments around styles htmlParser.addNodeFilter('script,style', function(nodes, name) { var i = nodes.length, node, value; function trim(value) { return value.replace(/(<!--\[CDATA\[|\]\]-->)/g, '\n') .replace(/^[\r\n]*|[\r\n]*$/g, '') .replace(/^\s*((<!--)?(\s*\/\/)?\s*<!\[CDATA\[|(<!--\s*)?\/\*\s*<!\[CDATA\[\s*\*\/|(\/\/)?\s*<!--|\/\*\s*<!--\s*\*\/)\s*[\r\n]*/gi, '') .replace(/\s*(\/\*\s*\]\]>\s*\*\/(-->)?|\s*\/\/\s*\]\]>(-->)?|\/\/\s*(-->)?|\]\]>|\/\*\s*-->\s*\*\/|\s*-->\s*)\s*$/g, ''); }; while (i--) { node = nodes[i]; value = node.firstChild ? node.firstChild.value : ''; if (name === "script") { // Remove mce- prefix from script elements node.attr('type', (node.attr('type') || 'text/javascript').replace(/^mce\-/, '')); if (value.length > 0) node.firstChild.value = '// <![CDATA[\n' + trim(value) + '\n// ]]>'; } else { if (value.length > 0) node.firstChild.value = '<!--\n' + trim(value) + '\n-->'; } } }); // Convert comments to cdata and handle protected comments htmlParser.addNodeFilter('#comment', function(nodes, name) { var i = nodes.length, node; while (i--) { node = nodes[i]; if (node.value.indexOf('[CDATA[') === 0) { node.name = '#cdata'; node.type = 4; node.value = node.value.replace(/^\[CDATA\[|\]\]$/g, ''); } else if (node.value.indexOf('mce:protected ') === 0) { node.name = "#text"; node.type = 3; node.raw = true; node.value = unescape(node.value).substr(14); } } }); htmlParser.addNodeFilter('xml:namespace,input', function(nodes, name) { var i = nodes.length, node; while (i--) { node = nodes[i]; if (node.type === 7) node.remove(); else if (node.type === 1) { if (name === "input" && !("type" in node.attributes.map)) node.attr('type', 'text'); } } }); // Fix list elements, TODO: Replace this later if (settings.fix_list_elements) { htmlParser.addNodeFilter('ul,ol', function(nodes, name) { var i = nodes.length, node, parentNode; while (i--) { node = nodes[i]; parentNode = node.parent; if (parentNode.name === 'ul' || parentNode.name === 'ol') { if (node.prev && node.prev.name === 'li') { node.prev.append(node); } } } }); } // Remove internal data attributes htmlParser.addAttributeFilter('data-mce-src,data-mce-href,data-mce-style', function(nodes, name) { var i = nodes.length; while (i--) { nodes[i].attr(name, null); } }); // Return public methods return { schema : schema, addNodeFilter : htmlParser.addNodeFilter, addAttributeFilter : htmlParser.addAttributeFilter, onPreProcess : onPreProcess, onPostProcess : onPostProcess, serialize : function(node, args) { var impl, doc, oldDoc, htmlSerializer, content; // Explorer won't clone contents of script and style and the // selected index of select elements are cleared on a clone operation. if (isIE && dom.select('script,style,select,map').length > 0) { content = node.innerHTML; node = node.cloneNode(false); dom.setHTML(node, content); } else node = node.cloneNode(true); // Nodes needs to be attached to something in WebKit/Opera // Older builds of Opera crashes if you attach the node to an document created dynamically // and since we can't feature detect a crash we need to sniff the acutal build number // This fix will make DOM ranges and make Sizzle happy! impl = node.ownerDocument.implementation; if (impl.createHTMLDocument) { // Create an empty HTML document doc = impl.createHTMLDocument(""); // Add the element or it's children if it's a body element to the new document each(node.nodeName == 'BODY' ? node.childNodes : [node], function(node) { doc.body.appendChild(doc.importNode(node, true)); }); // Grab first child or body element for serialization if (node.nodeName != 'BODY') node = doc.body.firstChild; else node = doc.body; // set the new document in DOMUtils so createElement etc works oldDoc = dom.doc; dom.doc = doc; } args = args || {}; args.format = args.format || 'html'; // Pre process if (!args.no_events) { args.node = node; onPreProcess.dispatch(self, args); } // Setup serializer htmlSerializer = new tinymce.html.Serializer(settings, schema); // Parse and serialize HTML args.content = htmlSerializer.serialize( htmlParser.parse(tinymce.trim(args.getInner ? node.innerHTML : dom.getOuterHTML(node)), args) ); // Replace all BOM characters for now until we can find a better solution if (!args.cleanup) args.content = args.content.replace(/\uFEFF|\u200B/g, ''); // Post process if (!args.no_events) onPostProcess.dispatch(self, args); // Restore the old document if it was changed if (oldDoc) dom.doc = oldDoc; args.node = null; return args.content; }, addRules : function(rules) { schema.addValidElements(rules); }, setRules : function(rules) { schema.setValidElements(rules); } }; }; })(tinymce); (function(tinymce) { tinymce.dom.ScriptLoader = function(settings) { var QUEUED = 0, LOADING = 1, LOADED = 2, states = {}, queue = [], scriptLoadedCallbacks = {}, queueLoadedCallbacks = [], loading = 0, undef; function loadScript(url, callback) { var t = this, dom = tinymce.DOM, elm, uri, loc, id; // Execute callback when script is loaded function done() { dom.remove(id); if (elm) elm.onreadystatechange = elm.onload = elm = null; callback(); }; function error() { // Report the error so it's easier for people to spot loading errors if (typeof(console) !== "undefined" && console.log) console.log("Failed to load: " + url); // We can't mark it as done if there is a load error since // A) We don't want to produce 404 errors on the server and // B) the onerror event won't fire on all browsers. // done(); }; id = dom.uniqueId(); if (tinymce.isIE6) { uri = new tinymce.util.URI(url); loc = location; // If script is from same domain and we // use IE 6 then use XHR since it's more reliable if (uri.host == loc.hostname && uri.port == loc.port && (uri.protocol + ':') == loc.protocol && uri.protocol.toLowerCase() != 'file') { tinymce.util.XHR.send({ url : tinymce._addVer(uri.getURI()), success : function(content) { // Create new temp script element var script = dom.create('script', { type : 'text/javascript' }); // Evaluate script in global scope script.text = content; document.getElementsByTagName('head')[0].appendChild(script); dom.remove(script); done(); }, error : error }); return; } } // Create new script element elm = dom.create('script', { id : id, type : 'text/javascript', src : tinymce._addVer(url) }); // Add onload listener for non IE browsers since IE9 // fires onload event before the script is parsed and executed if (!tinymce.isIE) elm.onload = done; // Add onerror event will get fired on some browsers but not all of them elm.onerror = error; // Opera 9.60 doesn't seem to fire the onreadystate event at correctly if (!tinymce.isOpera) { elm.onreadystatechange = function() { var state = elm.readyState; // Loaded state is passed on IE 6 however there // are known issues with this method but we can't use // XHR in a cross domain loading if (state == 'complete' || state == 'loaded') done(); }; } // Most browsers support this feature so we report errors // for those at least to help users track their missing plugins etc // todo: Removed since it produced error if the document is unloaded by navigating away, re-add it as an option /*elm.onerror = function() { alert('Failed to load: ' + url); };*/ // Add script to document (document.getElementsByTagName('head')[0] || document.body).appendChild(elm); }; this.isDone = function(url) { return states[url] == LOADED; }; this.markDone = function(url) { states[url] = LOADED; }; this.add = this.load = function(url, callback, scope) { var item, state = states[url]; // Add url to load queue if (state == undef) { queue.push(url); states[url] = QUEUED; } if (callback) { // Store away callback for later execution if (!scriptLoadedCallbacks[url]) scriptLoadedCallbacks[url] = []; scriptLoadedCallbacks[url].push({ func : callback, scope : scope || this }); } }; this.loadQueue = function(callback, scope) { this.loadScripts(queue, callback, scope); }; this.loadScripts = function(scripts, callback, scope) { var loadScripts; function execScriptLoadedCallbacks(url) { // Execute URL callback functions tinymce.each(scriptLoadedCallbacks[url], function(callback) { callback.func.call(callback.scope); }); scriptLoadedCallbacks[url] = undef; }; queueLoadedCallbacks.push({ func : callback, scope : scope || this }); loadScripts = function() { var loadingScripts = tinymce.grep(scripts); // Current scripts has been handled scripts.length = 0; // Load scripts that needs to be loaded tinymce.each(loadingScripts, function(url) { // Script is already loaded then execute script callbacks directly if (states[url] == LOADED) { execScriptLoadedCallbacks(url); return; } // Is script not loading then start loading it if (states[url] != LOADING) { states[url] = LOADING; loading++; loadScript(url, function() { states[url] = LOADED; loading--; execScriptLoadedCallbacks(url); // Load more scripts if they where added by the recently loaded script loadScripts(); }); } }); // No scripts are currently loading then execute all pending queue loaded callbacks if (!loading) { tinymce.each(queueLoadedCallbacks, function(callback) { callback.func.call(callback.scope); }); queueLoadedCallbacks.length = 0; } }; loadScripts(); }; }; // Global script loader tinymce.ScriptLoader = new tinymce.dom.ScriptLoader(); })(tinymce); (function(tinymce) { tinymce.dom.RangeUtils = function(dom) { var INVISIBLE_CHAR = '\uFEFF'; this.walk = function(rng, callback) { var startContainer = rng.startContainer, startOffset = rng.startOffset, endContainer = rng.endContainer, endOffset = rng.endOffset, ancestor, startPoint, endPoint, node, parent, siblings, nodes; // Handle table cell selection the table plugin enables // you to fake select table cells and perform formatting actions on them nodes = dom.select('td.mceSelected,th.mceSelected'); if (nodes.length > 0) { tinymce.each(nodes, function(node) { callback([node]); }); return; } function exclude(nodes) { var node; // First node is excluded node = nodes[0]; if (node.nodeType === 3 && node === startContainer && startOffset >= node.nodeValue.length) { nodes.splice(0, 1); } // Last node is excluded node = nodes[nodes.length - 1]; if (endOffset === 0 && nodes.length > 0 && node === endContainer && node.nodeType === 3) { nodes.splice(nodes.length - 1, 1); } return nodes; }; function collectSiblings(node, name, end_node) { var siblings = []; for (; node && node != end_node; node = node[name]) siblings.push(node); return siblings; }; function findEndPoint(node, root) { do { if (node.parentNode == root) return node; node = node.parentNode; } while(node); }; function walkBoundary(start_node, end_node, next) { var siblingName = next ? 'nextSibling' : 'previousSibling'; for (node = start_node, parent = node.parentNode; node && node != end_node; node = parent) { parent = node.parentNode; siblings = collectSiblings(node == start_node ? node : node[siblingName], siblingName); if (siblings.length) { if (!next) siblings.reverse(); callback(exclude(siblings)); } } }; // If index based start position then resolve it if (startContainer.nodeType == 1 && startContainer.hasChildNodes()) startContainer = startContainer.childNodes[startOffset]; // If index based end position then resolve it if (endContainer.nodeType == 1 && endContainer.hasChildNodes()) endContainer = endContainer.childNodes[Math.min(endOffset - 1, endContainer.childNodes.length - 1)]; // Same container if (startContainer == endContainer) return callback(exclude([startContainer])); // Find common ancestor and end points ancestor = dom.findCommonAncestor(startContainer, endContainer); // Process left side for (node = startContainer; node; node = node.parentNode) { if (node === endContainer) return walkBoundary(startContainer, ancestor, true); if (node === ancestor) break; } // Process right side for (node = endContainer; node; node = node.parentNode) { if (node === startContainer) return walkBoundary(endContainer, ancestor); if (node === ancestor) break; } // Find start/end point startPoint = findEndPoint(startContainer, ancestor) || startContainer; endPoint = findEndPoint(endContainer, ancestor) || endContainer; // Walk left leaf walkBoundary(startContainer, startPoint, true); // Walk the middle from start to end point siblings = collectSiblings( startPoint == startContainer ? startPoint : startPoint.nextSibling, 'nextSibling', endPoint == endContainer ? endPoint.nextSibling : endPoint ); if (siblings.length) callback(exclude(siblings)); // Walk right leaf walkBoundary(endContainer, endPoint); }; this.split = function(rng) { var startContainer = rng.startContainer, startOffset = rng.startOffset, endContainer = rng.endContainer, endOffset = rng.endOffset; function splitText(node, offset) { return node.splitText(offset); }; // Handle single text node if (startContainer == endContainer && startContainer.nodeType == 3) { if (startOffset > 0 && startOffset < startContainer.nodeValue.length) { endContainer = splitText(startContainer, startOffset); startContainer = endContainer.previousSibling; if (endOffset > startOffset) { endOffset = endOffset - startOffset; startContainer = endContainer = splitText(endContainer, endOffset).previousSibling; endOffset = endContainer.nodeValue.length; startOffset = 0; } else { endOffset = 0; } } } else { // Split startContainer text node if needed if (startContainer.nodeType == 3 && startOffset > 0 && startOffset < startContainer.nodeValue.length) { startContainer = splitText(startContainer, startOffset); startOffset = 0; } // Split endContainer text node if needed if (endContainer.nodeType == 3 && endOffset > 0 && endOffset < endContainer.nodeValue.length) { endContainer = splitText(endContainer, endOffset).previousSibling; endOffset = endContainer.nodeValue.length; } } return { startContainer : startContainer, startOffset : startOffset, endContainer : endContainer, endOffset : endOffset }; }; }; tinymce.dom.RangeUtils.compareRanges = function(rng1, rng2) { if (rng1 && rng2) { // Compare native IE ranges if (rng1.item || rng1.duplicate) { // Both are control ranges and the selected element matches if (rng1.item && rng2.item && rng1.item(0) === rng2.item(0)) return true; // Both are text ranges and the range matches if (rng1.isEqual && rng2.isEqual && rng2.isEqual(rng1)) return true; } else { // Compare w3c ranges return rng1.startContainer == rng2.startContainer && rng1.startOffset == rng2.startOffset; } } return false; }; })(tinymce); (function(tinymce) { var Event = tinymce.dom.Event, each = tinymce.each; tinymce.create('tinymce.ui.KeyboardNavigation', { KeyboardNavigation: function(settings, dom) { var t = this, root = settings.root, items = settings.items, enableUpDown = settings.enableUpDown, enableLeftRight = settings.enableLeftRight || !settings.enableUpDown, excludeFromTabOrder = settings.excludeFromTabOrder, itemFocussed, itemBlurred, rootKeydown, rootFocussed, focussedId; dom = dom || tinymce.DOM; itemFocussed = function(evt) { focussedId = evt.target.id; }; itemBlurred = function(evt) { dom.setAttrib(evt.target.id, 'tabindex', '-1'); }; rootFocussed = function(evt) { var item = dom.get(focussedId); dom.setAttrib(item, 'tabindex', '0'); item.focus(); }; t.focus = function() { dom.get(focussedId).focus(); }; t.destroy = function() { each(items, function(item) { dom.unbind(dom.get(item.id), 'focus', itemFocussed); dom.unbind(dom.get(item.id), 'blur', itemBlurred); }); dom.unbind(dom.get(root), 'focus', rootFocussed); dom.unbind(dom.get(root), 'keydown', rootKeydown); items = dom = root = t.focus = itemFocussed = itemBlurred = rootKeydown = rootFocussed = null; t.destroy = function() {}; }; t.moveFocus = function(dir, evt) { var idx = -1, controls = t.controls, newFocus; if (!focussedId) return; each(items, function(item, index) { if (item.id === focussedId) { idx = index; return false; } }); idx += dir; if (idx < 0) { idx = items.length - 1; } else if (idx >= items.length) { idx = 0; } newFocus = items[idx]; dom.setAttrib(focussedId, 'tabindex', '-1'); dom.setAttrib(newFocus.id, 'tabindex', '0'); dom.get(newFocus.id).focus(); if (settings.actOnFocus) { settings.onAction(newFocus.id); } if (evt) Event.cancel(evt); }; rootKeydown = function(evt) { var DOM_VK_LEFT = 37, DOM_VK_RIGHT = 39, DOM_VK_UP = 38, DOM_VK_DOWN = 40, DOM_VK_ESCAPE = 27, DOM_VK_ENTER = 14, DOM_VK_RETURN = 13, DOM_VK_SPACE = 32; switch (evt.keyCode) { case DOM_VK_LEFT: if (enableLeftRight) t.moveFocus(-1); break; case DOM_VK_RIGHT: if (enableLeftRight) t.moveFocus(1); break; case DOM_VK_UP: if (enableUpDown) t.moveFocus(-1); break; case DOM_VK_DOWN: if (enableUpDown) t.moveFocus(1); break; case DOM_VK_ESCAPE: if (settings.onCancel) { settings.onCancel(); Event.cancel(evt); } break; case DOM_VK_ENTER: case DOM_VK_RETURN: case DOM_VK_SPACE: if (settings.onAction) { settings.onAction(focussedId); Event.cancel(evt); } break; } }; // Set up state and listeners for each item. each(items, function(item, idx) { var tabindex; if (!item.id) { item.id = dom.uniqueId('_mce_item_'); } if (excludeFromTabOrder) { dom.bind(item.id, 'blur', itemBlurred); tabindex = '-1'; } else { tabindex = (idx === 0 ? '0' : '-1'); } dom.setAttrib(item.id, 'tabindex', tabindex); dom.bind(dom.get(item.id), 'focus', itemFocussed); }); // Setup initial state for root element. if (items[0]){ focussedId = items[0].id; } dom.setAttrib(root, 'tabindex', '-1'); // Setup listeners for root element. dom.bind(dom.get(root), 'focus', rootFocussed); dom.bind(dom.get(root), 'keydown', rootKeydown); } }); })(tinymce); (function(tinymce) { // Shorten class names var DOM = tinymce.DOM, is = tinymce.is; tinymce.create('tinymce.ui.Control', { Control : function(id, s, editor) { this.id = id; this.settings = s = s || {}; this.rendered = false; this.onRender = new tinymce.util.Dispatcher(this); this.classPrefix = ''; this.scope = s.scope || this; this.disabled = 0; this.active = 0; this.editor = editor; }, setAriaProperty : function(property, value) { var element = DOM.get(this.id + '_aria') || DOM.get(this.id); if (element) { DOM.setAttrib(element, 'aria-' + property, !!value); } }, focus : function() { DOM.get(this.id).focus(); }, setDisabled : function(s) { if (s != this.disabled) { this.setAriaProperty('disabled', s); this.setState('Disabled', s); this.setState('Enabled', !s); this.disabled = s; } }, isDisabled : function() { return this.disabled; }, setActive : function(s) { if (s != this.active) { this.setState('Active', s); this.active = s; this.setAriaProperty('pressed', s); } }, isActive : function() { return this.active; }, setState : function(c, s) { var n = DOM.get(this.id); c = this.classPrefix + c; if (s) DOM.addClass(n, c); else DOM.removeClass(n, c); }, isRendered : function() { return this.rendered; }, renderHTML : function() { }, renderTo : function(n) { DOM.setHTML(n, this.renderHTML()); }, postRender : function() { var t = this, b; // Set pending states if (is(t.disabled)) { b = t.disabled; t.disabled = -1; t.setDisabled(b); } if (is(t.active)) { b = t.active; t.active = -1; t.setActive(b); } }, remove : function() { DOM.remove(this.id); this.destroy(); }, destroy : function() { tinymce.dom.Event.clear(this.id); } }); })(tinymce); tinymce.create('tinymce.ui.Container:tinymce.ui.Control', { Container : function(id, s, editor) { this.parent(id, s, editor); this.controls = []; this.lookup = {}; }, add : function(c) { this.lookup[c.id] = c; this.controls.push(c); return c; }, get : function(n) { return this.lookup[n]; } }); tinymce.create('tinymce.ui.Separator:tinymce.ui.Control', { Separator : function(id, s) { this.parent(id, s); this.classPrefix = 'mceSeparator'; this.setDisabled(true); }, renderHTML : function() { return tinymce.DOM.createHTML('span', {'class' : this.classPrefix, role : 'separator', 'aria-orientation' : 'vertical', tabindex : '-1'}); } }); (function(tinymce) { var is = tinymce.is, DOM = tinymce.DOM, each = tinymce.each, walk = tinymce.walk; tinymce.create('tinymce.ui.MenuItem:tinymce.ui.Control', { MenuItem : function(id, s) { this.parent(id, s); this.classPrefix = 'mceMenuItem'; }, setSelected : function(s) { this.setState('Selected', s); this.setAriaProperty('checked', !!s); this.selected = s; }, isSelected : function() { return this.selected; }, postRender : function() { var t = this; t.parent(); // Set pending state if (is(t.selected)) t.setSelected(t.selected); } }); })(tinymce); (function(tinymce) { var is = tinymce.is, DOM = tinymce.DOM, each = tinymce.each, walk = tinymce.walk; tinymce.create('tinymce.ui.Menu:tinymce.ui.MenuItem', { Menu : function(id, s) { var t = this; t.parent(id, s); t.items = {}; t.collapsed = false; t.menuCount = 0; t.onAddItem = new tinymce.util.Dispatcher(this); }, expand : function(d) { var t = this; if (d) { walk(t, function(o) { if (o.expand) o.expand(); }, 'items', t); } t.collapsed = false; }, collapse : function(d) { var t = this; if (d) { walk(t, function(o) { if (o.collapse) o.collapse(); }, 'items', t); } t.collapsed = true; }, isCollapsed : function() { return this.collapsed; }, add : function(o) { if (!o.settings) o = new tinymce.ui.MenuItem(o.id || DOM.uniqueId(), o); this.onAddItem.dispatch(this, o); return this.items[o.id] = o; }, addSeparator : function() { return this.add({separator : true}); }, addMenu : function(o) { if (!o.collapse) o = this.createMenu(o); this.menuCount++; return this.add(o); }, hasMenus : function() { return this.menuCount !== 0; }, remove : function(o) { delete this.items[o.id]; }, removeAll : function() { var t = this; walk(t, function(o) { if (o.removeAll) o.removeAll(); else o.remove(); o.destroy(); }, 'items', t); t.items = {}; }, createMenu : function(o) { var m = new tinymce.ui.Menu(o.id || DOM.uniqueId(), o); m.onAddItem.add(this.onAddItem.dispatch, this.onAddItem); return m; } }); })(tinymce); (function(tinymce) { var is = tinymce.is, DOM = tinymce.DOM, each = tinymce.each, Event = tinymce.dom.Event, Element = tinymce.dom.Element; tinymce.create('tinymce.ui.DropMenu:tinymce.ui.Menu', { DropMenu : function(id, s) { s = s || {}; s.container = s.container || DOM.doc.body; s.offset_x = s.offset_x || 0; s.offset_y = s.offset_y || 0; s.vp_offset_x = s.vp_offset_x || 0; s.vp_offset_y = s.vp_offset_y || 0; if (is(s.icons) && !s.icons) s['class'] += ' mceNoIcons'; this.parent(id, s); this.onShowMenu = new tinymce.util.Dispatcher(this); this.onHideMenu = new tinymce.util.Dispatcher(this); this.classPrefix = 'mceMenu'; }, createMenu : function(s) { var t = this, cs = t.settings, m; s.container = s.container || cs.container; s.parent = t; s.constrain = s.constrain || cs.constrain; s['class'] = s['class'] || cs['class']; s.vp_offset_x = s.vp_offset_x || cs.vp_offset_x; s.vp_offset_y = s.vp_offset_y || cs.vp_offset_y; s.keyboard_focus = cs.keyboard_focus; m = new tinymce.ui.DropMenu(s.id || DOM.uniqueId(), s); m.onAddItem.add(t.onAddItem.dispatch, t.onAddItem); return m; }, focus : function() { var t = this; if (t.keyboardNav) { t.keyboardNav.focus(); } }, update : function() { var t = this, s = t.settings, tb = DOM.get('menu_' + t.id + '_tbl'), co = DOM.get('menu_' + t.id + '_co'), tw, th; tw = s.max_width ? Math.min(tb.clientWidth, s.max_width) : tb.clientWidth; th = s.max_height ? Math.min(tb.clientHeight, s.max_height) : tb.clientHeight; if (!DOM.boxModel) t.element.setStyles({width : tw + 2, height : th + 2}); else t.element.setStyles({width : tw, height : th}); if (s.max_width) DOM.setStyle(co, 'width', tw); if (s.max_height) { DOM.setStyle(co, 'height', th); if (tb.clientHeight < s.max_height) DOM.setStyle(co, 'overflow', 'hidden'); } }, showMenu : function(x, y, px) { var t = this, s = t.settings, co, vp = DOM.getViewPort(), w, h, mx, my, ot = 2, dm, tb, cp = t.classPrefix; t.collapse(1); if (t.isMenuVisible) return; if (!t.rendered) { co = DOM.add(t.settings.container, t.renderNode()); each(t.items, function(o) { o.postRender(); }); t.element = new Element('menu_' + t.id, {blocker : 1, container : s.container}); } else co = DOM.get('menu_' + t.id); // Move layer out of sight unless it's Opera since it scrolls to top of page due to an bug if (!tinymce.isOpera) DOM.setStyles(co, {left : -0xFFFF , top : -0xFFFF}); DOM.show(co); t.update(); x += s.offset_x || 0; y += s.offset_y || 0; vp.w -= 4; vp.h -= 4; // Move inside viewport if not submenu if (s.constrain) { w = co.clientWidth - ot; h = co.clientHeight - ot; mx = vp.x + vp.w; my = vp.y + vp.h; if ((x + s.vp_offset_x + w) > mx) x = px ? px - w : Math.max(0, (mx - s.vp_offset_x) - w); if ((y + s.vp_offset_y + h) > my) y = Math.max(0, (my - s.vp_offset_y) - h); } DOM.setStyles(co, {left : x , top : y}); t.element.update(); t.isMenuVisible = 1; t.mouseClickFunc = Event.add(co, 'click', function(e) { var m; e = e.target; if (e && (e = DOM.getParent(e, 'tr')) && !DOM.hasClass(e, cp + 'ItemSub')) { m = t.items[e.id]; if (m.isDisabled()) return; dm = t; while (dm) { if (dm.hideMenu) dm.hideMenu(); dm = dm.settings.parent; } if (m.settings.onclick) m.settings.onclick(e); return false; // Cancel to fix onbeforeunload problem } }); if (t.hasMenus()) { t.mouseOverFunc = Event.add(co, 'mouseover', function(e) { var m, r, mi; e = e.target; if (e && (e = DOM.getParent(e, 'tr'))) { m = t.items[e.id]; if (t.lastMenu) t.lastMenu.collapse(1); if (m.isDisabled()) return; if (e && DOM.hasClass(e, cp + 'ItemSub')) { //p = DOM.getPos(s.container); r = DOM.getRect(e); m.showMenu((r.x + r.w - ot), r.y - ot, r.x); t.lastMenu = m; DOM.addClass(DOM.get(m.id).firstChild, cp + 'ItemActive'); } } }); } Event.add(co, 'keydown', t._keyHandler, t); t.onShowMenu.dispatch(t); if (s.keyboard_focus) { t._setupKeyboardNav(); } }, hideMenu : function(c) { var t = this, co = DOM.get('menu_' + t.id), e; if (!t.isMenuVisible) return; if (t.keyboardNav) t.keyboardNav.destroy(); Event.remove(co, 'mouseover', t.mouseOverFunc); Event.remove(co, 'click', t.mouseClickFunc); Event.remove(co, 'keydown', t._keyHandler); DOM.hide(co); t.isMenuVisible = 0; if (!c) t.collapse(1); if (t.element) t.element.hide(); if (e = DOM.get(t.id)) DOM.removeClass(e.firstChild, t.classPrefix + 'ItemActive'); t.onHideMenu.dispatch(t); }, add : function(o) { var t = this, co; o = t.parent(o); if (t.isRendered && (co = DOM.get('menu_' + t.id))) t._add(DOM.select('tbody', co)[0], o); return o; }, collapse : function(d) { this.parent(d); this.hideMenu(1); }, remove : function(o) { DOM.remove(o.id); this.destroy(); return this.parent(o); }, destroy : function() { var t = this, co = DOM.get('menu_' + t.id); if (t.keyboardNav) t.keyboardNav.destroy(); Event.remove(co, 'mouseover', t.mouseOverFunc); Event.remove(DOM.select('a', co), 'focus', t.mouseOverFunc); Event.remove(co, 'click', t.mouseClickFunc); Event.remove(co, 'keydown', t._keyHandler); if (t.element) t.element.remove(); DOM.remove(co); }, renderNode : function() { var t = this, s = t.settings, n, tb, co, w; w = DOM.create('div', {role: 'listbox', id : 'menu_' + t.id, 'class' : s['class'], 'style' : 'position:absolute;left:0;top:0;z-index:200000;outline:0'}); if (t.settings.parent) { DOM.setAttrib(w, 'aria-parent', 'menu_' + t.settings.parent.id); } co = DOM.add(w, 'div', {role: 'presentation', id : 'menu_' + t.id + '_co', 'class' : t.classPrefix + (s['class'] ? ' ' + s['class'] : '')}); t.element = new Element('menu_' + t.id, {blocker : 1, container : s.container}); if (s.menu_line) DOM.add(co, 'span', {'class' : t.classPrefix + 'Line'}); // n = DOM.add(co, 'div', {id : 'menu_' + t.id + '_co', 'class' : 'mceMenuContainer'}); n = DOM.add(co, 'table', {role: 'presentation', id : 'menu_' + t.id + '_tbl', border : 0, cellPadding : 0, cellSpacing : 0}); tb = DOM.add(n, 'tbody'); each(t.items, function(o) { t._add(tb, o); }); t.rendered = true; return w; }, // Internal functions _setupKeyboardNav : function(){ var contextMenu, menuItems, t=this; contextMenu = DOM.get('menu_' + t.id); menuItems = DOM.select('a[role=option]', 'menu_' + t.id); menuItems.splice(0,0,contextMenu); t.keyboardNav = new tinymce.ui.KeyboardNavigation({ root: 'menu_' + t.id, items: menuItems, onCancel: function() { t.hideMenu(); }, enableUpDown: true }); contextMenu.focus(); }, _keyHandler : function(evt) { var t = this, e; switch (evt.keyCode) { case 37: // Left if (t.settings.parent) { t.hideMenu(); t.settings.parent.focus(); Event.cancel(evt); } break; case 39: // Right if (t.mouseOverFunc) t.mouseOverFunc(evt); break; } }, _add : function(tb, o) { var n, s = o.settings, a, ro, it, cp = this.classPrefix, ic; if (s.separator) { ro = DOM.add(tb, 'tr', {id : o.id, 'class' : cp + 'ItemSeparator'}); DOM.add(ro, 'td', {'class' : cp + 'ItemSeparator'}); if (n = ro.previousSibling) DOM.addClass(n, 'mceLast'); return; } n = ro = DOM.add(tb, 'tr', {id : o.id, 'class' : cp + 'Item ' + cp + 'ItemEnabled'}); n = it = DOM.add(n, s.titleItem ? 'th' : 'td'); n = a = DOM.add(n, 'a', {id: o.id + '_aria', role: s.titleItem ? 'presentation' : 'option', href : 'javascript:;', onclick : "return false;", onmousedown : 'return false;'}); if (s.parent) { DOM.setAttrib(a, 'aria-haspopup', 'true'); DOM.setAttrib(a, 'aria-owns', 'menu_' + o.id); } DOM.addClass(it, s['class']); // n = DOM.add(n, 'span', {'class' : 'item'}); ic = DOM.add(n, 'span', {'class' : 'mceIcon' + (s.icon ? ' mce_' + s.icon : '')}); if (s.icon_src) DOM.add(ic, 'img', {src : s.icon_src}); n = DOM.add(n, s.element || 'span', {'class' : 'mceText', title : o.settings.title}, o.settings.title); if (o.settings.style) { if (typeof o.settings.style == "function") o.settings.style = o.settings.style(); DOM.setAttrib(n, 'style', o.settings.style); } if (tb.childNodes.length == 1) DOM.addClass(ro, 'mceFirst'); if ((n = ro.previousSibling) && DOM.hasClass(n, cp + 'ItemSeparator')) DOM.addClass(ro, 'mceFirst'); if (o.collapse) DOM.addClass(ro, cp + 'ItemSub'); if (n = ro.previousSibling) DOM.removeClass(n, 'mceLast'); DOM.addClass(ro, 'mceLast'); } }); })(tinymce); (function(tinymce) { var DOM = tinymce.DOM; tinymce.create('tinymce.ui.Button:tinymce.ui.Control', { Button : function(id, s, ed) { this.parent(id, s, ed); this.classPrefix = 'mceButton'; }, renderHTML : function() { var cp = this.classPrefix, s = this.settings, h, l; l = DOM.encode(s.label || ''); h = '<a role="button" id="' + this.id + '" href="javascript:;" class="' + cp + ' ' + cp + 'Enabled ' + s['class'] + (l ? ' ' + cp + 'Labeled' : '') +'" onmousedown="return false;" onclick="return false;" aria-labelledby="' + this.id + '_voice" title="' + DOM.encode(s.title) + '">'; if (s.image && !(this.editor &&this.editor.forcedHighContrastMode) ) h += '<img class="mceIcon" src="' + s.image + '" alt="' + DOM.encode(s.title) + '" />' + l; else h += '<span class="mceIcon ' + s['class'] + '"></span>' + (l ? '<span class="' + cp + 'Label">' + l + '</span>' : ''); h += '<span class="mceVoiceLabel mceIconOnly" style="display: none;" id="' + this.id + '_voice">' + s.title + '</span>'; h += '</a>'; return h; }, postRender : function() { var t = this, s = t.settings, imgBookmark; // In IE a large image that occupies the entire editor area will be deselected when a button is clicked, so // need to keep the selection in case the selection is lost if (tinymce.isIE && t.editor) { tinymce.dom.Event.add(t.id, 'mousedown', function(e) { var nodeName = t.editor.selection.getNode().nodeName; imgBookmark = nodeName === 'IMG' ? t.editor.selection.getBookmark() : null; }); } tinymce.dom.Event.add(t.id, 'click', function(e) { if (!t.isDisabled()) { // restore the selection in case the selection is lost in IE if (tinymce.isIE && t.editor && imgBookmark !== null) { t.editor.selection.moveToBookmark(imgBookmark); } return s.onclick.call(s.scope, e); } }); tinymce.dom.Event.add(t.id, 'keyup', function(e) { if (!t.isDisabled() && e.keyCode==tinymce.VK.SPACEBAR) return s.onclick.call(s.scope, e); }); } }); })(tinymce); (function(tinymce) { var DOM = tinymce.DOM, Event = tinymce.dom.Event, each = tinymce.each, Dispatcher = tinymce.util.Dispatcher, undef; tinymce.create('tinymce.ui.ListBox:tinymce.ui.Control', { ListBox : function(id, s, ed) { var t = this; t.parent(id, s, ed); t.items = []; t.onChange = new Dispatcher(t); t.onPostRender = new Dispatcher(t); t.onAdd = new Dispatcher(t); t.onRenderMenu = new tinymce.util.Dispatcher(this); t.classPrefix = 'mceListBox'; t.marked = {}; }, select : function(va) { var t = this, fv, f; t.marked = {}; if (va == undef) return t.selectByIndex(-1); // Is string or number make function selector if (va && typeof(va)=="function") f = va; else { f = function(v) { return v == va; }; } // Do we need to do something? if (va != t.selectedValue) { // Find item each(t.items, function(o, i) { if (f(o.value)) { fv = 1; t.selectByIndex(i); return false; } }); if (!fv) t.selectByIndex(-1); } }, selectByIndex : function(idx) { var t = this, e, o, label; t.marked = {}; if (idx != t.selectedIndex) { e = DOM.get(t.id + '_text'); label = DOM.get(t.id + '_voiceDesc'); o = t.items[idx]; if (o) { t.selectedValue = o.value; t.selectedIndex = idx; DOM.setHTML(e, DOM.encode(o.title)); DOM.setHTML(label, t.settings.title + " - " + o.title); DOM.removeClass(e, 'mceTitle'); DOM.setAttrib(t.id, 'aria-valuenow', o.title); } else { DOM.setHTML(e, DOM.encode(t.settings.title)); DOM.setHTML(label, DOM.encode(t.settings.title)); DOM.addClass(e, 'mceTitle'); t.selectedValue = t.selectedIndex = null; DOM.setAttrib(t.id, 'aria-valuenow', t.settings.title); } e = 0; } }, mark : function(value) { this.marked[value] = true; }, add : function(n, v, o) { var t = this; o = o || {}; o = tinymce.extend(o, { title : n, value : v }); t.items.push(o); t.onAdd.dispatch(t, o); }, getLength : function() { return this.items.length; }, renderHTML : function() { var h = '', t = this, s = t.settings, cp = t.classPrefix; h = '<span role="listbox" aria-haspopup="true" aria-labelledby="' + t.id +'_voiceDesc" aria-describedby="' + t.id + '_voiceDesc"><table role="presentation" tabindex="0" id="' + t.id + '" cellpadding="0" cellspacing="0" class="' + cp + ' ' + cp + 'Enabled' + (s['class'] ? (' ' + s['class']) : '') + '"><tbody><tr>'; h += '<td>' + DOM.createHTML('span', {id: t.id + '_voiceDesc', 'class': 'voiceLabel', style:'display:none;'}, t.settings.title); h += DOM.createHTML('a', {id : t.id + '_text', tabindex : -1, href : 'javascript:;', 'class' : 'mceText', onclick : "return false;", onmousedown : 'return false;'}, DOM.encode(t.settings.title)) + '</td>'; h += '<td>' + DOM.createHTML('a', {id : t.id + '_open', tabindex : -1, href : 'javascript:;', 'class' : 'mceOpen', onclick : "return false;", onmousedown : 'return false;'}, '<span><span style="display:none;" class="mceIconOnly" aria-hidden="true">\u25BC</span></span>') + '</td>'; h += '</tr></tbody></table></span>'; return h; }, showMenu : function() { var t = this, p2, e = DOM.get(this.id), m; if (t.isDisabled() || t.items.length === 0) return; if (t.menu && t.menu.isMenuVisible) return t.hideMenu(); if (!t.isMenuRendered) { t.renderMenu(); t.isMenuRendered = true; } p2 = DOM.getPos(e); m = t.menu; m.settings.offset_x = p2.x; m.settings.offset_y = p2.y; m.settings.keyboard_focus = !tinymce.isOpera; // Opera is buggy when it comes to auto focus // Select in menu each(t.items, function(o) { if (m.items[o.id]) { m.items[o.id].setSelected(0); } }); each(t.items, function(o) { if (m.items[o.id] && t.marked[o.value]) { m.items[o.id].setSelected(1); } if (o.value === t.selectedValue) { m.items[o.id].setSelected(1); } }); m.showMenu(0, e.clientHeight); Event.add(DOM.doc, 'mousedown', t.hideMenu, t); DOM.addClass(t.id, t.classPrefix + 'Selected'); //DOM.get(t.id + '_text').focus(); }, hideMenu : function(e) { var t = this; if (t.menu && t.menu.isMenuVisible) { DOM.removeClass(t.id, t.classPrefix + 'Selected'); // Prevent double toogles by canceling the mouse click event to the button if (e && e.type == "mousedown" && (e.target.id == t.id + '_text' || e.target.id == t.id + '_open')) return; if (!e || !DOM.getParent(e.target, '.mceMenu')) { DOM.removeClass(t.id, t.classPrefix + 'Selected'); Event.remove(DOM.doc, 'mousedown', t.hideMenu, t); t.menu.hideMenu(); } } }, renderMenu : function() { var t = this, m; m = t.settings.control_manager.createDropMenu(t.id + '_menu', { menu_line : 1, 'class' : t.classPrefix + 'Menu mceNoIcons', max_width : 150, max_height : 150 }); m.onHideMenu.add(function() { t.hideMenu(); t.focus(); }); m.add({ title : t.settings.title, 'class' : 'mceMenuItemTitle', onclick : function() { if (t.settings.onselect('') !== false) t.select(''); // Must be runned after } }); each(t.items, function(o) { // No value then treat it as a title if (o.value === undef) { m.add({ title : o.title, role : "option", 'class' : 'mceMenuItemTitle', onclick : function() { if (t.settings.onselect('') !== false) t.select(''); // Must be runned after } }); } else { o.id = DOM.uniqueId(); o.role= "option"; o.onclick = function() { if (t.settings.onselect(o.value) !== false) t.select(o.value); // Must be runned after }; m.add(o); } }); t.onRenderMenu.dispatch(t, m); t.menu = m; }, postRender : function() { var t = this, cp = t.classPrefix; Event.add(t.id, 'click', t.showMenu, t); Event.add(t.id, 'keydown', function(evt) { if (evt.keyCode == 32) { // Space t.showMenu(evt); Event.cancel(evt); } }); Event.add(t.id, 'focus', function() { if (!t._focused) { t.keyDownHandler = Event.add(t.id, 'keydown', function(e) { if (e.keyCode == 40) { t.showMenu(); Event.cancel(e); } }); t.keyPressHandler = Event.add(t.id, 'keypress', function(e) { var v; if (e.keyCode == 13) { // Fake select on enter v = t.selectedValue; t.selectedValue = null; // Needs to be null to fake change Event.cancel(e); t.settings.onselect(v); } }); } t._focused = 1; }); Event.add(t.id, 'blur', function() { Event.remove(t.id, 'keydown', t.keyDownHandler); Event.remove(t.id, 'keypress', t.keyPressHandler); t._focused = 0; }); // Old IE doesn't have hover on all elements if (tinymce.isIE6 || !DOM.boxModel) { Event.add(t.id, 'mouseover', function() { if (!DOM.hasClass(t.id, cp + 'Disabled')) DOM.addClass(t.id, cp + 'Hover'); }); Event.add(t.id, 'mouseout', function() { if (!DOM.hasClass(t.id, cp + 'Disabled')) DOM.removeClass(t.id, cp + 'Hover'); }); } t.onPostRender.dispatch(t, DOM.get(t.id)); }, destroy : function() { this.parent(); Event.clear(this.id + '_text'); Event.clear(this.id + '_open'); } }); })(tinymce); (function(tinymce) { var DOM = tinymce.DOM, Event = tinymce.dom.Event, each = tinymce.each, Dispatcher = tinymce.util.Dispatcher, undef; tinymce.create('tinymce.ui.NativeListBox:tinymce.ui.ListBox', { NativeListBox : function(id, s) { this.parent(id, s); this.classPrefix = 'mceNativeListBox'; }, setDisabled : function(s) { DOM.get(this.id).disabled = s; this.setAriaProperty('disabled', s); }, isDisabled : function() { return DOM.get(this.id).disabled; }, select : function(va) { var t = this, fv, f; if (va == undef) return t.selectByIndex(-1); // Is string or number make function selector if (va && typeof(va)=="function") f = va; else { f = function(v) { return v == va; }; } // Do we need to do something? if (va != t.selectedValue) { // Find item each(t.items, function(o, i) { if (f(o.value)) { fv = 1; t.selectByIndex(i); return false; } }); if (!fv) t.selectByIndex(-1); } }, selectByIndex : function(idx) { DOM.get(this.id).selectedIndex = idx + 1; this.selectedValue = this.items[idx] ? this.items[idx].value : null; }, add : function(n, v, a) { var o, t = this; a = a || {}; a.value = v; if (t.isRendered()) DOM.add(DOM.get(this.id), 'option', a, n); o = { title : n, value : v, attribs : a }; t.items.push(o); t.onAdd.dispatch(t, o); }, getLength : function() { return this.items.length; }, renderHTML : function() { var h, t = this; h = DOM.createHTML('option', {value : ''}, '-- ' + t.settings.title + ' --'); each(t.items, function(it) { h += DOM.createHTML('option', {value : it.value}, it.title); }); h = DOM.createHTML('select', {id : t.id, 'class' : 'mceNativeListBox', 'aria-labelledby': t.id + '_aria'}, h); h += DOM.createHTML('span', {id : t.id + '_aria', 'style': 'display: none'}, t.settings.title); return h; }, postRender : function() { var t = this, ch, changeListenerAdded = true; t.rendered = true; function onChange(e) { var v = t.items[e.target.selectedIndex - 1]; if (v && (v = v.value)) { t.onChange.dispatch(t, v); if (t.settings.onselect) t.settings.onselect(v); } }; Event.add(t.id, 'change', onChange); // Accessibility keyhandler Event.add(t.id, 'keydown', function(e) { var bf; Event.remove(t.id, 'change', ch); changeListenerAdded = false; bf = Event.add(t.id, 'blur', function() { if (changeListenerAdded) return; changeListenerAdded = true; Event.add(t.id, 'change', onChange); Event.remove(t.id, 'blur', bf); }); //prevent default left and right keys on chrome - so that the keyboard navigation is used. if (tinymce.isWebKit && (e.keyCode==37 ||e.keyCode==39)) { return Event.prevent(e); } if (e.keyCode == 13 || e.keyCode == 32) { onChange(e); return Event.cancel(e); } }); t.onPostRender.dispatch(t, DOM.get(t.id)); } }); })(tinymce); (function(tinymce) { var DOM = tinymce.DOM, Event = tinymce.dom.Event, each = tinymce.each; tinymce.create('tinymce.ui.MenuButton:tinymce.ui.Button', { MenuButton : function(id, s, ed) { this.parent(id, s, ed); this.onRenderMenu = new tinymce.util.Dispatcher(this); s.menu_container = s.menu_container || DOM.doc.body; }, showMenu : function() { var t = this, p1, p2, e = DOM.get(t.id), m; if (t.isDisabled()) return; if (!t.isMenuRendered) { t.renderMenu(); t.isMenuRendered = true; } if (t.isMenuVisible) return t.hideMenu(); p1 = DOM.getPos(t.settings.menu_container); p2 = DOM.getPos(e); m = t.menu; m.settings.offset_x = p2.x; m.settings.offset_y = p2.y; m.settings.vp_offset_x = p2.x; m.settings.vp_offset_y = p2.y; m.settings.keyboard_focus = t._focused; m.showMenu(0, e.firstChild.clientHeight); Event.add(DOM.doc, 'mousedown', t.hideMenu, t); t.setState('Selected', 1); t.isMenuVisible = 1; }, renderMenu : function() { var t = this, m; m = t.settings.control_manager.createDropMenu(t.id + '_menu', { menu_line : 1, 'class' : this.classPrefix + 'Menu', icons : t.settings.icons }); m.onHideMenu.add(function() { t.hideMenu(); t.focus(); }); t.onRenderMenu.dispatch(t, m); t.menu = m; }, hideMenu : function(e) { var t = this; // Prevent double toogles by canceling the mouse click event to the button if (e && e.type == "mousedown" && DOM.getParent(e.target, function(e) {return e.id === t.id || e.id === t.id + '_open';})) return; if (!e || !DOM.getParent(e.target, '.mceMenu')) { t.setState('Selected', 0); Event.remove(DOM.doc, 'mousedown', t.hideMenu, t); if (t.menu) t.menu.hideMenu(); } t.isMenuVisible = 0; }, postRender : function() { var t = this, s = t.settings; Event.add(t.id, 'click', function() { if (!t.isDisabled()) { if (s.onclick) s.onclick(t.value); t.showMenu(); } }); } }); })(tinymce); (function(tinymce) { var DOM = tinymce.DOM, Event = tinymce.dom.Event, each = tinymce.each; tinymce.create('tinymce.ui.SplitButton:tinymce.ui.MenuButton', { SplitButton : function(id, s, ed) { this.parent(id, s, ed); this.classPrefix = 'mceSplitButton'; }, renderHTML : function() { var h, t = this, s = t.settings, h1; h = '<tbody><tr>'; if (s.image) h1 = DOM.createHTML('img ', {src : s.image, role: 'presentation', 'class' : 'mceAction ' + s['class']}); else h1 = DOM.createHTML('span', {'class' : 'mceAction ' + s['class']}, ''); h1 += DOM.createHTML('span', {'class': 'mceVoiceLabel mceIconOnly', id: t.id + '_voice', style: 'display:none;'}, s.title); h += '<td >' + DOM.createHTML('a', {role: 'button', id : t.id + '_action', tabindex: '-1', href : 'javascript:;', 'class' : 'mceAction ' + s['class'], onclick : "return false;", onmousedown : 'return false;', title : s.title}, h1) + '</td>'; h1 = DOM.createHTML('span', {'class' : 'mceOpen ' + s['class']}, '<span style="display:none;" class="mceIconOnly" aria-hidden="true">\u25BC</span>'); h += '<td >' + DOM.createHTML('a', {role: 'button', id : t.id + '_open', tabindex: '-1', href : 'javascript:;', 'class' : 'mceOpen ' + s['class'], onclick : "return false;", onmousedown : 'return false;', title : s.title}, h1) + '</td>'; h += '</tr></tbody>'; h = DOM.createHTML('table', { role: 'presentation', 'class' : 'mceSplitButton mceSplitButtonEnabled ' + s['class'], cellpadding : '0', cellspacing : '0', title : s.title}, h); return DOM.createHTML('div', {id : t.id, role: 'button', tabindex: '0', 'aria-labelledby': t.id + '_voice', 'aria-haspopup': 'true'}, h); }, postRender : function() { var t = this, s = t.settings, activate; if (s.onclick) { activate = function(evt) { if (!t.isDisabled()) { s.onclick(t.value); Event.cancel(evt); } }; Event.add(t.id + '_action', 'click', activate); Event.add(t.id, ['click', 'keydown'], function(evt) { var DOM_VK_SPACE = 32, DOM_VK_ENTER = 14, DOM_VK_RETURN = 13, DOM_VK_UP = 38, DOM_VK_DOWN = 40; if ((evt.keyCode === 32 || evt.keyCode === 13 || evt.keyCode === 14) && !evt.altKey && !evt.ctrlKey && !evt.metaKey) { activate(); Event.cancel(evt); } else if (evt.type === 'click' || evt.keyCode === DOM_VK_DOWN) { t.showMenu(); Event.cancel(evt); } }); } Event.add(t.id + '_open', 'click', function (evt) { t.showMenu(); Event.cancel(evt); }); Event.add([t.id, t.id + '_open'], 'focus', function() {t._focused = 1;}); Event.add([t.id, t.id + '_open'], 'blur', function() {t._focused = 0;}); // Old IE doesn't have hover on all elements if (tinymce.isIE6 || !DOM.boxModel) { Event.add(t.id, 'mouseover', function() { if (!DOM.hasClass(t.id, 'mceSplitButtonDisabled')) DOM.addClass(t.id, 'mceSplitButtonHover'); }); Event.add(t.id, 'mouseout', function() { if (!DOM.hasClass(t.id, 'mceSplitButtonDisabled')) DOM.removeClass(t.id, 'mceSplitButtonHover'); }); } }, destroy : function() { this.parent(); Event.clear(this.id + '_action'); Event.clear(this.id + '_open'); Event.clear(this.id); } }); })(tinymce); (function(tinymce) { var DOM = tinymce.DOM, Event = tinymce.dom.Event, is = tinymce.is, each = tinymce.each; tinymce.create('tinymce.ui.ColorSplitButton:tinymce.ui.SplitButton', { ColorSplitButton : function(id, s, ed) { var t = this; t.parent(id, s, ed); t.settings = s = tinymce.extend({ colors : '000000,993300,333300,003300,003366,000080,333399,333333,800000,FF6600,808000,008000,008080,0000FF,666699,808080,FF0000,FF9900,99CC00,339966,33CCCC,3366FF,800080,999999,FF00FF,FFCC00,FFFF00,00FF00,00FFFF,00CCFF,993366,C0C0C0,FF99CC,FFCC99,FFFF99,CCFFCC,CCFFFF,99CCFF,CC99FF,FFFFFF', grid_width : 8, default_color : '#888888' }, t.settings); t.onShowMenu = new tinymce.util.Dispatcher(t); t.onHideMenu = new tinymce.util.Dispatcher(t); t.value = s.default_color; }, showMenu : function() { var t = this, r, p, e, p2; if (t.isDisabled()) return; if (!t.isMenuRendered) { t.renderMenu(); t.isMenuRendered = true; } if (t.isMenuVisible) return t.hideMenu(); e = DOM.get(t.id); DOM.show(t.id + '_menu'); DOM.addClass(e, 'mceSplitButtonSelected'); p2 = DOM.getPos(e); DOM.setStyles(t.id + '_menu', { left : p2.x, top : p2.y + e.firstChild.clientHeight, zIndex : 200000 }); e = 0; Event.add(DOM.doc, 'mousedown', t.hideMenu, t); t.onShowMenu.dispatch(t); if (t._focused) { t._keyHandler = Event.add(t.id + '_menu', 'keydown', function(e) { if (e.keyCode == 27) t.hideMenu(); }); DOM.select('a', t.id + '_menu')[0].focus(); // Select first link } t.isMenuVisible = 1; }, hideMenu : function(e) { var t = this; if (t.isMenuVisible) { // Prevent double toogles by canceling the mouse click event to the button if (e && e.type == "mousedown" && DOM.getParent(e.target, function(e) {return e.id === t.id + '_open';})) return; if (!e || !DOM.getParent(e.target, '.mceSplitButtonMenu')) { DOM.removeClass(t.id, 'mceSplitButtonSelected'); Event.remove(DOM.doc, 'mousedown', t.hideMenu, t); Event.remove(t.id + '_menu', 'keydown', t._keyHandler); DOM.hide(t.id + '_menu'); } t.isMenuVisible = 0; t.onHideMenu.dispatch(); } }, renderMenu : function() { var t = this, m, i = 0, s = t.settings, n, tb, tr, w, context; w = DOM.add(s.menu_container, 'div', {role: 'listbox', id : t.id + '_menu', 'class' : s.menu_class + ' ' + s['class'], style : 'position:absolute;left:0;top:-1000px;'}); m = DOM.add(w, 'div', {'class' : s['class'] + ' mceSplitButtonMenu'}); DOM.add(m, 'span', {'class' : 'mceMenuLine'}); n = DOM.add(m, 'table', {role: 'presentation', 'class' : 'mceColorSplitMenu'}); tb = DOM.add(n, 'tbody'); // Generate color grid i = 0; each(is(s.colors, 'array') ? s.colors : s.colors.split(','), function(c) { c = c.replace(/^#/, ''); if (!i--) { tr = DOM.add(tb, 'tr'); i = s.grid_width - 1; } n = DOM.add(tr, 'td'); var settings = { href : 'javascript:;', style : { backgroundColor : '#' + c }, 'title': t.editor.getLang('colors.' + c, c), 'data-mce-color' : '#' + c }; // adding a proper ARIA role = button causes JAWS to read things incorrectly on IE. if (!tinymce.isIE ) { settings.role = 'option'; } n = DOM.add(n, 'a', settings); if (t.editor.forcedHighContrastMode) { n = DOM.add(n, 'canvas', { width: 16, height: 16, 'aria-hidden': 'true' }); if (n.getContext && (context = n.getContext("2d"))) { context.fillStyle = '#' + c; context.fillRect(0, 0, 16, 16); } else { // No point leaving a canvas element around if it's not supported for drawing on anyway. DOM.remove(n); } } }); if (s.more_colors_func) { n = DOM.add(tb, 'tr'); n = DOM.add(n, 'td', {colspan : s.grid_width, 'class' : 'mceMoreColors'}); n = DOM.add(n, 'a', {role: 'option', id : t.id + '_more', href : 'javascript:;', onclick : 'return false;', 'class' : 'mceMoreColors'}, s.more_colors_title); Event.add(n, 'click', function(e) { s.more_colors_func.call(s.more_colors_scope || this); return Event.cancel(e); // Cancel to fix onbeforeunload problem }); } DOM.addClass(m, 'mceColorSplitMenu'); new tinymce.ui.KeyboardNavigation({ root: t.id + '_menu', items: DOM.select('a', t.id + '_menu'), onCancel: function() { t.hideMenu(); t.focus(); } }); // Prevent IE from scrolling and hindering click to occur #4019 Event.add(t.id + '_menu', 'mousedown', function(e) {return Event.cancel(e);}); Event.add(t.id + '_menu', 'click', function(e) { var c; e = DOM.getParent(e.target, 'a', tb); if (e && e.nodeName.toLowerCase() == 'a' && (c = e.getAttribute('data-mce-color'))) t.setColor(c); return false; // Prevent IE auto save warning }); return w; }, setColor : function(c) { this.displayColor(c); this.hideMenu(); this.settings.onselect(c); }, displayColor : function(c) { var t = this; DOM.setStyle(t.id + '_preview', 'backgroundColor', c); t.value = c; }, postRender : function() { var t = this, id = t.id; t.parent(); DOM.add(id + '_action', 'div', {id : id + '_preview', 'class' : 'mceColorPreview'}); DOM.setStyle(t.id + '_preview', 'backgroundColor', t.value); }, destroy : function() { this.parent(); Event.clear(this.id + '_menu'); Event.clear(this.id + '_more'); DOM.remove(this.id + '_menu'); } }); })(tinymce); (function(tinymce) { // Shorten class names var dom = tinymce.DOM, each = tinymce.each, Event = tinymce.dom.Event; tinymce.create('tinymce.ui.ToolbarGroup:tinymce.ui.Container', { renderHTML : function() { var t = this, h = [], controls = t.controls, each = tinymce.each, settings = t.settings; h.push('<div id="' + t.id + '" role="group" aria-labelledby="' + t.id + '_voice">'); //TODO: ACC test this out - adding a role = application for getting the landmarks working well. h.push("<span role='application'>"); h.push('<span id="' + t.id + '_voice" class="mceVoiceLabel" style="display:none;">' + dom.encode(settings.name) + '</span>'); each(controls, function(toolbar) { h.push(toolbar.renderHTML()); }); h.push("</span>"); h.push('</div>'); return h.join(''); }, focus : function() { var t = this; dom.get(t.id).focus(); }, postRender : function() { var t = this, items = []; each(t.controls, function(toolbar) { each (toolbar.controls, function(control) { if (control.id) { items.push(control); } }); }); t.keyNav = new tinymce.ui.KeyboardNavigation({ root: t.id, items: items, onCancel: function() { //Move focus if webkit so that navigation back will read the item. if (tinymce.isWebKit) { dom.get(t.editor.id+"_ifr").focus(); } t.editor.focus(); }, excludeFromTabOrder: !t.settings.tab_focus_toolbar }); }, destroy : function() { var self = this; self.parent(); self.keyNav.destroy(); Event.clear(self.id); } }); })(tinymce); (function(tinymce) { // Shorten class names var dom = tinymce.DOM, each = tinymce.each; tinymce.create('tinymce.ui.Toolbar:tinymce.ui.Container', { renderHTML : function() { var t = this, h = '', c, co, s = t.settings, i, pr, nx, cl; cl = t.controls; for (i=0; i<cl.length; i++) { // Get current control, prev control, next control and if the control is a list box or not co = cl[i]; pr = cl[i - 1]; nx = cl[i + 1]; // Add toolbar start if (i === 0) { c = 'mceToolbarStart'; if (co.Button) c += ' mceToolbarStartButton'; else if (co.SplitButton) c += ' mceToolbarStartSplitButton'; else if (co.ListBox) c += ' mceToolbarStartListBox'; h += dom.createHTML('td', {'class' : c}, dom.createHTML('span', null, '<!-- IE -->')); } // Add toolbar end before list box and after the previous button // This is to fix the o2k7 editor skins if (pr && co.ListBox) { if (pr.Button || pr.SplitButton) h += dom.createHTML('td', {'class' : 'mceToolbarEnd'}, dom.createHTML('span', null, '<!-- IE -->')); } // Render control HTML // IE 8 quick fix, needed to propertly generate a hit area for anchors if (dom.stdMode) h += '<td style="position: relative">' + co.renderHTML() + '</td>'; else h += '<td>' + co.renderHTML() + '</td>'; // Add toolbar start after list box and before the next button // This is to fix the o2k7 editor skins if (nx && co.ListBox) { if (nx.Button || nx.SplitButton) h += dom.createHTML('td', {'class' : 'mceToolbarStart'}, dom.createHTML('span', null, '<!-- IE -->')); } } c = 'mceToolbarEnd'; if (co.Button) c += ' mceToolbarEndButton'; else if (co.SplitButton) c += ' mceToolbarEndSplitButton'; else if (co.ListBox) c += ' mceToolbarEndListBox'; h += dom.createHTML('td', {'class' : c}, dom.createHTML('span', null, '<!-- IE -->')); return dom.createHTML('table', {id : t.id, 'class' : 'mceToolbar' + (s['class'] ? ' ' + s['class'] : ''), cellpadding : '0', cellspacing : '0', align : t.settings.align || '', role: 'presentation', tabindex: '-1'}, '<tbody><tr>' + h + '</tr></tbody>'); } }); })(tinymce); (function(tinymce) { var Dispatcher = tinymce.util.Dispatcher, each = tinymce.each; tinymce.create('tinymce.AddOnManager', { AddOnManager : function() { var self = this; self.items = []; self.urls = {}; self.lookup = {}; self.onAdd = new Dispatcher(self); }, get : function(n) { if (this.lookup[n]) { return this.lookup[n].instance; } else { return undefined; } }, dependencies : function(n) { var result; if (this.lookup[n]) { result = this.lookup[n].dependencies; } return result || []; }, requireLangPack : function(n) { var s = tinymce.settings; if (s && s.language && s.language_load !== false) tinymce.ScriptLoader.add(this.urls[n] + '/langs/' + s.language + '.js'); }, add : function(id, o, dependencies) { this.items.push(o); this.lookup[id] = {instance:o, dependencies:dependencies}; this.onAdd.dispatch(this, id, o); return o; }, createUrl: function(baseUrl, dep) { if (typeof dep === "object") { return dep } else { return {prefix: baseUrl.prefix, resource: dep, suffix: baseUrl.suffix}; } }, addComponents: function(pluginName, scripts) { var pluginUrl = this.urls[pluginName]; tinymce.each(scripts, function(script){ tinymce.ScriptLoader.add(pluginUrl+"/"+script); }); }, load : function(n, u, cb, s) { var t = this, url = u; function loadDependencies() { var dependencies = t.dependencies(n); tinymce.each(dependencies, function(dep) { var newUrl = t.createUrl(u, dep); t.load(newUrl.resource, newUrl, undefined, undefined); }); if (cb) { if (s) { cb.call(s); } else { cb.call(tinymce.ScriptLoader); } } } if (t.urls[n]) return; if (typeof u === "object") url = u.prefix + u.resource + u.suffix; if (url.indexOf('/') !== 0 && url.indexOf('://') == -1) url = tinymce.baseURL + '/' + url; t.urls[n] = url.substring(0, url.lastIndexOf('/')); if (t.lookup[n]) { loadDependencies(); } else { tinymce.ScriptLoader.add(url, loadDependencies, s); } } }); // Create plugin and theme managers tinymce.PluginManager = new tinymce.AddOnManager(); tinymce.ThemeManager = new tinymce.AddOnManager(); }(tinymce)); (function(tinymce) { // Shorten names var each = tinymce.each, extend = tinymce.extend, DOM = tinymce.DOM, Event = tinymce.dom.Event, ThemeManager = tinymce.ThemeManager, PluginManager = tinymce.PluginManager, explode = tinymce.explode, Dispatcher = tinymce.util.Dispatcher, undef, instanceCounter = 0; // Setup some URLs where the editor API is located and where the document is tinymce.documentBaseURL = window.location.href.replace(/[\?#].*$/, '').replace(/[\/\\][^\/]+$/, ''); if (!/[\/\\]$/.test(tinymce.documentBaseURL)) tinymce.documentBaseURL += '/'; tinymce.baseURL = new tinymce.util.URI(tinymce.documentBaseURL).toAbsolute(tinymce.baseURL); tinymce.baseURI = new tinymce.util.URI(tinymce.baseURL); // Add before unload listener // This was required since IE was leaking memory if you added and removed beforeunload listeners // with attachEvent/detatchEvent so this only adds one listener and instances can the attach to the onBeforeUnload event tinymce.onBeforeUnload = new Dispatcher(tinymce); // Must be on window or IE will leak if the editor is placed in frame or iframe Event.add(window, 'beforeunload', function(e) { tinymce.onBeforeUnload.dispatch(tinymce, e); }); tinymce.onAddEditor = new Dispatcher(tinymce); tinymce.onRemoveEditor = new Dispatcher(tinymce); tinymce.EditorManager = extend(tinymce, { editors : [], i18n : {}, activeEditor : null, init : function(s) { var t = this, pl, sl = tinymce.ScriptLoader, e, el = [], ed; function createId(elm) { var id = elm.id; // Use element id, or unique name or generate a unique id if (!id) { id = elm.name; if (id && !DOM.get(id)) { id = elm.name; } else { // Generate unique name id = DOM.uniqueId(); } elm.setAttribute('id', id); } return id; }; function execCallback(se, n, s) { var f = se[n]; if (!f) return; if (tinymce.is(f, 'string')) { s = f.replace(/\.\w+$/, ''); s = s ? tinymce.resolve(s) : 0; f = tinymce.resolve(f); } return f.apply(s || this, Array.prototype.slice.call(arguments, 2)); }; function hasClass(n, c) { return c.constructor === RegExp ? c.test(n.className) : DOM.hasClass(n, c); }; s = extend({ theme : "simple", language : "en" }, s); t.settings = s; // Legacy call Event.bind(window, 'ready', function() { var l, co; execCallback(s, 'onpageload'); switch (s.mode) { case "exact": l = s.elements || ''; if(l.length > 0) { each(explode(l), function(v) { if (DOM.get(v)) { ed = new tinymce.Editor(v, s); el.push(ed); ed.render(1); } else { each(document.forms, function(f) { each(f.elements, function(e) { if (e.name === v) { v = 'mce_editor_' + instanceCounter++; DOM.setAttrib(e, 'id', v); ed = new tinymce.Editor(v, s); el.push(ed); ed.render(1); } }); }); } }); } break; case "textareas": case "specific_textareas": each(DOM.select('textarea'), function(elm) { if (s.editor_deselector && hasClass(elm, s.editor_deselector)) return; if (!s.editor_selector || hasClass(elm, s.editor_selector)) { ed = new tinymce.Editor(createId(elm), s); el.push(ed); ed.render(1); } }); break; default: if (s.types) { // Process type specific selector each(s.types, function(type) { each(DOM.select(type.selector), function(elm) { var editor = new tinymce.Editor(createId(elm), tinymce.extend({}, s, type)); el.push(editor); editor.render(1); }); }); } else if (s.selector) { // Process global selector each(DOM.select(s.selector), function(elm) { var editor = new tinymce.Editor(createId(elm), s); el.push(editor); editor.render(1); }); } } // Call onInit when all editors are initialized if (s.oninit) { l = co = 0; each(el, function(ed) { co++; if (!ed.initialized) { // Wait for it ed.onInit.add(function() { l++; // All done if (l == co) execCallback(s, 'oninit'); }); } else l++; // All done if (l == co) execCallback(s, 'oninit'); }); } }); }, get : function(id) { if (id === undef) return this.editors; return this.editors[id]; }, getInstanceById : function(id) { return this.get(id); }, add : function(editor) { var self = this, editors = self.editors; // Add named and index editor instance editors[editor.id] = editor; editors.push(editor); self._setActive(editor); self.onAddEditor.dispatch(self, editor); return editor; }, remove : function(editor) { var t = this, i, editors = t.editors; // Not in the collection if (!editors[editor.id]) return null; delete editors[editor.id]; for (i = 0; i < editors.length; i++) { if (editors[i] == editor) { editors.splice(i, 1); break; } } // Select another editor since the active one was removed if (t.activeEditor == editor) t._setActive(editors[0]); editor.destroy(); t.onRemoveEditor.dispatch(t, editor); return editor; }, execCommand : function(c, u, v) { var t = this, ed = t.get(v), w; function clr() { ed.destroy(); w.detachEvent('onunload', clr); w = w.tinyMCE = w.tinymce = null; // IE leak }; // Manager commands switch (c) { case "mceFocus": ed.focus(); return true; case "mceAddEditor": case "mceAddControl": if (!t.get(v)) new tinymce.Editor(v, t.settings).render(); return true; case "mceAddFrameControl": w = v.window; // Add tinyMCE global instance and tinymce namespace to specified window w.tinyMCE = tinyMCE; w.tinymce = tinymce; tinymce.DOM.doc = w.document; tinymce.DOM.win = w; ed = new tinymce.Editor(v.element_id, v); ed.render(); // Fix IE memory leaks if (tinymce.isIE) { w.attachEvent('onunload', clr); } v.page_window = null; return true; case "mceRemoveEditor": case "mceRemoveControl": if (ed) ed.remove(); return true; case 'mceToggleEditor': if (!ed) { t.execCommand('mceAddControl', 0, v); return true; } if (ed.isHidden()) ed.show(); else ed.hide(); return true; } // Run command on active editor if (t.activeEditor) return t.activeEditor.execCommand(c, u, v); return false; }, execInstanceCommand : function(id, c, u, v) { var ed = this.get(id); if (ed) return ed.execCommand(c, u, v); return false; }, triggerSave : function() { each(this.editors, function(e) { e.save(); }); }, addI18n : function(p, o) { var lo, i18n = this.i18n; if (!tinymce.is(p, 'string')) { each(p, function(o, lc) { each(o, function(o, g) { each(o, function(o, k) { if (g === 'common') i18n[lc + '.' + k] = o; else i18n[lc + '.' + g + '.' + k] = o; }); }); }); } else { each(o, function(o, k) { i18n[p + '.' + k] = o; }); } }, // Private methods _setActive : function(editor) { this.selectedInstance = this.activeEditor = editor; } }); })(tinymce); (function(tinymce) { // Shorten these names var DOM = tinymce.DOM, Event = tinymce.dom.Event, extend = tinymce.extend, each = tinymce.each, isGecko = tinymce.isGecko, isIE = tinymce.isIE, isWebKit = tinymce.isWebKit, is = tinymce.is, ThemeManager = tinymce.ThemeManager, PluginManager = tinymce.PluginManager, explode = tinymce.explode; tinymce.create('tinymce.Editor', { Editor : function(id, settings) { var self = this, TRUE = true; self.settings = settings = extend({ id : id, language : 'en', theme : 'simple', skin : 'default', delta_width : 0, delta_height : 0, popup_css : '', plugins : '', document_base_url : tinymce.documentBaseURL, add_form_submit_trigger : TRUE, submit_patch : TRUE, add_unload_trigger : TRUE, convert_urls : TRUE, relative_urls : TRUE, remove_script_host : TRUE, table_inline_editing : false, object_resizing : TRUE, accessibility_focus : TRUE, doctype : tinymce.isIE6 ? '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">' : '<!DOCTYPE>', // Use old doctype on IE 6 to avoid horizontal scroll visual : TRUE, font_size_style_values : 'xx-small,x-small,small,medium,large,x-large,xx-large', font_size_legacy_values : 'xx-small,small,medium,large,x-large,xx-large,300%', // See: http://www.w3.org/TR/CSS2/fonts.html#propdef-font-size apply_source_formatting : TRUE, directionality : 'ltr', forced_root_block : 'p', hidden_input : TRUE, padd_empty_editor : TRUE, render_ui : TRUE, indentation : '30px', fix_table_elements : TRUE, inline_styles : TRUE, convert_fonts_to_spans : TRUE, indent : 'simple', indent_before : 'p,h1,h2,h3,h4,h5,h6,blockquote,div,title,style,pre,script,td,ul,li,area,table,thead,tfoot,tbody,tr,section,article,hgroup,aside,figure', indent_after : 'p,h1,h2,h3,h4,h5,h6,blockquote,div,title,style,pre,script,td,ul,li,area,table,thead,tfoot,tbody,tr,section,article,hgroup,aside,figure', validate : TRUE, entity_encoding : 'named', url_converter : self.convertURL, url_converter_scope : self, ie7_compat : TRUE }, settings); self.id = self.editorId = id; self.isNotDirty = false; self.plugins = {}; self.documentBaseURI = new tinymce.util.URI(settings.document_base_url || tinymce.documentBaseURL, { base_uri : tinyMCE.baseURI }); self.baseURI = tinymce.baseURI; self.contentCSS = []; // Creates all events like onClick, onSetContent etc see Editor.Events.js for the actual logic self.setupEvents(); // Internal command handler objects self.execCommands = {}; self.queryStateCommands = {}; self.queryValueCommands = {}; // Call setup self.execCallback('setup', self); }, render : function(nst) { var t = this, s = t.settings, id = t.id, sl = tinymce.ScriptLoader; // Page is not loaded yet, wait for it if (!Event.domLoaded) { Event.add(window, 'ready', function() { t.render(); }); return; } tinyMCE.settings = s; // Element not found, then skip initialization if (!t.getElement()) return; // Is a iPad/iPhone and not on iOS5, then skip initialization. We need to sniff // here since the browser says it has contentEditable support but there is no visible caret. if (tinymce.isIDevice && !tinymce.isIOS5) return; // Add hidden input for non input elements inside form elements if (!/TEXTAREA|INPUT/i.test(t.getElement().nodeName) && s.hidden_input && DOM.getParent(id, 'form')) DOM.insertAfter(DOM.create('input', {type : 'hidden', name : id}), id); if (tinymce.WindowManager) t.windowManager = new tinymce.WindowManager(t); if (s.encoding == 'xml') { t.onGetContent.add(function(ed, o) { if (o.save) o.content = DOM.encode(o.content); }); } if (s.add_form_submit_trigger) { t.onSubmit.addToTop(function() { if (t.initialized) { t.save(); t.isNotDirty = 1; } }); } if (s.add_unload_trigger) { t._beforeUnload = tinyMCE.onBeforeUnload.add(function() { if (t.initialized && !t.destroyed && !t.isHidden()) t.save({format : 'raw', no_events : true}); }); } tinymce.addUnload(t.destroy, t); if (s.submit_patch) { t.onBeforeRenderUI.add(function() { var n = t.getElement().form; if (!n) return; // Already patched if (n._mceOldSubmit) return; // Check page uses id="submit" or name="submit" for it's submit button if (!n.submit.nodeType && !n.submit.length) { t.formElement = n; n._mceOldSubmit = n.submit; n.submit = function() { // Save all instances tinymce.triggerSave(); t.isNotDirty = 1; return t.formElement._mceOldSubmit(t.formElement); }; } n = null; }); } // Load scripts function loadScripts() { if (s.language && s.language_load !== false) sl.add(tinymce.baseURL + '/langs/' + s.language + '.js'); if (s.theme && s.theme.charAt(0) != '-' && !ThemeManager.urls[s.theme]) ThemeManager.load(s.theme, 'themes/' + s.theme + '/editor_template' + tinymce.suffix + '.js'); each(explode(s.plugins), function(p) { if (p &&!PluginManager.urls[p]) { if (p.charAt(0) == '-') { p = p.substr(1, p.length); var dependencies = PluginManager.dependencies(p); each(dependencies, function(dep) { var defaultSettings = {prefix:'plugins/', resource: dep, suffix:'/editor_plugin' + tinymce.suffix + '.js'}; dep = PluginManager.createUrl(defaultSettings, dep); PluginManager.load(dep.resource, dep); }); } else { // Skip safari plugin, since it is removed as of 3.3b1 if (p == 'safari') { return; } PluginManager.load(p, {prefix:'plugins/', resource: p, suffix:'/editor_plugin' + tinymce.suffix + '.js'}); } } }); // Init when que is loaded sl.loadQueue(function() { if (!t.removed) t.init(); }); }; loadScripts(); }, init : function() { var n, t = this, s = t.settings, w, h, e = t.getElement(), o, ti, u, bi, bc, re, i, initializedPlugins = []; tinymce.add(t); s.aria_label = s.aria_label || DOM.getAttrib(e, 'aria-label', t.getLang('aria.rich_text_area')); if (s.theme) { s.theme = s.theme.replace(/-/, ''); o = ThemeManager.get(s.theme); t.theme = new o(); if (t.theme.init) t.theme.init(t, ThemeManager.urls[s.theme] || tinymce.documentBaseURL.replace(/\/$/, '')); } function initPlugin(p) { var c = PluginManager.get(p), u = PluginManager.urls[p] || tinymce.documentBaseURL.replace(/\/$/, ''), po; if (c && tinymce.inArray(initializedPlugins,p) === -1) { each(PluginManager.dependencies(p), function(dep){ initPlugin(dep); }); po = new c(t, u); t.plugins[p] = po; if (po.init) { po.init(t, u); initializedPlugins.push(p); } } } // Create all plugins each(explode(s.plugins.replace(/\-/g, '')), initPlugin); // Setup popup CSS path(s) if (s.popup_css !== false) { if (s.popup_css) s.popup_css = t.documentBaseURI.toAbsolute(s.popup_css); else s.popup_css = t.baseURI.toAbsolute("themes/" + s.theme + "/skins/" + s.skin + "/dialog.css"); } if (s.popup_css_add) s.popup_css += ',' + t.documentBaseURI.toAbsolute(s.popup_css_add); t.controlManager = new tinymce.ControlManager(t); t.onExecCommand.add(function(ed, c) { // Don't refresh the select lists until caret move if (!/^(FontName|FontSize)$/.test(c)) t.nodeChanged(); }); // Enables users to override the control factory t.onBeforeRenderUI.dispatch(t, t.controlManager); // Measure box if (s.render_ui && t.theme) { w = s.width || e.style.width || e.offsetWidth; h = s.height || e.style.height || e.offsetHeight; t.orgDisplay = e.style.display; re = /^[0-9\.]+(|px)$/i; if (re.test('' + w)) w = Math.max(parseInt(w, 10) + (o.deltaWidth || 0), 100); if (re.test('' + h)) h = Math.max(parseInt(h, 10) + (o.deltaHeight || 0), 100); // Render UI o = t.theme.renderUI({ targetNode : e, width : w, height : h, deltaWidth : s.delta_width, deltaHeight : s.delta_height }); t.editorContainer = o.editorContainer; } // Load specified content CSS last if (s.content_css) { each(explode(s.content_css), function(u) { t.contentCSS.push(t.documentBaseURI.toAbsolute(u)); }); } // Content editable mode ends here if (s.content_editable) { e = n = o = null; // Fix IE leak return t.initContentBody(); } // User specified a document.domain value if (document.domain && location.hostname != document.domain) tinymce.relaxedDomain = document.domain; // Resize editor DOM.setStyles(o.sizeContainer || o.editorContainer, { width : w, height : h }); h = (o.iframeHeight || h) + (typeof(h) == 'number' ? (o.deltaHeight || 0) : ''); if (h < 100) h = 100; t.iframeHTML = s.doctype + '<html><head xmlns="http://www.w3.org/1999/xhtml">'; // We only need to override paths if we have to // IE has a bug where it remove site absolute urls to relative ones if this is specified if (s.document_base_url != tinymce.documentBaseURL) t.iframeHTML += '<base href="' + t.documentBaseURI.getURI() + '" />'; // IE8 doesn't support carets behind images setting ie7_compat would force IE8+ to run in IE7 compat mode. if (s.ie7_compat) t.iframeHTML += '<meta http-equiv="X-UA-Compatible" content="IE=7" />'; else t.iframeHTML += '<meta http-equiv="X-UA-Compatible" content="IE=edge" />'; t.iframeHTML += '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />'; // Load the CSS by injecting them into the HTML this will reduce "flicker" for (i = 0; i < t.contentCSS.length; i++) { t.iframeHTML += '<link type="text/css" rel="stylesheet" href="' + t.contentCSS[i] + '" />'; } t.contentCSS = []; bi = s.body_id || 'tinymce'; if (bi.indexOf('=') != -1) { bi = t.getParam('body_id', '', 'hash'); bi = bi[t.id] || bi; } bc = s.body_class || ''; if (bc.indexOf('=') != -1) { bc = t.getParam('body_class', '', 'hash'); bc = bc[t.id] || ''; } t.iframeHTML += '</head><body id="' + bi + '" class="mceContentBody ' + bc + '" onload="window.parent.tinyMCE.get(\'' + t.id + '\').onLoad.dispatch();"><br></body></html>'; // Domain relaxing enabled, then set document domain if (tinymce.relaxedDomain && (isIE || (tinymce.isOpera && parseFloat(opera.version()) < 11))) { // We need to write the contents here in IE since multiple writes messes up refresh button and back button u = 'javascript:(function(){document.open();document.domain="' + document.domain + '";var ed = window.parent.tinyMCE.get("' + t.id + '");document.write(ed.iframeHTML);document.close();ed.initContentBody();})()'; } // Create iframe // TODO: ACC add the appropriate description on this. n = DOM.add(o.iframeContainer, 'iframe', { id : t.id + "_ifr", src : u || 'javascript:""', // Workaround for HTTPS warning in IE6/7 frameBorder : '0', allowTransparency : "true", title : s.aria_label, style : { width : '100%', height : h, display : 'block' // Important for Gecko to render the iframe correctly } }); t.contentAreaContainer = o.iframeContainer; DOM.get(o.editorContainer).style.display = t.orgDisplay; DOM.get(t.id).style.display = 'none'; DOM.setAttrib(t.id, 'aria-hidden', true); if (!tinymce.relaxedDomain || !u) t.initContentBody(); e = n = o = null; // Cleanup }, initContentBody : function() { var self = this, settings = self.settings, targetElm = DOM.get(self.id), doc = self.getDoc(), html, body; // Setup iframe body if ((!isIE || !tinymce.relaxedDomain) && !settings.content_editable) { doc.open(); doc.write(self.iframeHTML); doc.close(); if (tinymce.relaxedDomain) doc.domain = tinymce.relaxedDomain; } if (settings.content_editable) { DOM.addClass(targetElm, 'mceContentBody'); self.contentDocument = doc = settings.content_document || document; self.contentWindow = settings.content_window || window; self.bodyElement = targetElm; // Prevent leak in IE settings.content_document = settings.content_window = null; } // It will not steal focus while setting contentEditable body = self.getBody(); body.disabled = true; if (!settings.readonly) body.contentEditable = self.getParam('content_editable_state', true); body.disabled = false; self.schema = new tinymce.html.Schema(settings); self.dom = new tinymce.dom.DOMUtils(doc, { keep_values : true, url_converter : self.convertURL, url_converter_scope : self, hex_colors : settings.force_hex_style_colors, class_filter : settings.class_filter, update_styles : true, root_element : settings.content_editable ? self.id : null, schema : self.schema }); self.parser = new tinymce.html.DomParser(settings, self.schema); // Convert src and href into data-mce-src, data-mce-href and data-mce-style self.parser.addAttributeFilter('src,href,style', function(nodes, name) { var i = nodes.length, node, dom = self.dom, value, internalName; while (i--) { node = nodes[i]; value = node.attr(name); internalName = 'data-mce-' + name; // Add internal attribute if we need to we don't on a refresh of the document if (!node.attributes.map[internalName]) { if (name === "style") node.attr(internalName, dom.serializeStyle(dom.parseStyle(value), node.name)); else node.attr(internalName, self.convertURL(value, name, node.name)); } } }); // Keep scripts from executing self.parser.addNodeFilter('script', function(nodes, name) { var i = nodes.length, node; while (i--) { node = nodes[i]; node.attr('type', 'mce-' + (node.attr('type') || 'text/javascript')); } }); self.parser.addNodeFilter('#cdata', function(nodes, name) { var i = nodes.length, node; while (i--) { node = nodes[i]; node.type = 8; node.name = '#comment'; node.value = '[CDATA[' + node.value + ']]'; } }); self.parser.addNodeFilter('p,h1,h2,h3,h4,h5,h6,div', function(nodes, name) { var i = nodes.length, node, nonEmptyElements = self.schema.getNonEmptyElements(); while (i--) { node = nodes[i]; if (node.isEmpty(nonEmptyElements)) node.empty().append(new tinymce.html.Node('br', 1)).shortEnded = true; } }); self.serializer = new tinymce.dom.Serializer(settings, self.dom, self.schema); self.selection = new tinymce.dom.Selection(self.dom, self.getWin(), self.serializer); self.formatter = new tinymce.Formatter(self); self.undoManager = new tinymce.UndoManager(self); self.forceBlocks = new tinymce.ForceBlocks(self); self.enterKey = new tinymce.EnterKey(self); self.editorCommands = new tinymce.EditorCommands(self); // Pass through self.serializer.onPreProcess.add(function(se, o) { return self.onPreProcess.dispatch(self, o, se); }); self.serializer.onPostProcess.add(function(se, o) { return self.onPostProcess.dispatch(self, o, se); }); self.onPreInit.dispatch(self); if (!settings.gecko_spellcheck) doc.body.spellcheck = false; if (!settings.readonly) { self.bindNativeEvents(); } self.controlManager.onPostRender.dispatch(self, self.controlManager); self.onPostRender.dispatch(self); self.quirks = tinymce.util.Quirks(self); if (settings.directionality) body.dir = settings.directionality; if (settings.nowrap) body.style.whiteSpace = "nowrap"; if (settings.protect) { self.onBeforeSetContent.add(function(ed, o) { each(settings.protect, function(pattern) { o.content = o.content.replace(pattern, function(str) { return '<!--mce:protected ' + escape(str) + '-->'; }); }); }); } // Add visual aids when new contents is added self.onSetContent.add(function() { self.addVisual(self.getBody()); }); // Remove empty contents if (settings.padd_empty_editor) { self.onPostProcess.add(function(ed, o) { o.content = o.content.replace(/^(<p[^>]*>(&nbsp;|&#160;|\s|\u00a0|)<\/p>[\r\n]*|<br \/>[\r\n]*)$/, ''); }); } self.load({initial : true, format : 'html'}); self.startContent = self.getContent({format : 'raw'}); self.initialized = true; self.onInit.dispatch(self); self.execCallback('setupcontent_callback', self.id, body, doc); self.execCallback('init_instance_callback', self); self.focus(true); self.nodeChanged({initial : true}); // Load specified content CSS last each(self.contentCSS, function(url) { self.dom.loadCSS(url); }); // Handle auto focus if (settings.auto_focus) { setTimeout(function () { var ed = tinymce.get(settings.auto_focus); ed.selection.select(ed.getBody(), 1); ed.selection.collapse(1); ed.getBody().focus(); ed.getWin().focus(); }, 100); } // Clean up references for IE targetElm = doc = body = null; }, focus : function(skip_focus) { var oed, self = this, selection = self.selection, contentEditable = self.settings.content_editable, ieRng, controlElm, doc = self.getDoc(), body; if (!skip_focus) { // Get selected control element ieRng = selection.getRng(); if (ieRng.item) { controlElm = ieRng.item(0); } self._refreshContentEditable(); // Focus the window iframe if (!contentEditable) { self.getWin().focus(); } // Focus the body as well since it's contentEditable if (tinymce.isGecko || contentEditable) { body = self.getBody(); // Check for setActive since it doesn't scroll to the element if (body.setActive) { body.setActive(); } else { body.focus(); } if (contentEditable) { selection.normalize(); } } // Restore selected control element // This is needed when for example an image is selected within a // layer a call to focus will then remove the control selection if (controlElm && controlElm.ownerDocument == doc) { ieRng = doc.body.createControlRange(); ieRng.addElement(controlElm); ieRng.select(); } } if (tinymce.activeEditor != self) { if ((oed = tinymce.activeEditor) != null) oed.onDeactivate.dispatch(oed, self); self.onActivate.dispatch(self, oed); } tinymce._setActive(self); }, execCallback : function(n) { var t = this, f = t.settings[n], s; if (!f) return; // Look through lookup if (t.callbackLookup && (s = t.callbackLookup[n])) { f = s.func; s = s.scope; } if (is(f, 'string')) { s = f.replace(/\.\w+$/, ''); s = s ? tinymce.resolve(s) : 0; f = tinymce.resolve(f); t.callbackLookup = t.callbackLookup || {}; t.callbackLookup[n] = {func : f, scope : s}; } return f.apply(s || t, Array.prototype.slice.call(arguments, 1)); }, translate : function(s) { var c = this.settings.language || 'en', i18n = tinymce.i18n; if (!s) return ''; return i18n[c + '.' + s] || s.replace(/\{\#([^\}]+)\}/g, function(a, b) { return i18n[c + '.' + b] || '{#' + b + '}'; }); }, getLang : function(n, dv) { return tinymce.i18n[(this.settings.language || 'en') + '.' + n] || (is(dv) ? dv : '{#' + n + '}'); }, getParam : function(n, dv, ty) { var tr = tinymce.trim, v = is(this.settings[n]) ? this.settings[n] : dv, o; if (ty === 'hash') { o = {}; if (is(v, 'string')) { each(v.indexOf('=') > 0 ? v.split(/[;,](?![^=;,]*(?:[;,]|$))/) : v.split(','), function(v) { v = v.split('='); if (v.length > 1) o[tr(v[0])] = tr(v[1]); else o[tr(v[0])] = tr(v); }); } else o = v; return o; } return v; }, nodeChanged : function(o) { var self = this, selection = self.selection, node; // Fix for bug #1896577 it seems that this can not be fired while the editor is loading if (self.initialized) { o = o || {}; // Normalize selection for example <b>a</b><i>|a</i> becomes <b>a|</b><i>a</i> selection.normalize(); // Get start node node = selection.getStart() || self.getBody(); node = isIE && node.ownerDocument != self.getDoc() ? self.getBody() : node; // Fix for IE initial state // Get parents and add them to object o.parents = []; self.dom.getParent(node, function(node) { if (node.nodeName == 'BODY') return true; o.parents.push(node); }); self.onNodeChange.dispatch( self, o ? o.controlManager || self.controlManager : self.controlManager, node, selection.isCollapsed(), o ); } }, addButton : function(name, settings) { var self = this; self.buttons = self.buttons || {}; self.buttons[name] = settings; }, addCommand : function(name, callback, scope) { this.execCommands[name] = {func : callback, scope : scope || this}; }, addQueryStateHandler : function(name, callback, scope) { this.queryStateCommands[name] = {func : callback, scope : scope || this}; }, addQueryValueHandler : function(name, callback, scope) { this.queryValueCommands[name] = {func : callback, scope : scope || this}; }, addShortcut : function(pa, desc, cmd_func, sc) { var t = this, c; if (t.settings.custom_shortcuts === false) return false; t.shortcuts = t.shortcuts || {}; if (is(cmd_func, 'string')) { c = cmd_func; cmd_func = function() { t.execCommand(c, false, null); }; } if (is(cmd_func, 'object')) { c = cmd_func; cmd_func = function() { t.execCommand(c[0], c[1], c[2]); }; } each(explode(pa), function(pa) { var o = { func : cmd_func, scope : sc || this, desc : t.translate(desc), alt : false, ctrl : false, shift : false }; each(explode(pa, '+'), function(v) { switch (v) { case 'alt': case 'ctrl': case 'shift': o[v] = true; break; default: o.charCode = v.charCodeAt(0); o.keyCode = v.toUpperCase().charCodeAt(0); } }); t.shortcuts[(o.ctrl ? 'ctrl' : '') + ',' + (o.alt ? 'alt' : '') + ',' + (o.shift ? 'shift' : '') + ',' + o.keyCode] = o; }); return true; }, execCommand : function(cmd, ui, val, a) { var t = this, s = 0, o, st; if (!/^(mceAddUndoLevel|mceEndUndoLevel|mceBeginUndoLevel|mceRepaint|SelectAll)$/.test(cmd) && (!a || !a.skip_focus)) t.focus(); a = extend({}, a); t.onBeforeExecCommand.dispatch(t, cmd, ui, val, a); if (a.terminate) return false; // Command callback if (t.execCallback('execcommand_callback', t.id, t.selection.getNode(), cmd, ui, val)) { t.onExecCommand.dispatch(t, cmd, ui, val, a); return true; } // Registred commands if (o = t.execCommands[cmd]) { st = o.func.call(o.scope, ui, val); // Fall through on true if (st !== true) { t.onExecCommand.dispatch(t, cmd, ui, val, a); return st; } } // Plugin commands each(t.plugins, function(p) { if (p.execCommand && p.execCommand(cmd, ui, val)) { t.onExecCommand.dispatch(t, cmd, ui, val, a); s = 1; return false; } }); if (s) return true; // Theme commands if (t.theme && t.theme.execCommand && t.theme.execCommand(cmd, ui, val)) { t.onExecCommand.dispatch(t, cmd, ui, val, a); return true; } // Editor commands if (t.editorCommands.execCommand(cmd, ui, val)) { t.onExecCommand.dispatch(t, cmd, ui, val, a); return true; } // Browser commands t.getDoc().execCommand(cmd, ui, val); t.onExecCommand.dispatch(t, cmd, ui, val, a); }, queryCommandState : function(cmd) { var t = this, o, s; // Is hidden then return undefined if (t._isHidden()) return; // Registred commands if (o = t.queryStateCommands[cmd]) { s = o.func.call(o.scope); // Fall though on true if (s !== true) return s; } // Registred commands o = t.editorCommands.queryCommandState(cmd); if (o !== -1) return o; // Browser commands try { return this.getDoc().queryCommandState(cmd); } catch (ex) { // Fails sometimes see bug: 1896577 } }, queryCommandValue : function(c) { var t = this, o, s; // Is hidden then return undefined if (t._isHidden()) return; // Registred commands if (o = t.queryValueCommands[c]) { s = o.func.call(o.scope); // Fall though on true if (s !== true) return s; } // Registred commands o = t.editorCommands.queryCommandValue(c); if (is(o)) return o; // Browser commands try { return this.getDoc().queryCommandValue(c); } catch (ex) { // Fails sometimes see bug: 1896577 } }, show : function() { var self = this; DOM.show(self.getContainer()); DOM.hide(self.id); self.load(); }, hide : function() { var self = this, doc = t.getDoc(); // Fixed bug where IE has a blinking cursor left from the editor if (isIE && doc) doc.execCommand('SelectAll'); // We must save before we hide so Safari doesn't crash self.save(); DOM.hide(self.getContainer()); DOM.setStyle(self.id, 'display', self.orgDisplay); }, isHidden : function() { return !DOM.isHidden(this.id); }, setProgressState : function(b, ti, o) { this.onSetProgressState.dispatch(this, b, ti, o); return b; }, load : function(o) { var t = this, e = t.getElement(), h; if (e) { o = o || {}; o.load = true; // Double encode existing entities in the value h = t.setContent(is(e.value) ? e.value : e.innerHTML, o); o.element = e; if (!o.no_events) t.onLoadContent.dispatch(t, o); o.element = e = null; return h; } }, save : function(o) { var t = this, e = t.getElement(), h, f; if (!e || !t.initialized) return; o = o || {}; o.save = true; o.element = e; h = o.content = t.getContent(o); if (!o.no_events) t.onSaveContent.dispatch(t, o); h = o.content; if (!/TEXTAREA|INPUT/i.test(e.nodeName)) { e.innerHTML = h; // Update hidden form element if (f = DOM.getParent(t.id, 'form')) { each(f.elements, function(e) { if (e.name == t.id) { e.value = h; return false; } }); } } else e.value = h; o.element = e = null; return h; }, setContent : function(content, args) { var self = this, rootNode, body = self.getBody(), forcedRootBlockName; // Setup args object args = args || {}; args.format = args.format || 'html'; args.set = true; args.content = content; // Do preprocessing if (!args.no_events) self.onBeforeSetContent.dispatch(self, args); content = args.content; // Padd empty content in Gecko and Safari. Commands will otherwise fail on the content // It will also be impossible to place the caret in the editor unless there is a BR element present if (!tinymce.isIE && (content.length === 0 || /^\s+$/.test(content))) { forcedRootBlockName = self.settings.forced_root_block; if (forcedRootBlockName) content = '<' + forcedRootBlockName + '><br data-mce-bogus="1"></' + forcedRootBlockName + '>'; else content = '<br data-mce-bogus="1">'; body.innerHTML = content; self.selection.select(body, true); self.selection.collapse(true); return; } // Parse and serialize the html if (args.format !== 'raw') { content = new tinymce.html.Serializer({}, self.schema).serialize( self.parser.parse(content) ); } // Set the new cleaned contents to the editor args.content = tinymce.trim(content); self.dom.setHTML(body, args.content); // Do post processing if (!args.no_events) self.onSetContent.dispatch(self, args); self.selection.normalize(); return args.content; }, getContent : function(args) { var self = this, content; // Setup args object args = args || {}; args.format = args.format || 'html'; args.get = true; args.getInner = true; // Do preprocessing if (!args.no_events) self.onBeforeGetContent.dispatch(self, args); // Get raw contents or by default the cleaned contents if (args.format == 'raw') content = self.getBody().innerHTML; else content = self.serializer.serialize(self.getBody(), args); args.content = tinymce.trim(content); // Do post processing if (!args.no_events) self.onGetContent.dispatch(self, args); return args.content; }, isDirty : function() { var self = this; return tinymce.trim(self.startContent) != tinymce.trim(self.getContent({format : 'raw', no_events : 1})) && !self.isNotDirty; }, getContainer : function() { var self = this; if (!self.container) self.container = DOM.get(self.editorContainer || self.id + '_parent'); return self.container; }, getContentAreaContainer : function() { return this.contentAreaContainer; }, getElement : function() { return DOM.get(this.settings.content_element || this.id); }, getWin : function() { var self = this, elm; if (!self.contentWindow) { elm = DOM.get(self.id + "_ifr"); if (elm) self.contentWindow = elm.contentWindow; } return self.contentWindow; }, getDoc : function() { var self = this, win; if (!self.contentDocument) { win = self.getWin(); if (win) self.contentDocument = win.document; } return self.contentDocument; }, getBody : function() { return this.bodyElement || this.getDoc().body; }, convertURL : function(url, name, elm) { var self = this, settings = self.settings; // Use callback instead if (settings.urlconverter_callback) return self.execCallback('urlconverter_callback', url, elm, true, name); // Don't convert link href since thats the CSS files that gets loaded into the editor also skip local file URLs if (!settings.convert_urls || (elm && elm.nodeName == 'LINK') || url.indexOf('file:') === 0) return url; // Convert to relative if (settings.relative_urls) return self.documentBaseURI.toRelative(url); // Convert to absolute url = self.documentBaseURI.toAbsolute(url, settings.remove_script_host); return url; }, addVisual : function(elm) { var self = this, settings = self.settings, dom = self.dom, cls; elm = elm || self.getBody(); if (!is(self.hasVisual)) self.hasVisual = settings.visual; each(dom.select('table,a', elm), function(elm) { var value; switch (elm.nodeName) { case 'TABLE': cls = settings.visual_table_class || 'mceItemTable'; value = dom.getAttrib(elm, 'border'); if (!value || value == '0') { if (self.hasVisual) dom.addClass(elm, cls); else dom.removeClass(elm, cls); } return; case 'A': value = dom.getAttrib(elm, 'name'); cls = 'mceItemAnchor'; if (value) { if (self.hasVisual) dom.addClass(elm, cls); else dom.removeClass(elm, cls); } return; } }); self.onVisualAid.dispatch(self, elm, self.hasVisual); }, remove : function() { var self = this, elm = self.getContainer(); if (!self.removed) { self.removed = 1; // Cancels post remove event execution self.hide(); // Don't clear the window or document if content editable // is enabled since other instances might still be present if (!self.settings.content_editable) { Event.clear(self.getWin()); Event.clear(self.getDoc()); } Event.clear(self.getBody()); Event.clear(self.formElement); Event.unbind(elm); self.execCallback('remove_instance_callback', self); self.onRemove.dispatch(self); // Clear all execCommand listeners this is required to avoid errors if the editor was removed inside another command self.onExecCommand.listeners = []; tinymce.remove(self); DOM.remove(elm); } }, destroy : function(s) { var t = this; // One time is enough if (t.destroyed) return; // We must unbind on Gecko since it would otherwise produce the pesky "attempt to run compile-and-go script on a cleared scope" message if (isGecko) { Event.unbind(t.getDoc()); Event.unbind(t.getWin()); Event.unbind(t.getBody()); } if (!s) { tinymce.removeUnload(t.destroy); tinyMCE.onBeforeUnload.remove(t._beforeUnload); // Manual destroy if (t.theme && t.theme.destroy) t.theme.destroy(); // Destroy controls, selection and dom t.controlManager.destroy(); t.selection.destroy(); t.dom.destroy(); } if (t.formElement) { t.formElement.submit = t.formElement._mceOldSubmit; t.formElement._mceOldSubmit = null; } t.contentAreaContainer = t.formElement = t.container = t.settings.content_element = t.bodyElement = t.contentDocument = t.contentWindow = null; if (t.selection) t.selection = t.selection.win = t.selection.dom = t.selection.dom.doc = null; t.destroyed = 1; }, // Internal functions _refreshContentEditable : function() { var self = this, body, parent; // Check if the editor was hidden and the re-initalize contentEditable mode by removing and adding the body again if (self._isHidden()) { body = self.getBody(); parent = body.parentNode; parent.removeChild(body); parent.appendChild(body); body.focus(); } }, _isHidden : function() { var s; if (!isGecko) return 0; // Weird, wheres that cursor selection? s = this.selection.getSel(); return (!s || !s.rangeCount || s.rangeCount === 0); } }); })(tinymce); (function(tinymce) { var each = tinymce.each; tinymce.Editor.prototype.setupEvents = function() { var self = this, settings = self.settings; // Add events to the editor each([ 'onPreInit', 'onBeforeRenderUI', 'onPostRender', 'onLoad', 'onInit', 'onRemove', 'onActivate', 'onDeactivate', 'onClick', 'onEvent', 'onMouseUp', 'onMouseDown', 'onDblClick', 'onKeyDown', 'onKeyUp', 'onKeyPress', 'onContextMenu', 'onSubmit', 'onReset', 'onPaste', 'onPreProcess', 'onPostProcess', 'onBeforeSetContent', 'onBeforeGetContent', 'onSetContent', 'onGetContent', 'onLoadContent', 'onSaveContent', 'onNodeChange', 'onChange', 'onBeforeExecCommand', 'onExecCommand', 'onUndo', 'onRedo', 'onVisualAid', 'onSetProgressState', 'onSetAttrib' ], function(name) { self[name] = new tinymce.util.Dispatcher(self); }); // Handle legacy cleanup_callback option if (settings.cleanup_callback) { self.onBeforeSetContent.add(function(ed, o) { o.content = ed.execCallback('cleanup_callback', 'insert_to_editor', o.content, o); }); self.onPreProcess.add(function(ed, o) { if (o.set) ed.execCallback('cleanup_callback', 'insert_to_editor_dom', o.node, o); if (o.get) ed.execCallback('cleanup_callback', 'get_from_editor_dom', o.node, o); }); self.onPostProcess.add(function(ed, o) { if (o.set) o.content = ed.execCallback('cleanup_callback', 'insert_to_editor', o.content, o); if (o.get) o.content = ed.execCallback('cleanup_callback', 'get_from_editor', o.content, o); }); } // Handle legacy save_callback option if (settings.save_callback) { self.onGetContent.add(function(ed, o) { if (o.save) o.content = ed.execCallback('save_callback', ed.id, o.content, ed.getBody()); }); } // Handle legacy handle_event_callback option if (settings.handle_event_callback) { self.onEvent.add(function(ed, e, o) { if (self.execCallback('handle_event_callback', e, ed, o) === false) Event.cancel(e); }); } // Handle legacy handle_node_change_callback option if (settings.handle_node_change_callback) { self.onNodeChange.add(function(ed, cm, n) { ed.execCallback('handle_node_change_callback', ed.id, n, -1, -1, true, ed.selection.isCollapsed()); }); } // Handle legacy save_callback option if (settings.save_callback) { self.onSaveContent.add(function(ed, o) { var h = ed.execCallback('save_callback', ed.id, o.content, ed.getBody()); if (h) o.content = h; }); } // Handle legacy onchange_callback option if (settings.onchange_callback) { self.onChange.add(function(ed, l) { ed.execCallback('onchange_callback', ed, l); }); } }; tinymce.Editor.prototype.bindNativeEvents = function() { // 'focus', 'blur', 'dblclick', 'beforedeactivate', submit, reset var self = this, i, settings = self.settings, dom = self.dom, nativeToDispatcherMap; nativeToDispatcherMap = { mouseup : 'onMouseUp', mousedown : 'onMouseDown', click : 'onClick', keyup : 'onKeyUp', keydown : 'onKeyDown', keypress : 'onKeyPress', submit : 'onSubmit', reset : 'onReset', contextmenu : 'onContextMenu', dblclick : 'onDblClick', paste : 'onPaste' // Doesn't work in all browsers yet }; // Handler that takes a native event and sends it out to a dispatcher like onKeyDown function eventHandler(evt, args) { var type = evt.type; // Don't fire events when it's removed if (self.removed) return; // Sends the native event out to a global dispatcher then to the specific event dispatcher if (self.onEvent.dispatch(self, evt, args) !== false) { self[nativeToDispatcherMap[evt.fakeType || evt.type]].dispatch(self, evt, args); } }; // Opera doesn't support focus event for contentEditable elements so we need to fake it function doOperaFocus(e) { self.focus(true); }; // Add DOM events each(nativeToDispatcherMap, function(dispatcherName, nativeName) { var root = settings.content_editable ? self.getBody() : self.getDoc(); switch (nativeName) { case 'contextmenu': dom.bind(root, nativeName, eventHandler); break; case 'paste': dom.bind(self.getBody(), nativeName, eventHandler); break; case 'submit': case 'reset': dom.bind(self.getElement().form || tinymce.DOM.getParent(self.id, 'form'), nativeName, eventHandler); break; default: dom.bind(root, nativeName, eventHandler); } }); // Set the editor as active when focused dom.bind(settings.content_editable ? self.getBody() : (tinymce.isGecko ? self.getDoc() : self.getWin()), 'focus', function(e) { self.focus(true); }); if (settings.content_editable && tinymce.isOpera) { dom.bind(self.getBody(), 'click', doOperaFocus); dom.bind(self.getBody(), 'keydown', doOperaFocus); } // Add node change handler self.onMouseUp.add(self.nodeChanged); self.onKeyUp.add(function(ed, e) { var keyCode = e.keyCode; if ((keyCode >= 33 && keyCode <= 36) || (keyCode >= 37 && keyCode <= 40) || keyCode == 13 || keyCode == 45 || keyCode == 46 || keyCode == 8 || (tinymce.isMac && (keyCode == 91 || keyCode == 93)) || e.ctrlKey) self.nodeChanged(); }); // Add reset handler self.onReset.add(function() { self.setContent(self.startContent, {format : 'raw'}); }); // Add shortcuts function handleShortcut(e, execute) { if (e.altKey || e.ctrlKey || e.metaKey) { each(self.shortcuts, function(shortcut) { var ctrlState = tinymce.isMac ? e.metaKey : e.ctrlKey; if (shortcut.ctrl != ctrlState || shortcut.alt != e.altKey || shortcut.shift != e.shiftKey) return; if (e.keyCode == shortcut.keyCode || (e.charCode && e.charCode == shortcut.charCode)) { e.preventDefault(); if (execute) { shortcut.func.call(shortcut.scope); } return true; } }); } }; self.onKeyUp.add(function(ed, e) { handleShortcut(e); }); self.onKeyPress.add(function(ed, e) { handleShortcut(e); }); self.onKeyDown.add(function(ed, e) { handleShortcut(e, true); }); if (tinymce.isOpera) { self.onClick.add(function(ed, e) { e.preventDefault(); }); } }; })(tinymce); (function(tinymce) { // Added for compression purposes var each = tinymce.each, undef, TRUE = true, FALSE = false; tinymce.EditorCommands = function(editor) { var dom = editor.dom, selection = editor.selection, commands = {state: {}, exec : {}, value : {}}, settings = editor.settings, formatter = editor.formatter, bookmark; function execCommand(command, ui, value) { var func; command = command.toLowerCase(); if (func = commands.exec[command]) { func(command, ui, value); return TRUE; } return FALSE; }; function queryCommandState(command) { var func; command = command.toLowerCase(); if (func = commands.state[command]) return func(command); return -1; }; function queryCommandValue(command) { var func; command = command.toLowerCase(); if (func = commands.value[command]) return func(command); return FALSE; }; function addCommands(command_list, type) { type = type || 'exec'; each(command_list, function(callback, command) { each(command.toLowerCase().split(','), function(command) { commands[type][command] = callback; }); }); }; // Expose public methods tinymce.extend(this, { execCommand : execCommand, queryCommandState : queryCommandState, queryCommandValue : queryCommandValue, addCommands : addCommands }); // Private methods function execNativeCommand(command, ui, value) { if (ui === undef) ui = FALSE; if (value === undef) value = null; return editor.getDoc().execCommand(command, ui, value); }; function isFormatMatch(name) { return formatter.match(name); }; function toggleFormat(name, value) { formatter.toggle(name, value ? {value : value} : undef); }; function storeSelection(type) { bookmark = selection.getBookmark(type); }; function restoreSelection() { selection.moveToBookmark(bookmark); }; // Add execCommand overrides addCommands({ // Ignore these, added for compatibility 'mceResetDesignMode,mceBeginUndoLevel' : function() {}, // Add undo manager logic 'mceEndUndoLevel,mceAddUndoLevel' : function() { editor.undoManager.add(); }, 'Cut,Copy,Paste' : function(command) { var doc = editor.getDoc(), failed; // Try executing the native command try { execNativeCommand(command); } catch (ex) { // Command failed failed = TRUE; } // Present alert message about clipboard access not being available if (failed || !doc.queryCommandSupported(command)) { if (tinymce.isGecko) { editor.windowManager.confirm(editor.getLang('clipboard_msg'), function(state) { if (state) open('http://www.mozilla.org/editor/midasdemo/securityprefs.html', '_blank'); }); } else editor.windowManager.alert(editor.getLang('clipboard_no_support')); } }, // Override unlink command unlink : function(command) { if (selection.isCollapsed()) selection.select(selection.getNode()); execNativeCommand(command); selection.collapse(FALSE); }, // Override justify commands to use the text formatter engine 'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull' : function(command) { var align = command.substring(7); // Remove all other alignments first each('left,center,right,full'.split(','), function(name) { if (align != name) formatter.remove('align' + name); }); toggleFormat('align' + align); execCommand('mceRepaint'); }, // Override list commands to fix WebKit bug 'InsertUnorderedList,InsertOrderedList' : function(command) { var listElm, listParent; execNativeCommand(command); // WebKit produces lists within block elements so we need to split them // we will replace the native list creation logic to custom logic later on // TODO: Remove this when the list creation logic is removed listElm = dom.getParent(selection.getNode(), 'ol,ul'); if (listElm) { listParent = listElm.parentNode; // If list is within a text block then split that block if (/^(H[1-6]|P|ADDRESS|PRE)$/.test(listParent.nodeName)) { storeSelection(); dom.split(listParent, listElm); restoreSelection(); } } }, // Override commands to use the text formatter engine 'Bold,Italic,Underline,Strikethrough,Superscript,Subscript' : function(command) { toggleFormat(command); }, // Override commands to use the text formatter engine 'ForeColor,HiliteColor,FontName' : function(command, ui, value) { toggleFormat(command, value); }, FontSize : function(command, ui, value) { var fontClasses, fontSizes; // Convert font size 1-7 to styles if (value >= 1 && value <= 7) { fontSizes = tinymce.explode(settings.font_size_style_values); fontClasses = tinymce.explode(settings.font_size_classes); if (fontClasses) value = fontClasses[value - 1] || value; else value = fontSizes[value - 1] || value; } toggleFormat(command, value); }, RemoveFormat : function(command) { formatter.remove(command); }, mceBlockQuote : function(command) { toggleFormat('blockquote'); }, FormatBlock : function(command, ui, value) { return toggleFormat(value || 'p'); }, mceCleanup : function() { var bookmark = selection.getBookmark(); editor.setContent(editor.getContent({cleanup : TRUE}), {cleanup : TRUE}); selection.moveToBookmark(bookmark); }, mceRemoveNode : function(command, ui, value) { var node = value || selection.getNode(); // Make sure that the body node isn't removed if (node != editor.getBody()) { storeSelection(); editor.dom.remove(node, TRUE); restoreSelection(); } }, mceSelectNodeDepth : function(command, ui, value) { var counter = 0; dom.getParent(selection.getNode(), function(node) { if (node.nodeType == 1 && counter++ == value) { selection.select(node); return FALSE; } }, editor.getBody()); }, mceSelectNode : function(command, ui, value) { selection.select(value); }, mceInsertContent : function(command, ui, value) { var parser, serializer, parentNode, rootNode, fragment, args, marker, nodeRect, viewPortRect, rng, node, node2, bookmarkHtml, viewportBodyElement; //selection.normalize(); // Setup parser and serializer parser = editor.parser; serializer = new tinymce.html.Serializer({}, editor.schema); bookmarkHtml = '<span id="mce_marker" data-mce-type="bookmark">\uFEFF</span>'; // Run beforeSetContent handlers on the HTML to be inserted args = {content: value, format: 'html'}; selection.onBeforeSetContent.dispatch(selection, args); value = args.content; // Add caret at end of contents if it's missing if (value.indexOf('{$caret}') == -1) value += '{$caret}'; // Replace the caret marker with a span bookmark element value = value.replace(/\{\$caret\}/, bookmarkHtml); // Insert node maker where we will insert the new HTML and get it's parent if (!selection.isCollapsed()) editor.getDoc().execCommand('Delete', false, null); parentNode = selection.getNode(); // Parse the fragment within the context of the parent node args = {context : parentNode.nodeName.toLowerCase()}; fragment = parser.parse(value, args); // Move the caret to a more suitable location node = fragment.lastChild; if (node.attr('id') == 'mce_marker') { marker = node; for (node = node.prev; node; node = node.walk(true)) { if (node.type == 3 || !dom.isBlock(node.name)) { node.parent.insert(marker, node, node.name === 'br'); break; } } } // If parser says valid we can insert the contents into that parent if (!args.invalid) { value = serializer.serialize(fragment); // Check if parent is empty or only has one BR element then set the innerHTML of that parent node = parentNode.firstChild; node2 = parentNode.lastChild; if (!node || (node === node2 && node.nodeName === 'BR')) dom.setHTML(parentNode, value); else selection.setContent(value); } else { // If the fragment was invalid within that context then we need // to parse and process the parent it's inserted into // Insert bookmark node and get the parent selection.setContent(bookmarkHtml); parentNode = editor.selection.getNode(); rootNode = editor.getBody(); // Opera will return the document node when selection is in root if (parentNode.nodeType == 9) parentNode = node = rootNode; else node = parentNode; // Find the ancestor just before the root element while (node !== rootNode) { parentNode = node; node = node.parentNode; } // Get the outer/inner HTML depending on if we are in the root and parser and serialize that value = parentNode == rootNode ? rootNode.innerHTML : dom.getOuterHTML(parentNode); value = serializer.serialize( parser.parse( // Need to replace by using a function since $ in the contents would otherwise be a problem value.replace(/<span (id="mce_marker"|id=mce_marker).+?<\/span>/i, function() { return serializer.serialize(fragment); }) ) ); // Set the inner/outer HTML depending on if we are in the root or not if (parentNode == rootNode) dom.setHTML(rootNode, value); else dom.setOuterHTML(parentNode, value); } marker = dom.get('mce_marker'); // Scroll range into view scrollIntoView on element can't be used since it will scroll the main view port as well nodeRect = dom.getRect(marker); viewPortRect = dom.getViewPort(editor.getWin()); // Check if node is out side the viewport if it is then scroll to it if ((nodeRect.y + nodeRect.h > viewPortRect.y + viewPortRect.h || nodeRect.y < viewPortRect.y) || (nodeRect.x > viewPortRect.x + viewPortRect.w || nodeRect.x < viewPortRect.x)) { viewportBodyElement = tinymce.isIE ? editor.getDoc().documentElement : editor.getBody(); viewportBodyElement.scrollLeft = nodeRect.x; viewportBodyElement.scrollTop = nodeRect.y - viewPortRect.h + 25; } // Move selection before marker and remove it rng = dom.createRng(); // If previous sibling is a text node set the selection to the end of that node node = marker.previousSibling; if (node && node.nodeType == 3) { rng.setStart(node, node.nodeValue.length); } else { // If the previous sibling isn't a text node or doesn't exist set the selection before the marker node rng.setStartBefore(marker); rng.setEndBefore(marker); } // Remove the marker node and set the new range dom.remove(marker); selection.setRng(rng); // Dispatch after event and add any visual elements needed selection.onSetContent.dispatch(selection, args); editor.addVisual(); }, mceInsertRawHTML : function(command, ui, value) { selection.setContent('tiny_mce_marker'); editor.setContent(editor.getContent().replace(/tiny_mce_marker/g, function() { return value })); }, mceSetContent : function(command, ui, value) { editor.setContent(value); }, 'Indent,Outdent' : function(command) { var intentValue, indentUnit, value; // Setup indent level intentValue = settings.indentation; indentUnit = /[a-z%]+$/i.exec(intentValue); intentValue = parseInt(intentValue); if (!queryCommandState('InsertUnorderedList') && !queryCommandState('InsertOrderedList')) { // If forced_root_blocks is set to false we don't have a block to indent so lets create a div if (!settings.forced_root_block && !dom.getParent(selection.getNode(), dom.isBlock)) { formatter.apply('div'); } each(selection.getSelectedBlocks(), function(element) { if (command == 'outdent') { value = Math.max(0, parseInt(element.style.paddingLeft || 0) - intentValue); dom.setStyle(element, 'paddingLeft', value ? value + indentUnit : ''); } else dom.setStyle(element, 'paddingLeft', (parseInt(element.style.paddingLeft || 0) + intentValue) + indentUnit); }); } else execNativeCommand(command); }, mceRepaint : function() { var bookmark; if (tinymce.isGecko) { try { storeSelection(TRUE); if (selection.getSel()) selection.getSel().selectAllChildren(editor.getBody()); selection.collapse(TRUE); restoreSelection(); } catch (ex) { // Ignore } } }, mceToggleFormat : function(command, ui, value) { formatter.toggle(value); }, InsertHorizontalRule : function() { editor.execCommand('mceInsertContent', false, '<hr />'); }, mceToggleVisualAid : function() { editor.hasVisual = !editor.hasVisual; editor.addVisual(); }, mceReplaceContent : function(command, ui, value) { editor.execCommand('mceInsertContent', false, value.replace(/\{\$selection\}/g, selection.getContent({format : 'text'}))); }, mceInsertLink : function(command, ui, value) { var anchor; if (typeof(value) == 'string') value = {href : value}; anchor = dom.getParent(selection.getNode(), 'a'); // Spaces are never valid in URLs and it's a very common mistake for people to make so we fix it here. value.href = value.href.replace(' ', '%20'); // Remove existing links if there could be child links or that the href isn't specified if (!anchor || !value.href) { formatter.remove('link'); } // Apply new link to selection if (value.href) { formatter.apply('link', value, anchor); } }, selectAll : function() { var root = dom.getRoot(), rng = dom.createRng(); rng.setStart(root, 0); rng.setEnd(root, root.childNodes.length); editor.selection.setRng(rng); } }); // Add queryCommandState overrides addCommands({ // Override justify commands 'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull' : function(command) { var name = 'align' + command.substring(7); // Use Formatter.matchNode instead of Formatter.match so that we don't match on parent node. This fixes bug where for both left // and right align buttons can be active. This could occur when selected nodes have align right and the parent has align left. var nodes = selection.isCollapsed() ? [selection.getNode()] : selection.getSelectedBlocks(); var matches = tinymce.map(nodes, function(node) { return !!formatter.matchNode(node, name); }); return tinymce.inArray(matches, TRUE) !== -1; }, 'Bold,Italic,Underline,Strikethrough,Superscript,Subscript' : function(command) { return isFormatMatch(command); }, mceBlockQuote : function() { return isFormatMatch('blockquote'); }, Outdent : function() { var node; if (settings.inline_styles) { if ((node = dom.getParent(selection.getStart(), dom.isBlock)) && parseInt(node.style.paddingLeft) > 0) return TRUE; if ((node = dom.getParent(selection.getEnd(), dom.isBlock)) && parseInt(node.style.paddingLeft) > 0) return TRUE; } return queryCommandState('InsertUnorderedList') || queryCommandState('InsertOrderedList') || (!settings.inline_styles && !!dom.getParent(selection.getNode(), 'BLOCKQUOTE')); }, 'InsertUnorderedList,InsertOrderedList' : function(command) { return dom.getParent(selection.getNode(), command == 'insertunorderedlist' ? 'UL' : 'OL'); } }, 'state'); // Add queryCommandValue overrides addCommands({ 'FontSize,FontName' : function(command) { var value = 0, parent; if (parent = dom.getParent(selection.getNode(), 'span')) { if (command == 'fontsize') value = parent.style.fontSize; else value = parent.style.fontFamily.replace(/, /g, ',').replace(/[\'\"]/g, '').toLowerCase(); } return value; } }, 'value'); // Add undo manager logic addCommands({ Undo : function() { editor.undoManager.undo(); }, Redo : function() { editor.undoManager.redo(); } }); }; })(tinymce); (function(tinymce) { var Dispatcher = tinymce.util.Dispatcher; tinymce.UndoManager = function(editor) { var self, index = 0, data = [], beforeBookmark, onAdd, onUndo, onRedo; function getContent() { // Remove whitespace before/after and remove pure bogus nodes return tinymce.trim(editor.getContent({format : 'raw', no_events : 1}).replace(/<span[^>]+data-mce-bogus[^>]+>[\u200B\uFEFF]+<\/span>/g, '')); }; function addNonTypingUndoLevel() { self.typing = false; self.add(); }; // Create event instances onAdd = new Dispatcher(self); onUndo = new Dispatcher(self); onRedo = new Dispatcher(self); // Pass though onAdd event from UndoManager to Editor as onChange onAdd.add(function(undoman, level) { if (undoman.hasUndo()) return editor.onChange.dispatch(editor, level, undoman); }); // Pass though onUndo event from UndoManager to Editor onUndo.add(function(undoman, level) { return editor.onUndo.dispatch(editor, level, undoman); }); // Pass though onRedo event from UndoManager to Editor onRedo.add(function(undoman, level) { return editor.onRedo.dispatch(editor, level, undoman); }); // Add initial undo level when the editor is initialized editor.onInit.add(function() { self.add(); }); // Get position before an execCommand is processed editor.onBeforeExecCommand.add(function(ed, cmd, ui, val, args) { if (cmd != 'Undo' && cmd != 'Redo' && cmd != 'mceRepaint' && (!args || !args.skip_undo)) { self.beforeChange(); } }); // Add undo level after an execCommand call was made editor.onExecCommand.add(function(ed, cmd, ui, val, args) { if (cmd != 'Undo' && cmd != 'Redo' && cmd != 'mceRepaint' && (!args || !args.skip_undo)) { self.add(); } }); // Add undo level on save contents, drag end and blur/focusout editor.onSaveContent.add(addNonTypingUndoLevel); editor.dom.bind(editor.dom.getRoot(), 'dragend', addNonTypingUndoLevel); editor.dom.bind(editor.getDoc(), tinymce.isGecko ? 'blur' : 'focusout', function(e) { if (!editor.removed && self.typing) { addNonTypingUndoLevel(); } }); editor.onKeyUp.add(function(editor, e) { var keyCode = e.keyCode; if ((keyCode >= 33 && keyCode <= 36) || (keyCode >= 37 && keyCode <= 40) || keyCode == 45 || keyCode == 13 || e.ctrlKey) { addNonTypingUndoLevel(); } }); editor.onKeyDown.add(function(editor, e) { var keyCode = e.keyCode; // Is caracter positon keys left,right,up,down,home,end,pgdown,pgup,enter if ((keyCode >= 33 && keyCode <= 36) || (keyCode >= 37 && keyCode <= 40) || keyCode == 45) { if (self.typing) { addNonTypingUndoLevel(); } return; } // If key isn't shift,ctrl,alt,capslock,metakey if ((keyCode < 16 || keyCode > 20) && keyCode != 224 && keyCode != 91 && !self.typing) { self.beforeChange(); self.typing = true; self.add(); } }); editor.onMouseDown.add(function(editor, e) { if (self.typing) { addNonTypingUndoLevel(); } }); // Add keyboard shortcuts for undo/redo keys editor.addShortcut('ctrl+z', 'undo_desc', 'Undo'); editor.addShortcut('ctrl+y', 'redo_desc', 'Redo'); self = { // Explose for debugging reasons data : data, typing : false, onAdd : onAdd, onUndo : onUndo, onRedo : onRedo, beforeChange : function() { beforeBookmark = editor.selection.getBookmark(2, true); }, add : function(level) { var i, settings = editor.settings, lastLevel; level = level || {}; level.content = getContent(); // Add undo level if needed lastLevel = data[index]; if (lastLevel && lastLevel.content == level.content) return null; // Set before bookmark on previous level if (data[index]) data[index].beforeBookmark = beforeBookmark; // Time to compress if (settings.custom_undo_redo_levels) { if (data.length > settings.custom_undo_redo_levels) { for (i = 0; i < data.length - 1; i++) data[i] = data[i + 1]; data.length--; index = data.length; } } // Get a non intrusive normalized bookmark level.bookmark = editor.selection.getBookmark(2, true); // Crop array if needed if (index < data.length - 1) data.length = index + 1; data.push(level); index = data.length - 1; self.onAdd.dispatch(self, level); editor.isNotDirty = 0; return level; }, undo : function() { var level, i; if (self.typing) { self.add(); self.typing = false; } if (index > 0) { level = data[--index]; editor.setContent(level.content, {format : 'raw'}); editor.selection.moveToBookmark(level.beforeBookmark); self.onUndo.dispatch(self, level); } return level; }, redo : function() { var level; if (index < data.length - 1) { level = data[++index]; editor.setContent(level.content, {format : 'raw'}); editor.selection.moveToBookmark(level.bookmark); self.onRedo.dispatch(self, level); } return level; }, clear : function() { data = []; index = 0; self.typing = false; }, hasUndo : function() { return index > 0 || this.typing; }, hasRedo : function() { return index < data.length - 1 && !this.typing; } }; return self; }; })(tinymce); tinymce.ForceBlocks = function(editor) { var settings = editor.settings, dom = editor.dom, selection = editor.selection, blockElements = editor.schema.getBlockElements(); function addRootBlocks() { var node = selection.getStart(), rootNode = editor.getBody(), rng, startContainer, startOffset, endContainer, endOffset, rootBlockNode, tempNode, offset = -0xFFFFFF; if (!node || node.nodeType !== 1 || !settings.forced_root_block) return; // Check if node is wrapped in block while (node != rootNode) { if (blockElements[node.nodeName]) return; node = node.parentNode; } // Get current selection rng = selection.getRng(); if (rng.setStart) { startContainer = rng.startContainer; startOffset = rng.startOffset; endContainer = rng.endContainer; endOffset = rng.endOffset; } else { // Force control range into text range if (rng.item) { node = rng.item(0); rng = editor.getDoc().body.createTextRange(); rng.moveToElementText(node); } tmpRng = rng.duplicate(); tmpRng.collapse(true); startOffset = tmpRng.move('character', offset) * -1; if (!tmpRng.collapsed) { tmpRng = rng.duplicate(); tmpRng.collapse(false); endOffset = (tmpRng.move('character', offset) * -1) - startOffset; } } // Wrap non block elements and text nodes node = rootNode.firstChild; while (node) { if (node.nodeType === 3 || (node.nodeType == 1 && !blockElements[node.nodeName])) { if (!rootBlockNode) { rootBlockNode = dom.create(settings.forced_root_block); node.parentNode.insertBefore(rootBlockNode, node); } tempNode = node; node = node.nextSibling; rootBlockNode.appendChild(tempNode); } else { rootBlockNode = null; node = node.nextSibling; } } if (rng.setStart) { rng.setStart(startContainer, startOffset); rng.setEnd(endContainer, endOffset); selection.setRng(rng); } else { try { rng = editor.getDoc().body.createTextRange(); rng.moveToElementText(rootNode); rng.collapse(true); rng.moveStart('character', startOffset); if (endOffset > 0) rng.moveEnd('character', endOffset); rng.select(); } catch (ex) { // Ignore } } editor.nodeChanged(); }; // Force root blocks if (settings.forced_root_block) { editor.onKeyUp.add(addRootBlocks); editor.onClick.add(addRootBlocks); } }; (function(tinymce) { // Shorten names var DOM = tinymce.DOM, Event = tinymce.dom.Event, each = tinymce.each, extend = tinymce.extend; tinymce.create('tinymce.ControlManager', { ControlManager : function(ed, s) { var t = this, i; s = s || {}; t.editor = ed; t.controls = {}; t.onAdd = new tinymce.util.Dispatcher(t); t.onPostRender = new tinymce.util.Dispatcher(t); t.prefix = s.prefix || ed.id + '_'; t._cls = {}; t.onPostRender.add(function() { each(t.controls, function(c) { c.postRender(); }); }); }, get : function(id) { return this.controls[this.prefix + id] || this.controls[id]; }, setActive : function(id, s) { var c = null; if (c = this.get(id)) c.setActive(s); return c; }, setDisabled : function(id, s) { var c = null; if (c = this.get(id)) c.setDisabled(s); return c; }, add : function(c) { var t = this; if (c) { t.controls[c.id] = c; t.onAdd.dispatch(c, t); } return c; }, createControl : function(n) { var c, t = this, ed = t.editor; each(ed.plugins, function(p) { if (p.createControl) { c = p.createControl(n, t); if (c) return false; } }); switch (n) { case "|": case "separator": return t.createSeparator(); } if (!c && ed.buttons && (c = ed.buttons[n])) return t.createButton(n, c); return t.add(c); }, createDropMenu : function(id, s, cc) { var t = this, ed = t.editor, c, bm, v, cls; s = extend({ 'class' : 'mceDropDown', constrain : ed.settings.constrain_menus }, s); s['class'] = s['class'] + ' ' + ed.getParam('skin') + 'Skin'; if (v = ed.getParam('skin_variant')) s['class'] += ' ' + ed.getParam('skin') + 'Skin' + v.substring(0, 1).toUpperCase() + v.substring(1); id = t.prefix + id; cls = cc || t._cls.dropmenu || tinymce.ui.DropMenu; c = t.controls[id] = new cls(id, s); c.onAddItem.add(function(c, o) { var s = o.settings; s.title = ed.getLang(s.title, s.title); if (!s.onclick) { s.onclick = function(v) { if (s.cmd) ed.execCommand(s.cmd, s.ui || false, s.value); }; } }); ed.onRemove.add(function() { c.destroy(); }); // Fix for bug #1897785, #1898007 if (tinymce.isIE) { c.onShowMenu.add(function() { // IE 8 needs focus in order to store away a range with the current collapsed caret location ed.focus(); bm = ed.selection.getBookmark(1); }); c.onHideMenu.add(function() { if (bm) { ed.selection.moveToBookmark(bm); bm = 0; } }); } return t.add(c); }, createListBox : function(id, s, cc) { var t = this, ed = t.editor, cmd, c, cls; if (t.get(id)) return null; s.title = ed.translate(s.title); s.scope = s.scope || ed; if (!s.onselect) { s.onselect = function(v) { ed.execCommand(s.cmd, s.ui || false, v || s.value); }; } s = extend({ title : s.title, 'class' : 'mce_' + id, scope : s.scope, control_manager : t }, s); id = t.prefix + id; function useNativeListForAccessibility(ed) { return ed.settings.use_accessible_selects && !tinymce.isGecko } if (ed.settings.use_native_selects || useNativeListForAccessibility(ed)) c = new tinymce.ui.NativeListBox(id, s); else { cls = cc || t._cls.listbox || tinymce.ui.ListBox; c = new cls(id, s, ed); } t.controls[id] = c; // Fix focus problem in Safari if (tinymce.isWebKit) { c.onPostRender.add(function(c, n) { // Store bookmark on mousedown Event.add(n, 'mousedown', function() { ed.bookmark = ed.selection.getBookmark(1); }); // Restore on focus, since it might be lost Event.add(n, 'focus', function() { ed.selection.moveToBookmark(ed.bookmark); ed.bookmark = null; }); }); } if (c.hideMenu) ed.onMouseDown.add(c.hideMenu, c); return t.add(c); }, createButton : function(id, s, cc) { var t = this, ed = t.editor, o, c, cls; if (t.get(id)) return null; s.title = ed.translate(s.title); s.label = ed.translate(s.label); s.scope = s.scope || ed; if (!s.onclick && !s.menu_button) { s.onclick = function() { ed.execCommand(s.cmd, s.ui || false, s.value); }; } s = extend({ title : s.title, 'class' : 'mce_' + id, unavailable_prefix : ed.getLang('unavailable', ''), scope : s.scope, control_manager : t }, s); id = t.prefix + id; if (s.menu_button) { cls = cc || t._cls.menubutton || tinymce.ui.MenuButton; c = new cls(id, s, ed); ed.onMouseDown.add(c.hideMenu, c); } else { cls = t._cls.button || tinymce.ui.Button; c = new cls(id, s, ed); } return t.add(c); }, createMenuButton : function(id, s, cc) { s = s || {}; s.menu_button = 1; return this.createButton(id, s, cc); }, createSplitButton : function(id, s, cc) { var t = this, ed = t.editor, cmd, c, cls; if (t.get(id)) return null; s.title = ed.translate(s.title); s.scope = s.scope || ed; if (!s.onclick) { s.onclick = function(v) { ed.execCommand(s.cmd, s.ui || false, v || s.value); }; } if (!s.onselect) { s.onselect = function(v) { ed.execCommand(s.cmd, s.ui || false, v || s.value); }; } s = extend({ title : s.title, 'class' : 'mce_' + id, scope : s.scope, control_manager : t }, s); id = t.prefix + id; cls = cc || t._cls.splitbutton || tinymce.ui.SplitButton; c = t.add(new cls(id, s, ed)); ed.onMouseDown.add(c.hideMenu, c); return c; }, createColorSplitButton : function(id, s, cc) { var t = this, ed = t.editor, cmd, c, cls, bm; if (t.get(id)) return null; s.title = ed.translate(s.title); s.scope = s.scope || ed; if (!s.onclick) { s.onclick = function(v) { if (tinymce.isIE) bm = ed.selection.getBookmark(1); ed.execCommand(s.cmd, s.ui || false, v || s.value); }; } if (!s.onselect) { s.onselect = function(v) { ed.execCommand(s.cmd, s.ui || false, v || s.value); }; } s = extend({ title : s.title, 'class' : 'mce_' + id, 'menu_class' : ed.getParam('skin') + 'Skin', scope : s.scope, more_colors_title : ed.getLang('more_colors') }, s); id = t.prefix + id; cls = cc || t._cls.colorsplitbutton || tinymce.ui.ColorSplitButton; c = new cls(id, s, ed); ed.onMouseDown.add(c.hideMenu, c); // Remove the menu element when the editor is removed ed.onRemove.add(function() { c.destroy(); }); // Fix for bug #1897785, #1898007 if (tinymce.isIE) { c.onShowMenu.add(function() { // IE 8 needs focus in order to store away a range with the current collapsed caret location ed.focus(); bm = ed.selection.getBookmark(1); }); c.onHideMenu.add(function() { if (bm) { ed.selection.moveToBookmark(bm); bm = 0; } }); } return t.add(c); }, createToolbar : function(id, s, cc) { var c, t = this, cls; id = t.prefix + id; cls = cc || t._cls.toolbar || tinymce.ui.Toolbar; c = new cls(id, s, t.editor); if (t.get(id)) return null; return t.add(c); }, createToolbarGroup : function(id, s, cc) { var c, t = this, cls; id = t.prefix + id; cls = cc || this._cls.toolbarGroup || tinymce.ui.ToolbarGroup; c = new cls(id, s, t.editor); if (t.get(id)) return null; return t.add(c); }, createSeparator : function(cc) { var cls = cc || this._cls.separator || tinymce.ui.Separator; return new cls(); }, setControlType : function(n, c) { return this._cls[n.toLowerCase()] = c; }, destroy : function() { each(this.controls, function(c) { c.destroy(); }); this.controls = null; } }); })(tinymce); (function(tinymce) { var Dispatcher = tinymce.util.Dispatcher, each = tinymce.each, isIE = tinymce.isIE, isOpera = tinymce.isOpera; tinymce.create('tinymce.WindowManager', { WindowManager : function(ed) { var t = this; t.editor = ed; t.onOpen = new Dispatcher(t); t.onClose = new Dispatcher(t); t.params = {}; t.features = {}; }, open : function(s, p) { var t = this, f = '', x, y, mo = t.editor.settings.dialog_type == 'modal', w, sw, sh, vp = tinymce.DOM.getViewPort(), u; // Default some options s = s || {}; p = p || {}; sw = isOpera ? vp.w : screen.width; // Opera uses windows inside the Opera window sh = isOpera ? vp.h : screen.height; s.name = s.name || 'mc_' + new Date().getTime(); s.width = parseInt(s.width || 320); s.height = parseInt(s.height || 240); s.resizable = true; s.left = s.left || parseInt(sw / 2.0) - (s.width / 2.0); s.top = s.top || parseInt(sh / 2.0) - (s.height / 2.0); p.inline = false; p.mce_width = s.width; p.mce_height = s.height; p.mce_auto_focus = s.auto_focus; if (mo) { if (isIE) { s.center = true; s.help = false; s.dialogWidth = s.width + 'px'; s.dialogHeight = s.height + 'px'; s.scroll = s.scrollbars || false; } } // Build features string each(s, function(v, k) { if (tinymce.is(v, 'boolean')) v = v ? 'yes' : 'no'; if (!/^(name|url)$/.test(k)) { if (isIE && mo) f += (f ? ';' : '') + k + ':' + v; else f += (f ? ',' : '') + k + '=' + v; } }); t.features = s; t.params = p; t.onOpen.dispatch(t, s, p); u = s.url || s.file; u = tinymce._addVer(u); try { if (isIE && mo) { w = 1; window.showModalDialog(u, window, f); } else w = window.open(u, s.name, f); } catch (ex) { // Ignore } if (!w) alert(t.editor.getLang('popup_blocked')); }, close : function(w) { w.close(); this.onClose.dispatch(this); }, createInstance : function(cl, a, b, c, d, e) { var f = tinymce.resolve(cl); return new f(a, b, c, d, e); }, confirm : function(t, cb, s, w) { w = w || window; cb.call(s || this, w.confirm(this._decode(this.editor.getLang(t, t)))); }, alert : function(tx, cb, s, w) { var t = this; w = w || window; w.alert(t._decode(t.editor.getLang(tx, tx))); if (cb) cb.call(s || t); }, resizeBy : function(dw, dh, win) { win.resizeBy(dw, dh); }, // Internal functions _decode : function(s) { return tinymce.DOM.decode(s).replace(/\\n/g, '\n'); } }); }(tinymce)); (function(tinymce) { tinymce.Formatter = function(ed) { var formats = {}, each = tinymce.each, dom = ed.dom, selection = ed.selection, TreeWalker = tinymce.dom.TreeWalker, rangeUtils = new tinymce.dom.RangeUtils(dom), isValid = ed.schema.isValidChild, isBlock = dom.isBlock, forcedRootBlock = ed.settings.forced_root_block, nodeIndex = dom.nodeIndex, INVISIBLE_CHAR = tinymce.isGecko ? '\u200B' : '\uFEFF', MCE_ATTR_RE = /^(src|href|style)$/, FALSE = false, TRUE = true, undef, getContentEditable = dom.getContentEditable; function isArray(obj) { return obj instanceof Array; }; function getParents(node, selector) { return dom.getParents(node, selector, dom.getRoot()); }; function isCaretNode(node) { return node.nodeType === 1 && node.id === '_mce_caret'; }; function defaultFormats() { register({ alignleft : [ {selector : 'figure,p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles : {textAlign : 'left'}, defaultBlock: 'div'}, {selector : 'img,table', collapsed : false, styles : {'float' : 'left'}} ], aligncenter : [ {selector : 'figure,p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles : {textAlign : 'center'}, defaultBlock: 'div'}, {selector : 'img', collapsed : false, styles : {display : 'block', marginLeft : 'auto', marginRight : 'auto'}}, {selector : 'table', collapsed : false, styles : {marginLeft : 'auto', marginRight : 'auto'}} ], alignright : [ {selector : 'figure,p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles : {textAlign : 'right'}, defaultBlock: 'div'}, {selector : 'img,table', collapsed : false, styles : {'float' : 'right'}} ], alignfull : [ {selector : 'figure,p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles : {textAlign : 'justify'}, defaultBlock: 'div'} ], bold : [ {inline : 'strong', remove : 'all'}, {inline : 'span', styles : {fontWeight : 'bold'}}, {inline : 'b', remove : 'all'} ], italic : [ {inline : 'em', remove : 'all'}, {inline : 'span', styles : {fontStyle : 'italic'}}, {inline : 'i', remove : 'all'} ], underline : [ {inline : 'span', styles : {textDecoration : 'underline'}, exact : true}, {inline : 'u', remove : 'all'} ], strikethrough : [ {inline : 'span', styles : {textDecoration : 'line-through'}, exact : true}, {inline : 'strike', remove : 'all'} ], forecolor : {inline : 'span', styles : {color : '%value'}, wrap_links : false}, hilitecolor : {inline : 'span', styles : {backgroundColor : '%value'}, wrap_links : false}, fontname : {inline : 'span', styles : {fontFamily : '%value'}}, fontsize : {inline : 'span', styles : {fontSize : '%value'}}, fontsize_class : {inline : 'span', attributes : {'class' : '%value'}}, blockquote : {block : 'blockquote', wrapper : 1, remove : 'all'}, subscript : {inline : 'sub'}, superscript : {inline : 'sup'}, link : {inline : 'a', selector : 'a', remove : 'all', split : true, deep : true, onmatch : function(node) { return true; }, onformat : function(elm, fmt, vars) { each(vars, function(value, key) { dom.setAttrib(elm, key, value); }); } }, removeformat : [ {selector : 'b,strong,em,i,font,u,strike', remove : 'all', split : true, expand : false, block_expand : true, deep : true}, {selector : 'span', attributes : ['style', 'class'], remove : 'empty', split : true, expand : false, deep : true}, {selector : '*', attributes : ['style', 'class'], split : false, expand : false, deep : true} ] }); // Register default block formats each('p h1 h2 h3 h4 h5 h6 div address pre div code dt dd samp'.split(/\s/), function(name) { register(name, {block : name, remove : 'all'}); }); // Register user defined formats register(ed.settings.formats); }; function addKeyboardShortcuts() { // Add some inline shortcuts ed.addShortcut('ctrl+b', 'bold_desc', 'Bold'); ed.addShortcut('ctrl+i', 'italic_desc', 'Italic'); ed.addShortcut('ctrl+u', 'underline_desc', 'Underline'); // BlockFormat shortcuts keys for (var i = 1; i <= 6; i++) { ed.addShortcut('ctrl+' + i, '', ['FormatBlock', false, 'h' + i]); } ed.addShortcut('ctrl+7', '', ['FormatBlock', false, 'p']); ed.addShortcut('ctrl+8', '', ['FormatBlock', false, 'div']); ed.addShortcut('ctrl+9', '', ['FormatBlock', false, 'address']); }; // Public functions function get(name) { return name ? formats[name] : formats; }; function register(name, format) { if (name) { if (typeof(name) !== 'string') { each(name, function(format, name) { register(name, format); }); } else { // Force format into array and add it to internal collection format = format.length ? format : [format]; each(format, function(format) { // Set deep to false by default on selector formats this to avoid removing // alignment on images inside paragraphs when alignment is changed on paragraphs if (format.deep === undef) format.deep = !format.selector; // Default to true if (format.split === undef) format.split = !format.selector || format.inline; // Default to true if (format.remove === undef && format.selector && !format.inline) format.remove = 'none'; // Mark format as a mixed format inline + block level if (format.selector && format.inline) { format.mixed = true; format.block_expand = true; } // Split classes if needed if (typeof(format.classes) === 'string') format.classes = format.classes.split(/\s+/); }); formats[name] = format; } } }; var getTextDecoration = function(node) { var decoration; ed.dom.getParent(node, function(n) { decoration = ed.dom.getStyle(n, 'text-decoration'); return decoration && decoration !== 'none'; }); return decoration; }; var processUnderlineAndColor = function(node) { var textDecoration; if (node.nodeType === 1 && node.parentNode && node.parentNode.nodeType === 1) { textDecoration = getTextDecoration(node.parentNode); if (ed.dom.getStyle(node, 'color') && textDecoration) { ed.dom.setStyle(node, 'text-decoration', textDecoration); } else if (ed.dom.getStyle(node, 'textdecoration') === textDecoration) { ed.dom.setStyle(node, 'text-decoration', null); } } }; function apply(name, vars, node) { var formatList = get(name), format = formatList[0], bookmark, rng, i, isCollapsed = selection.isCollapsed(); function setElementFormat(elm, fmt) { fmt = fmt || format; if (elm) { if (fmt.onformat) { fmt.onformat(elm, fmt, vars, node); } each(fmt.styles, function(value, name) { dom.setStyle(elm, name, replaceVars(value, vars)); }); each(fmt.attributes, function(value, name) { dom.setAttrib(elm, name, replaceVars(value, vars)); }); each(fmt.classes, function(value) { value = replaceVars(value, vars); if (!dom.hasClass(elm, value)) dom.addClass(elm, value); }); } }; function adjustSelectionToVisibleSelection() { function findSelectionEnd(start, end) { var walker = new TreeWalker(end); for (node = walker.current(); node; node = walker.prev()) { if (node.childNodes.length > 1 || node == start || node.tagName == 'BR') { return node; } } }; // Adjust selection so that a end container with a end offset of zero is not included in the selection // as this isn't visible to the user. var rng = ed.selection.getRng(); var start = rng.startContainer; var end = rng.endContainer; if (start != end && rng.endOffset === 0) { var newEnd = findSelectionEnd(start, end); var endOffset = newEnd.nodeType == 3 ? newEnd.length : newEnd.childNodes.length; rng.setEnd(newEnd, endOffset); } return rng; } function applyStyleToList(node, bookmark, wrapElm, newWrappers, process){ var nodes = [], listIndex = -1, list, startIndex = -1, endIndex = -1, currentWrapElm; // find the index of the first child list. each(node.childNodes, function(n, index) { if (n.nodeName === "UL" || n.nodeName === "OL") { listIndex = index; list = n; return false; } }); // get the index of the bookmarks each(node.childNodes, function(n, index) { if (n.nodeName === "SPAN" && dom.getAttrib(n, "data-mce-type") == "bookmark") { if (n.id == bookmark.id + "_start") { startIndex = index; } else if (n.id == bookmark.id + "_end") { endIndex = index; } } }); // if the selection spans across an embedded list, or there isn't an embedded list - handle processing normally if (listIndex <= 0 || (startIndex < listIndex && endIndex > listIndex)) { each(tinymce.grep(node.childNodes), process); return 0; } else { currentWrapElm = dom.clone(wrapElm, FALSE); // create a list of the nodes on the same side of the list as the selection each(tinymce.grep(node.childNodes), function(n, index) { if ((startIndex < listIndex && index < listIndex) || (startIndex > listIndex && index > listIndex)) { nodes.push(n); n.parentNode.removeChild(n); } }); // insert the wrapping element either before or after the list. if (startIndex < listIndex) { node.insertBefore(currentWrapElm, list); } else if (startIndex > listIndex) { node.insertBefore(currentWrapElm, list.nextSibling); } // add the new nodes to the list. newWrappers.push(currentWrapElm); each(nodes, function(node) { currentWrapElm.appendChild(node); }); return currentWrapElm; } }; function applyRngStyle(rng, bookmark, node_specific) { var newWrappers = [], wrapName, wrapElm, contentEditable = true; // Setup wrapper element wrapName = format.inline || format.block; wrapElm = dom.create(wrapName); setElementFormat(wrapElm); rangeUtils.walk(rng, function(nodes) { var currentWrapElm; function process(node) { var nodeName, parentName, found, hasContentEditableState, lastContentEditable; lastContentEditable = contentEditable; nodeName = node.nodeName.toLowerCase(); parentName = node.parentNode.nodeName.toLowerCase(); // Node has a contentEditable value if (node.nodeType === 1 && getContentEditable(node)) { lastContentEditable = contentEditable; contentEditable = getContentEditable(node) === "true"; hasContentEditableState = true; // We don't want to wrap the container only it's children } // Stop wrapping on br elements if (isEq(nodeName, 'br')) { currentWrapElm = 0; // Remove any br elements when we wrap things if (format.block) dom.remove(node); return; } // If node is wrapper type if (format.wrapper && matchNode(node, name, vars)) { currentWrapElm = 0; return; } // Can we rename the block if (contentEditable && !hasContentEditableState && format.block && !format.wrapper && isTextBlock(nodeName)) { node = dom.rename(node, wrapName); setElementFormat(node); newWrappers.push(node); currentWrapElm = 0; return; } // Handle selector patterns if (format.selector) { // Look for matching formats each(formatList, function(format) { // Check collapsed state if it exists if ('collapsed' in format && format.collapsed !== isCollapsed) { return; } if (dom.is(node, format.selector) && !isCaretNode(node)) { setElementFormat(node, format); found = true; } }); // Continue processing if a selector match wasn't found and a inline element is defined if (!format.inline || found) { currentWrapElm = 0; return; } } // Is it valid to wrap this item if (contentEditable && !hasContentEditableState && isValid(wrapName, nodeName) && isValid(parentName, wrapName) && !(!node_specific && node.nodeType === 3 && node.nodeValue.length === 1 && node.nodeValue.charCodeAt(0) === 65279) && !isCaretNode(node)) { // Start wrapping if (!currentWrapElm) { // Wrap the node currentWrapElm = dom.clone(wrapElm, FALSE); node.parentNode.insertBefore(currentWrapElm, node); newWrappers.push(currentWrapElm); } currentWrapElm.appendChild(node); } else if (nodeName == 'li' && bookmark) { // Start wrapping - if we are in a list node and have a bookmark, then we will always begin by wrapping in a new element. currentWrapElm = applyStyleToList(node, bookmark, wrapElm, newWrappers, process); } else { // Start a new wrapper for possible children currentWrapElm = 0; each(tinymce.grep(node.childNodes), process); if (hasContentEditableState) { contentEditable = lastContentEditable; // Restore last contentEditable state from stack } // End the last wrapper currentWrapElm = 0; } }; // Process siblings from range each(nodes, process); }); // Wrap links inside as well, for example color inside a link when the wrapper is around the link if (format.wrap_links === false) { each(newWrappers, function(node) { function process(node) { var i, currentWrapElm, children; if (node.nodeName === 'A') { currentWrapElm = dom.clone(wrapElm, FALSE); newWrappers.push(currentWrapElm); children = tinymce.grep(node.childNodes); for (i = 0; i < children.length; i++) currentWrapElm.appendChild(children[i]); node.appendChild(currentWrapElm); } each(tinymce.grep(node.childNodes), process); }; process(node); }); } // Cleanup each(newWrappers, function(node) { var childCount; function getChildCount(node) { var count = 0; each(node.childNodes, function(node) { if (!isWhiteSpaceNode(node) && !isBookmarkNode(node)) count++; }); return count; }; function mergeStyles(node) { var child, clone; each(node.childNodes, function(node) { if (node.nodeType == 1 && !isBookmarkNode(node) && !isCaretNode(node)) { child = node; return FALSE; // break loop } }); // If child was found and of the same type as the current node if (child && matchName(child, format)) { clone = dom.clone(child, FALSE); setElementFormat(clone); dom.replace(clone, node, TRUE); dom.remove(child, 1); } return clone || node; }; childCount = getChildCount(node); // Remove empty nodes but only if there is multiple wrappers and they are not block // elements so never remove single <h1></h1> since that would remove the currrent empty block element where the caret is at if ((newWrappers.length > 1 || !isBlock(node)) && childCount === 0) { dom.remove(node, 1); return; } if (format.inline || format.wrapper) { // Merges the current node with it's children of similar type to reduce the number of elements if (!format.exact && childCount === 1) node = mergeStyles(node); // Remove/merge children each(formatList, function(format) { // Merge all children of similar type will move styles from child to parent // this: <span style="color:red"><b><span style="color:red; font-size:10px">text</span></b></span> // will become: <span style="color:red"><b><span style="font-size:10px">text</span></b></span> each(dom.select(format.inline, node), function(child) { var parent; // When wrap_links is set to false we don't want // to remove the format on children within links if (format.wrap_links === false) { parent = child.parentNode; do { if (parent.nodeName === 'A') return; } while (parent = parent.parentNode); } removeFormat(format, vars, child, format.exact ? child : null); }); }); // Remove child if direct parent is of same type if (matchNode(node.parentNode, name, vars)) { dom.remove(node, 1); node = 0; return TRUE; } // Look for parent with similar style format if (format.merge_with_parents) { dom.getParent(node.parentNode, function(parent) { if (matchNode(parent, name, vars)) { dom.remove(node, 1); node = 0; return TRUE; } }); } // Merge next and previous siblings if they are similar <b>text</b><b>text</b> becomes <b>texttext</b> if (node && format.merge_siblings !== false) { node = mergeSiblings(getNonWhiteSpaceSibling(node), node); node = mergeSiblings(node, getNonWhiteSpaceSibling(node, TRUE)); } } }); }; if (format) { if (node) { if (node.nodeType) { rng = dom.createRng(); rng.setStartBefore(node); rng.setEndAfter(node); applyRngStyle(expandRng(rng, formatList), null, true); } else { applyRngStyle(node, null, true); } } else { if (!isCollapsed || !format.inline || dom.select('td.mceSelected,th.mceSelected').length) { // Obtain selection node before selection is unselected by applyRngStyle() var curSelNode = ed.selection.getNode(); // If the formats have a default block and we can't find a parent block then start wrapping it with a DIV this is for forced_root_blocks: false // It's kind of a hack but people should be using the default block type P since all desktop editors work that way if (!forcedRootBlock && formatList[0].defaultBlock && !dom.getParent(curSelNode, dom.isBlock)) { apply(formatList[0].defaultBlock); } // Apply formatting to selection ed.selection.setRng(adjustSelectionToVisibleSelection()); bookmark = selection.getBookmark(); applyRngStyle(expandRng(selection.getRng(TRUE), formatList), bookmark); // Colored nodes should be underlined so that the color of the underline matches the text color. if (format.styles && (format.styles.color || format.styles.textDecoration)) { tinymce.walk(curSelNode, processUnderlineAndColor, 'childNodes'); processUnderlineAndColor(curSelNode); } selection.moveToBookmark(bookmark); moveStart(selection.getRng(TRUE)); ed.nodeChanged(); } else performCaretAction('apply', name, vars); } } }; function remove(name, vars, node) { var formatList = get(name), format = formatList[0], bookmark, i, rng, contentEditable = true; // Merges the styles for each node function process(node) { var children, i, l, localContentEditable, lastContentEditable, hasContentEditableState; // Node has a contentEditable value if (node.nodeType === 1 && getContentEditable(node)) { lastContentEditable = contentEditable; contentEditable = getContentEditable(node) === "true"; hasContentEditableState = true; // We don't want to wrap the container only it's children } // Grab the children first since the nodelist might be changed children = tinymce.grep(node.childNodes); // Process current node if (contentEditable && !hasContentEditableState) { for (i = 0, l = formatList.length; i < l; i++) { if (removeFormat(formatList[i], vars, node, node)) break; } } // Process the children if (format.deep) { if (children.length) { for (i = 0, l = children.length; i < l; i++) process(children[i]); if (hasContentEditableState) { contentEditable = lastContentEditable; // Restore last contentEditable state from stack } } } }; function findFormatRoot(container) { var formatRoot; // Find format root each(getParents(container.parentNode).reverse(), function(parent) { var format; // Find format root element if (!formatRoot && parent.id != '_start' && parent.id != '_end') { // Is the node matching the format we are looking for format = matchNode(parent, name, vars); if (format && format.split !== false) formatRoot = parent; } }); return formatRoot; }; function wrapAndSplit(format_root, container, target, split) { var parent, clone, lastClone, firstClone, i, formatRootParent; // Format root found then clone formats and split it if (format_root) { formatRootParent = format_root.parentNode; for (parent = container.parentNode; parent && parent != formatRootParent; parent = parent.parentNode) { clone = dom.clone(parent, FALSE); for (i = 0; i < formatList.length; i++) { if (removeFormat(formatList[i], vars, clone, clone)) { clone = 0; break; } } // Build wrapper node if (clone) { if (lastClone) clone.appendChild(lastClone); if (!firstClone) firstClone = clone; lastClone = clone; } } // Never split block elements if the format is mixed if (split && (!format.mixed || !isBlock(format_root))) container = dom.split(format_root, container); // Wrap container in cloned formats if (lastClone) { target.parentNode.insertBefore(lastClone, target); firstClone.appendChild(target); } } return container; }; function splitToFormatRoot(container) { return wrapAndSplit(findFormatRoot(container), container, container, true); }; function unwrap(start) { var node = dom.get(start ? '_start' : '_end'), out = node[start ? 'firstChild' : 'lastChild']; // If the end is placed within the start the result will be removed // So this checks if the out node is a bookmark node if it is it // checks for another more suitable node if (isBookmarkNode(out)) out = out[start ? 'firstChild' : 'lastChild']; dom.remove(node, true); return out; }; function removeRngStyle(rng) { var startContainer, endContainer, node; rng = expandRng(rng, formatList, TRUE); if (format.split) { startContainer = getContainer(rng, TRUE); endContainer = getContainer(rng); if (startContainer != endContainer) { // WebKit will render the table incorrectly if we wrap a TD in a SPAN so lets see if the can use the first child instead // This will happen if you tripple click a table cell and use remove formatting node = startContainer.firstChild; if (startContainer.nodeName == "TD" && node) { startContainer = node; } // Wrap start/end nodes in span element since these might be cloned/moved startContainer = wrap(startContainer, 'span', {id : '_start', 'data-mce-type' : 'bookmark'}); endContainer = wrap(endContainer, 'span', {id : '_end', 'data-mce-type' : 'bookmark'}); // Split start/end splitToFormatRoot(startContainer); splitToFormatRoot(endContainer); // Unwrap start/end to get real elements again startContainer = unwrap(TRUE); endContainer = unwrap(); } else startContainer = endContainer = splitToFormatRoot(startContainer); // Update range positions since they might have changed after the split operations rng.startContainer = startContainer.parentNode; rng.startOffset = nodeIndex(startContainer); rng.endContainer = endContainer.parentNode; rng.endOffset = nodeIndex(endContainer) + 1; } // Remove items between start/end rangeUtils.walk(rng, function(nodes) { each(nodes, function(node) { process(node); // Remove parent span if it only contains text-decoration: underline, yet a parent node is also underlined. if (node.nodeType === 1 && ed.dom.getStyle(node, 'text-decoration') === 'underline' && node.parentNode && getTextDecoration(node.parentNode) === 'underline') { removeFormat({'deep': false, 'exact': true, 'inline': 'span', 'styles': {'textDecoration' : 'underline'}}, null, node); } }); }); }; // Handle node if (node) { if (node.nodeType) { rng = dom.createRng(); rng.setStartBefore(node); rng.setEndAfter(node); removeRngStyle(rng); } else { removeRngStyle(node); } return; } if (!selection.isCollapsed() || !format.inline || dom.select('td.mceSelected,th.mceSelected').length) { bookmark = selection.getBookmark(); removeRngStyle(selection.getRng(TRUE)); selection.moveToBookmark(bookmark); // Check if start element still has formatting then we are at: "<b>text|</b>text" and need to move the start into the next text node if (format.inline && match(name, vars, selection.getStart())) { moveStart(selection.getRng(true)); } ed.nodeChanged(); } else performCaretAction('remove', name, vars); }; function toggle(name, vars, node) { var fmt = get(name); if (match(name, vars, node) && (!('toggle' in fmt[0]) || fmt[0].toggle)) remove(name, vars, node); else apply(name, vars, node); }; function matchNode(node, name, vars, similar) { var formatList = get(name), format, i, classes; function matchItems(node, format, item_name) { var key, value, items = format[item_name], i; // Custom match if (format.onmatch) { return format.onmatch(node, format, item_name); } // Check all items if (items) { // Non indexed object if (items.length === undef) { for (key in items) { if (items.hasOwnProperty(key)) { if (item_name === 'attributes') value = dom.getAttrib(node, key); else value = getStyle(node, key); if (similar && !value && !format.exact) return; if ((!similar || format.exact) && !isEq(value, replaceVars(items[key], vars))) return; } } } else { // Only one match needed for indexed arrays for (i = 0; i < items.length; i++) { if (item_name === 'attributes' ? dom.getAttrib(node, items[i]) : getStyle(node, items[i])) return format; } } } return format; }; if (formatList && node) { // Check each format in list for (i = 0; i < formatList.length; i++) { format = formatList[i]; // Name name, attributes, styles and classes if (matchName(node, format) && matchItems(node, format, 'attributes') && matchItems(node, format, 'styles')) { // Match classes if (classes = format.classes) { for (i = 0; i < classes.length; i++) { if (!dom.hasClass(node, classes[i])) return; } } return format; } } } }; function match(name, vars, node) { var startNode; function matchParents(node) { // Find first node with similar format settings node = dom.getParent(node, function(node) { return !!matchNode(node, name, vars, true); }); // Do an exact check on the similar format element return matchNode(node, name, vars); }; // Check specified node if (node) return matchParents(node); // Check selected node node = selection.getNode(); if (matchParents(node)) return TRUE; // Check start node if it's different startNode = selection.getStart(); if (startNode != node) { if (matchParents(startNode)) return TRUE; } return FALSE; }; function matchAll(names, vars) { var startElement, matchedFormatNames = [], checkedMap = {}, i, ni, name; // Check start of selection for formats startElement = selection.getStart(); dom.getParent(startElement, function(node) { var i, name; for (i = 0; i < names.length; i++) { name = names[i]; if (!checkedMap[name] && matchNode(node, name, vars)) { checkedMap[name] = true; matchedFormatNames.push(name); } } }); return matchedFormatNames; }; function canApply(name) { var formatList = get(name), startNode, parents, i, x, selector; if (formatList) { startNode = selection.getStart(); parents = getParents(startNode); for (x = formatList.length - 1; x >= 0; x--) { selector = formatList[x].selector; // Format is not selector based, then always return TRUE if (!selector) return TRUE; for (i = parents.length - 1; i >= 0; i--) { if (dom.is(parents[i], selector)) return TRUE; } } } return FALSE; }; // Expose to public tinymce.extend(this, { get : get, register : register, apply : apply, remove : remove, toggle : toggle, match : match, matchAll : matchAll, matchNode : matchNode, canApply : canApply }); // Initialize defaultFormats(); addKeyboardShortcuts(); // Private functions function matchName(node, format) { // Check for inline match if (isEq(node, format.inline)) return TRUE; // Check for block match if (isEq(node, format.block)) return TRUE; // Check for selector match if (format.selector) return dom.is(node, format.selector); }; function isEq(str1, str2) { str1 = str1 || ''; str2 = str2 || ''; str1 = '' + (str1.nodeName || str1); str2 = '' + (str2.nodeName || str2); return str1.toLowerCase() == str2.toLowerCase(); }; function getStyle(node, name) { var styleVal = dom.getStyle(node, name); // Force the format to hex if (name == 'color' || name == 'backgroundColor') styleVal = dom.toHex(styleVal); // Opera will return bold as 700 if (name == 'fontWeight' && styleVal == 700) styleVal = 'bold'; return '' + styleVal; }; function replaceVars(value, vars) { if (typeof(value) != "string") value = value(vars); else if (vars) { value = value.replace(/%(\w+)/g, function(str, name) { return vars[name] || str; }); } return value; }; function isWhiteSpaceNode(node) { return node && node.nodeType === 3 && /^([\t \r\n]+|)$/.test(node.nodeValue); }; function wrap(node, name, attrs) { var wrapper = dom.create(name, attrs); node.parentNode.insertBefore(wrapper, node); wrapper.appendChild(node); return wrapper; }; function expandRng(rng, format, remove) { var sibling, lastIdx, leaf, endPoint, startContainer = rng.startContainer, startOffset = rng.startOffset, endContainer = rng.endContainer, endOffset = rng.endOffset; // This function walks up the tree if there is no siblings before/after the node function findParentContainer(start) { var container, parent, child, sibling, siblingName, root; container = parent = start ? startContainer : endContainer; siblingName = start ? 'previousSibling' : 'nextSibling'; root = dom.getRoot(); // If it's a text node and the offset is inside the text if (container.nodeType == 3 && !isWhiteSpaceNode(container)) { if (start ? startOffset > 0 : endOffset < container.nodeValue.length) { return container; } } for (;;) { // Stop expanding on block elements if (!format[0].block_expand && isBlock(parent)) return parent; // Walk left/right for (sibling = parent[siblingName]; sibling; sibling = sibling[siblingName]) { if (!isBookmarkNode(sibling) && !isWhiteSpaceNode(sibling)) { return parent; } } // Check if we can move up are we at root level or body level if (parent.parentNode == root) { container = parent; break; } parent = parent.parentNode; } return container; }; // This function walks down the tree to find the leaf at the selection. // The offset is also returned as if node initially a leaf, the offset may be in the middle of the text node. function findLeaf(node, offset) { if (offset === undef) offset = node.nodeType === 3 ? node.length : node.childNodes.length; while (node && node.hasChildNodes()) { node = node.childNodes[offset]; if (node) offset = node.nodeType === 3 ? node.length : node.childNodes.length; } return { node: node, offset: offset }; } // If index based start position then resolve it if (startContainer.nodeType == 1 && startContainer.hasChildNodes()) { lastIdx = startContainer.childNodes.length - 1; startContainer = startContainer.childNodes[startOffset > lastIdx ? lastIdx : startOffset]; if (startContainer.nodeType == 3) startOffset = 0; } // If index based end position then resolve it if (endContainer.nodeType == 1 && endContainer.hasChildNodes()) { lastIdx = endContainer.childNodes.length - 1; endContainer = endContainer.childNodes[endOffset > lastIdx ? lastIdx : endOffset - 1]; if (endContainer.nodeType == 3) endOffset = endContainer.nodeValue.length; } // Expands the node to the closes contentEditable false element if it exists function findParentContentEditable(node) { var parent = node; while (parent) { if (parent.nodeType === 1 && getContentEditable(parent)) { return getContentEditable(parent) === "false" ? parent : node; } parent = parent.parentNode; } return node; }; function findWordEndPoint(container, offset, start) { var walker, node, pos, lastTextNode; function findSpace(node, offset) { var pos, pos2, str = node.nodeValue; if (typeof(offset) == "undefined") { offset = start ? str.length : 0; } if (start) { pos = str.lastIndexOf(' ', offset); pos2 = str.lastIndexOf('\u00a0', offset); pos = pos > pos2 ? pos : pos2; // Include the space on remove to avoid tag soup if (pos !== -1 && !remove) { pos++; } } else { pos = str.indexOf(' ', offset); pos2 = str.indexOf('\u00a0', offset); pos = pos !== -1 && (pos2 === -1 || pos < pos2) ? pos : pos2; } return pos; }; if (container.nodeType === 3) { pos = findSpace(container, offset); if (pos !== -1) { return {container : container, offset : pos}; } lastTextNode = container; } // Walk the nodes inside the block walker = new TreeWalker(container, dom.getParent(container, isBlock) || ed.getBody()); while (node = walker[start ? 'prev' : 'next']()) { if (node.nodeType === 3) { lastTextNode = node; pos = findSpace(node); if (pos !== -1) { return {container : node, offset : pos}; } } else if (isBlock(node)) { break; } } if (lastTextNode) { if (start) { offset = 0; } else { offset = lastTextNode.length; } return {container: lastTextNode, offset: offset}; } }; function findSelectorEndPoint(container, sibling_name) { var parents, i, y, curFormat; if (container.nodeType == 3 && container.nodeValue.length === 0 && container[sibling_name]) container = container[sibling_name]; parents = getParents(container); for (i = 0; i < parents.length; i++) { for (y = 0; y < format.length; y++) { curFormat = format[y]; // If collapsed state is set then skip formats that doesn't match that if ("collapsed" in curFormat && curFormat.collapsed !== rng.collapsed) continue; if (dom.is(parents[i], curFormat.selector)) return parents[i]; } } return container; }; function findBlockEndPoint(container, sibling_name, sibling_name2) { var node; // Expand to block of similar type if (!format[0].wrapper) node = dom.getParent(container, format[0].block); // Expand to first wrappable block element or any block element if (!node) node = dom.getParent(container.nodeType == 3 ? container.parentNode : container, isBlock); // Exclude inner lists from wrapping if (node && format[0].wrapper) node = getParents(node, 'ul,ol').reverse()[0] || node; // Didn't find a block element look for first/last wrappable element if (!node) { node = container; while (node[sibling_name] && !isBlock(node[sibling_name])) { node = node[sibling_name]; // Break on BR but include it will be removed later on // we can't remove it now since we need to check if it can be wrapped if (isEq(node, 'br')) break; } } return node || container; }; // Expand to closest contentEditable element startContainer = findParentContentEditable(startContainer); endContainer = findParentContentEditable(endContainer); // Exclude bookmark nodes if possible if (isBookmarkNode(startContainer.parentNode) || isBookmarkNode(startContainer)) { startContainer = isBookmarkNode(startContainer) ? startContainer : startContainer.parentNode; startContainer = startContainer.nextSibling || startContainer; if (startContainer.nodeType == 3) startOffset = 0; } if (isBookmarkNode(endContainer.parentNode) || isBookmarkNode(endContainer)) { endContainer = isBookmarkNode(endContainer) ? endContainer : endContainer.parentNode; endContainer = endContainer.previousSibling || endContainer; if (endContainer.nodeType == 3) endOffset = endContainer.length; } if (format[0].inline) { if (rng.collapsed) { // Expand left to closest word boundery endPoint = findWordEndPoint(startContainer, startOffset, true); if (endPoint) { startContainer = endPoint.container; startOffset = endPoint.offset; } // Expand right to closest word boundery endPoint = findWordEndPoint(endContainer, endOffset); if (endPoint) { endContainer = endPoint.container; endOffset = endPoint.offset; } } // Avoid applying formatting to a trailing space. leaf = findLeaf(endContainer, endOffset); if (leaf.node) { while (leaf.node && leaf.offset === 0 && leaf.node.previousSibling) leaf = findLeaf(leaf.node.previousSibling); if (leaf.node && leaf.offset > 0 && leaf.node.nodeType === 3 && leaf.node.nodeValue.charAt(leaf.offset - 1) === ' ') { if (leaf.offset > 1) { endContainer = leaf.node; endContainer.splitText(leaf.offset - 1); } } } } // Move start/end point up the tree if the leaves are sharp and if we are in different containers // Example * becomes !: !<p><b><i>*text</i><i>text*</i></b></p>! // This will reduce the number of wrapper elements that needs to be created // Move start point up the tree if (format[0].inline || format[0].block_expand) { if (!format[0].inline || (startContainer.nodeType != 3 || startOffset === 0)) { startContainer = findParentContainer(true); } if (!format[0].inline || (endContainer.nodeType != 3 || endOffset === endContainer.nodeValue.length)) { endContainer = findParentContainer(); } } // Expand start/end container to matching selector if (format[0].selector && format[0].expand !== FALSE && !format[0].inline) { // Find new startContainer/endContainer if there is better one startContainer = findSelectorEndPoint(startContainer, 'previousSibling'); endContainer = findSelectorEndPoint(endContainer, 'nextSibling'); } // Expand start/end container to matching block element or text node if (format[0].block || format[0].selector) { // Find new startContainer/endContainer if there is better one startContainer = findBlockEndPoint(startContainer, 'previousSibling'); endContainer = findBlockEndPoint(endContainer, 'nextSibling'); // Non block element then try to expand up the leaf if (format[0].block) { if (!isBlock(startContainer)) startContainer = findParentContainer(true); if (!isBlock(endContainer)) endContainer = findParentContainer(); } } // Setup index for startContainer if (startContainer.nodeType == 1) { startOffset = nodeIndex(startContainer); startContainer = startContainer.parentNode; } // Setup index for endContainer if (endContainer.nodeType == 1) { endOffset = nodeIndex(endContainer) + 1; endContainer = endContainer.parentNode; } // Return new range like object return { startContainer : startContainer, startOffset : startOffset, endContainer : endContainer, endOffset : endOffset }; } function removeFormat(format, vars, node, compare_node) { var i, attrs, stylesModified; // Check if node matches format if (!matchName(node, format)) return FALSE; // Should we compare with format attribs and styles if (format.remove != 'all') { // Remove styles each(format.styles, function(value, name) { value = replaceVars(value, vars); // Indexed array if (typeof(name) === 'number') { name = value; compare_node = 0; } if (!compare_node || isEq(getStyle(compare_node, name), value)) dom.setStyle(node, name, ''); stylesModified = 1; }); // Remove style attribute if it's empty if (stylesModified && dom.getAttrib(node, 'style') == '') { node.removeAttribute('style'); node.removeAttribute('data-mce-style'); } // Remove attributes each(format.attributes, function(value, name) { var valueOut; value = replaceVars(value, vars); // Indexed array if (typeof(name) === 'number') { name = value; compare_node = 0; } if (!compare_node || isEq(dom.getAttrib(compare_node, name), value)) { // Keep internal classes if (name == 'class') { value = dom.getAttrib(node, name); if (value) { // Build new class value where everything is removed except the internal prefixed classes valueOut = ''; each(value.split(/\s+/), function(cls) { if (/mce\w+/.test(cls)) valueOut += (valueOut ? ' ' : '') + cls; }); // We got some internal classes left if (valueOut) { dom.setAttrib(node, name, valueOut); return; } } } // IE6 has a bug where the attribute doesn't get removed correctly if (name == "class") node.removeAttribute('className'); // Remove mce prefixed attributes if (MCE_ATTR_RE.test(name)) node.removeAttribute('data-mce-' + name); node.removeAttribute(name); } }); // Remove classes each(format.classes, function(value) { value = replaceVars(value, vars); if (!compare_node || dom.hasClass(compare_node, value)) dom.removeClass(node, value); }); // Check for non internal attributes attrs = dom.getAttribs(node); for (i = 0; i < attrs.length; i++) { if (attrs[i].nodeName.indexOf('_') !== 0) return FALSE; } } // Remove the inline child if it's empty for example <b> or <span> if (format.remove != 'none') { removeNode(node, format); return TRUE; } }; function removeNode(node, format) { var parentNode = node.parentNode, rootBlockElm; function find(node, next, inc) { node = getNonWhiteSpaceSibling(node, next, inc); return !node || (node.nodeName == 'BR' || isBlock(node)); }; if (format.block) { if (!forcedRootBlock) { // Append BR elements if needed before we remove the block if (isBlock(node) && !isBlock(parentNode)) { if (!find(node, FALSE) && !find(node.firstChild, TRUE, 1)) node.insertBefore(dom.create('br'), node.firstChild); if (!find(node, TRUE) && !find(node.lastChild, FALSE, 1)) node.appendChild(dom.create('br')); } } else { // Wrap the block in a forcedRootBlock if we are at the root of document if (parentNode == dom.getRoot()) { if (!format.list_block || !isEq(node, format.list_block)) { each(tinymce.grep(node.childNodes), function(node) { if (isValid(forcedRootBlock, node.nodeName.toLowerCase())) { if (!rootBlockElm) rootBlockElm = wrap(node, forcedRootBlock); else rootBlockElm.appendChild(node); } else rootBlockElm = 0; }); } } } } // Never remove nodes that isn't the specified inline element if a selector is specified too if (format.selector && format.inline && !isEq(format.inline, node)) return; dom.remove(node, 1); }; function getNonWhiteSpaceSibling(node, next, inc) { if (node) { next = next ? 'nextSibling' : 'previousSibling'; for (node = inc ? node : node[next]; node; node = node[next]) { if (node.nodeType == 1 || !isWhiteSpaceNode(node)) return node; } } }; function isBookmarkNode(node) { return node && node.nodeType == 1 && node.getAttribute('data-mce-type') == 'bookmark'; }; function mergeSiblings(prev, next) { var marker, sibling, tmpSibling; function compareElements(node1, node2) { // Not the same name if (node1.nodeName != node2.nodeName) return FALSE; function getAttribs(node) { var attribs = {}; each(dom.getAttribs(node), function(attr) { var name = attr.nodeName.toLowerCase(); // Don't compare internal attributes or style if (name.indexOf('_') !== 0 && name !== 'style') attribs[name] = dom.getAttrib(node, name); }); return attribs; }; function compareObjects(obj1, obj2) { var value, name; for (name in obj1) { // Obj1 has item obj2 doesn't have if (obj1.hasOwnProperty(name)) { value = obj2[name]; // Obj2 doesn't have obj1 item if (value === undef) return FALSE; // Obj2 item has a different value if (obj1[name] != value) return FALSE; // Delete similar value delete obj2[name]; } } // Check if obj 2 has something obj 1 doesn't have for (name in obj2) { // Obj2 has item obj1 doesn't have if (obj2.hasOwnProperty(name)) return FALSE; } return TRUE; }; // Attribs are not the same if (!compareObjects(getAttribs(node1), getAttribs(node2))) return FALSE; // Styles are not the same if (!compareObjects(dom.parseStyle(dom.getAttrib(node1, 'style')), dom.parseStyle(dom.getAttrib(node2, 'style')))) return FALSE; return TRUE; }; function findElementSibling(node, sibling_name) { for (sibling = node; sibling; sibling = sibling[sibling_name]) { if (sibling.nodeType == 3 && sibling.nodeValue.length !== 0) return node; if (sibling.nodeType == 1 && !isBookmarkNode(sibling)) return sibling; } return node; }; // Check if next/prev exists and that they are elements if (prev && next) { // If previous sibling is empty then jump over it prev = findElementSibling(prev, 'previousSibling'); next = findElementSibling(next, 'nextSibling'); // Compare next and previous nodes if (compareElements(prev, next)) { // Append nodes between for (sibling = prev.nextSibling; sibling && sibling != next;) { tmpSibling = sibling; sibling = sibling.nextSibling; prev.appendChild(tmpSibling); } // Remove next node dom.remove(next); // Move children into prev node each(tinymce.grep(next.childNodes), function(node) { prev.appendChild(node); }); return prev; } } return next; }; function isTextBlock(name) { return /^(h[1-6]|p|div|pre|address|dl|dt|dd)$/.test(name); }; function getContainer(rng, start) { var container, offset, lastIdx, walker; container = rng[start ? 'startContainer' : 'endContainer']; offset = rng[start ? 'startOffset' : 'endOffset']; if (container.nodeType == 1) { lastIdx = container.childNodes.length - 1; if (!start && offset) offset--; container = container.childNodes[offset > lastIdx ? lastIdx : offset]; } // If start text node is excluded then walk to the next node if (container.nodeType === 3 && start && offset >= container.nodeValue.length) { container = new TreeWalker(container, ed.getBody()).next() || container; } // If end text node is excluded then walk to the previous node if (container.nodeType === 3 && !start && offset === 0) { container = new TreeWalker(container, ed.getBody()).prev() || container; } return container; }; function performCaretAction(type, name, vars) { var caretContainerId = '_mce_caret', debug = ed.settings.caret_debug; // Creates a caret container bogus element function createCaretContainer(fill) { var caretContainer = dom.create('span', {id: caretContainerId, 'data-mce-bogus': true, style: debug ? 'color:red' : ''}); if (fill) { caretContainer.appendChild(ed.getDoc().createTextNode(INVISIBLE_CHAR)); } return caretContainer; }; function isCaretContainerEmpty(node, nodes) { while (node) { if ((node.nodeType === 3 && node.nodeValue !== INVISIBLE_CHAR) || node.childNodes.length > 1) { return false; } // Collect nodes if (nodes && node.nodeType === 1) { nodes.push(node); } node = node.firstChild; } return true; }; // Returns any parent caret container element function getParentCaretContainer(node) { while (node) { if (node.id === caretContainerId) { return node; } node = node.parentNode; } }; // Finds the first text node in the specified node function findFirstTextNode(node) { var walker; if (node) { walker = new TreeWalker(node, node); for (node = walker.current(); node; node = walker.next()) { if (node.nodeType === 3) { return node; } } } }; // Removes the caret container for the specified node or all on the current document function removeCaretContainer(node, move_caret) { var child, rng; if (!node) { node = getParentCaretContainer(selection.getStart()); if (!node) { while (node = dom.get(caretContainerId)) { removeCaretContainer(node, false); } } } else { rng = selection.getRng(true); if (isCaretContainerEmpty(node)) { if (move_caret !== false) { rng.setStartBefore(node); rng.setEndBefore(node); } dom.remove(node); } else { child = findFirstTextNode(node); if (child.nodeValue.charAt(0) === INVISIBLE_CHAR) { child = child.deleteData(0, 1); } dom.remove(node, 1); } selection.setRng(rng); } }; // Applies formatting to the caret postion function applyCaretFormat() { var rng, caretContainer, textNode, offset, bookmark, container, text; rng = selection.getRng(true); offset = rng.startOffset; container = rng.startContainer; text = container.nodeValue; caretContainer = getParentCaretContainer(selection.getStart()); if (caretContainer) { textNode = findFirstTextNode(caretContainer); } // Expand to word is caret is in the middle of a text node and the char before/after is a alpha numeric character if (text && offset > 0 && offset < text.length && /\w/.test(text.charAt(offset)) && /\w/.test(text.charAt(offset - 1))) { // Get bookmark of caret position bookmark = selection.getBookmark(); // Collapse bookmark range (WebKit) rng.collapse(true); // Expand the range to the closest word and split it at those points rng = expandRng(rng, get(name)); rng = rangeUtils.split(rng); // Apply the format to the range apply(name, vars, rng); // Move selection back to caret position selection.moveToBookmark(bookmark); } else { if (!caretContainer || textNode.nodeValue !== INVISIBLE_CHAR) { caretContainer = createCaretContainer(true); textNode = caretContainer.firstChild; rng.insertNode(caretContainer); offset = 1; apply(name, vars, caretContainer); } else { apply(name, vars, caretContainer); } // Move selection to text node selection.setCursorLocation(textNode, offset); } }; function removeCaretFormat() { var rng = selection.getRng(true), container, offset, bookmark, hasContentAfter, node, formatNode, parents = [], i, caretContainer; container = rng.startContainer; offset = rng.startOffset; node = container; if (container.nodeType == 3) { if (offset != container.nodeValue.length || container.nodeValue === INVISIBLE_CHAR) { hasContentAfter = true; } node = node.parentNode; } while (node) { if (matchNode(node, name, vars)) { formatNode = node; break; } if (node.nextSibling) { hasContentAfter = true; } parents.push(node); node = node.parentNode; } // Node doesn't have the specified format if (!formatNode) { return; } // Is there contents after the caret then remove the format on the element if (hasContentAfter) { // Get bookmark of caret position bookmark = selection.getBookmark(); // Collapse bookmark range (WebKit) rng.collapse(true); // Expand the range to the closest word and split it at those points rng = expandRng(rng, get(name), true); rng = rangeUtils.split(rng); // Remove the format from the range remove(name, vars, rng); // Move selection back to caret position selection.moveToBookmark(bookmark); } else { caretContainer = createCaretContainer(); node = caretContainer; for (i = parents.length - 1; i >= 0; i--) { node.appendChild(dom.clone(parents[i], false)); node = node.firstChild; } // Insert invisible character into inner most format element node.appendChild(dom.doc.createTextNode(INVISIBLE_CHAR)); node = node.firstChild; // Insert caret container after the formated node dom.insertAfter(caretContainer, formatNode); // Move selection to text node selection.setCursorLocation(node, 1); } }; // Only bind the caret events once if (!self._hasCaretEvents) { // Mark current caret container elements as bogus when getting the contents so we don't end up with empty elements ed.onBeforeGetContent.addToTop(function() { var nodes = [], i; if (isCaretContainerEmpty(getParentCaretContainer(selection.getStart()), nodes)) { // Mark children i = nodes.length; while (i--) { dom.setAttrib(nodes[i], 'data-mce-bogus', '1'); } } }); // Remove caret container on mouse up and on key up tinymce.each('onMouseUp onKeyUp'.split(' '), function(name) { ed[name].addToTop(function() { removeCaretContainer(); }); }); // Remove caret container on keydown and it's a backspace, enter or left/right arrow keys ed.onKeyDown.addToTop(function(ed, e) { var keyCode = e.keyCode; if (keyCode == 8 || keyCode == 37 || keyCode == 39) { removeCaretContainer(getParentCaretContainer(selection.getStart())); } }); self._hasCaretEvents = true; } // Do apply or remove caret format if (type == "apply") { applyCaretFormat(); } else { removeCaretFormat(); } }; function moveStart(rng) { var container = rng.startContainer, offset = rng.startOffset, isAtEndOfText, walker, node, nodes, tmpNode; // Convert text node into index if possible if (container.nodeType == 3 && offset >= container.nodeValue.length) { // Get the parent container location and walk from there offset = nodeIndex(container); container = container.parentNode; isAtEndOfText = true; } // Move startContainer/startOffset in to a suitable node if (container.nodeType == 1) { nodes = container.childNodes; container = nodes[Math.min(offset, nodes.length - 1)]; walker = new TreeWalker(container, dom.getParent(container, dom.isBlock)); // If offset is at end of the parent node walk to the next one if (offset > nodes.length - 1 || isAtEndOfText) walker.next(); for (node = walker.current(); node; node = walker.next()) { if (node.nodeType == 3 && !isWhiteSpaceNode(node)) { // IE has a "neat" feature where it moves the start node into the closest element // we can avoid this by inserting an element before it and then remove it after we set the selection tmpNode = dom.create('a', null, INVISIBLE_CHAR); node.parentNode.insertBefore(tmpNode, node); // Set selection and remove tmpNode rng.setStart(node, 0); selection.setRng(rng); dom.remove(tmpNode); return; } } } }; }; })(tinymce); tinymce.onAddEditor.add(function(tinymce, ed) { var filters, fontSizes, dom, settings = ed.settings; function replaceWithSpan(node, styles) { tinymce.each(styles, function(value, name) { if (value) dom.setStyle(node, name, value); }); dom.rename(node, 'span'); }; function convert(editor, params) { dom = editor.dom; if (settings.convert_fonts_to_spans) { tinymce.each(dom.select('font,u,strike', params.node), function(node) { filters[node.nodeName.toLowerCase()](ed.dom, node); }); } }; if (settings.inline_styles) { fontSizes = tinymce.explode(settings.font_size_legacy_values); filters = { font : function(dom, node) { replaceWithSpan(node, { backgroundColor : node.style.backgroundColor, color : node.color, fontFamily : node.face, fontSize : fontSizes[parseInt(node.size, 10) - 1] }); }, u : function(dom, node) { replaceWithSpan(node, { textDecoration : 'underline' }); }, strike : function(dom, node) { replaceWithSpan(node, { textDecoration : 'line-through' }); } }; ed.onPreProcess.add(convert); ed.onSetContent.add(convert); ed.onInit.add(function() { ed.selection.onSetContent.add(convert); }); } }); (function(tinymce) { var TreeWalker = tinymce.dom.TreeWalker; tinymce.EnterKey = function(editor) { var dom = editor.dom, selection = editor.selection, settings = editor.settings, undoManager = editor.undoManager; function handleEnterKey(evt) { var rng = selection.getRng(true), tmpRng, editableRoot, container, offset, parentBlock, documentMode, newBlock, fragment, containerBlock, parentBlockName, containerBlockName, newBlockName, isAfterLastNodeInContainer; // Returns true if the block can be split into two blocks or not function canSplitBlock(node) { return node && dom.isBlock(node) && !/^(TD|TH|CAPTION)$/.test(node.nodeName) && !/^(fixed|absolute)/i.test(node.style.position) && dom.getContentEditable(node) !== "true"; }; // Moves the caret to a suitable position within the root for example in the first non pure whitespace text node or before an image function moveToCaretPosition(root) { var walker, node, rng, y, viewPort, lastNode = root, tempElm; rng = dom.createRng(); if (root.hasChildNodes()) { walker = new TreeWalker(root, root); while (node = walker.current()) { if (node.nodeType == 3) { rng.setStart(node, 0); rng.setEnd(node, 0); break; } if (/^(BR|IMG)$/.test(node.nodeName)) { rng.setStartBefore(node); rng.setEndBefore(node); break; } lastNode = node; node = walker.next(); } if (!node) { rng.setStart(lastNode, 0); rng.setEnd(lastNode, 0); } } else { if (root.nodeName == 'BR') { if (root.nextSibling && dom.isBlock(root.nextSibling)) { // Trick on older IE versions to render the caret before the BR between two lists if (!documentMode || documentMode < 9) { tempElm = dom.create('br'); root.parentNode.insertBefore(tempElm, root); } rng.setStartBefore(root); rng.setEndBefore(root); } else { rng.setStartAfter(root); rng.setEndAfter(root); } } else { rng.setStart(root, 0); rng.setEnd(root, 0); } } selection.setRng(rng); // Remove tempElm created for old IE:s dom.remove(tempElm); viewPort = dom.getViewPort(editor.getWin()); // scrollIntoView seems to scroll the parent window in most browsers now including FF 3.0b4 so it's time to stop using it and do it our selfs y = dom.getPos(root).y; if (y < viewPort.y || y + 25 > viewPort.y + viewPort.h) { editor.getWin().scrollTo(0, y < viewPort.y ? y : y - viewPort.h + 25); // Needs to be hardcoded to roughly one line of text if a huge text block is broken into two blocks } }; // Creates a new block element by cloning the current one or creating a new one if the name is specified // This function will also copy any text formatting from the parent block and add it to the new one function createNewBlock(name) { var node = container, block, clonedNode, caretNode; block = name || parentBlockName == "TABLE" ? dom.create(name || newBlockName) : parentBlock.cloneNode(false); caretNode = block; // Clone any parent styles if (settings.keep_styles !== false) { do { if (/^(SPAN|STRONG|B|EM|I|FONT|STRIKE|U)$/.test(node.nodeName)) { clonedNode = node.cloneNode(false); dom.setAttrib(clonedNode, 'id', ''); // Remove ID since it needs to be document unique if (block.hasChildNodes()) { clonedNode.appendChild(block.firstChild); block.appendChild(clonedNode); } else { caretNode = clonedNode; block.appendChild(clonedNode); } } } while (node = node.parentNode); } // BR is needed in empty blocks on non IE browsers if (!tinymce.isIE) { caretNode.innerHTML = '<br>'; } return block; }; // Returns true/false if the caret is at the start/end of the parent block element function isCaretAtStartOrEndOfBlock(start) { var walker, node, name; // Caret is in the middle of a text node like "a|b" if (container.nodeType == 3 && (start ? offset > 0 : offset < container.nodeValue.length)) { return false; } // If after the last element in block node edge case for #5091 if (container.parentNode == parentBlock && isAfterLastNodeInContainer && !start) { return true; } // Caret can be before/after a table if (container.nodeName === "TABLE" || (container.previousSibling && container.previousSibling.nodeName == "TABLE")) { return (isAfterLastNodeInContainer && !start) || (!isAfterLastNodeInContainer && start); } // Walk the DOM and look for text nodes or non empty elements walker = new TreeWalker(container, parentBlock); while (node = (start ? walker.prev() : walker.next())) { if (node.nodeType === 1) { // Ignore bogus elements if (node.getAttribute('data-mce-bogus')) { continue; } // Keep empty elements like <img /> name = node.nodeName.toLowerCase(); if (name === 'IMG') { return false; } } else if (node.nodeType === 3 && !/^[ \t\r\n]*$/.test(node.nodeValue)) { return false; } } return true; }; // Wraps any text nodes or inline elements in the specified forced root block name function wrapSelfAndSiblingsInDefaultBlock(container, offset) { var newBlock, parentBlock, startNode, node, next, blockName = newBlockName || 'P'; // Not in a block element or in a table cell or caption parentBlock = dom.getParent(container, dom.isBlock); if (!parentBlock || !canSplitBlock(parentBlock)) { parentBlock = parentBlock || editableRoot; if (!parentBlock.hasChildNodes()) { newBlock = dom.create(blockName); parentBlock.appendChild(newBlock); rng.setStart(newBlock, 0); rng.setEnd(newBlock, 0); return newBlock; } // Find parent that is the first child of parentBlock node = container; while (node.parentNode != parentBlock) { node = node.parentNode; } // Loop left to find start node start wrapping at while (node && !dom.isBlock(node)) { startNode = node; node = node.previousSibling; } if (startNode) { newBlock = dom.create(blockName); startNode.parentNode.insertBefore(newBlock, startNode); // Start wrapping until we hit a block node = startNode; while (node && !dom.isBlock(node)) { next = node.nextSibling; newBlock.appendChild(node); node = next; } // Restore range to it's past location rng.setStart(container, offset); rng.setEnd(container, offset); } } return container; }; // Inserts a block or br before/after or in the middle of a split list of the LI is empty function handleEmptyListItem() { function isFirstOrLastLi(first) { var node = containerBlock[first ? 'firstChild' : 'lastChild']; // Find first/last element since there might be whitespace there while (node) { if (node.nodeType == 1) { break; } node = node[first ? 'nextSibling' : 'previousSibling']; } return node === parentBlock; }; newBlock = newBlockName ? createNewBlock(newBlockName) : dom.create('BR'); if (isFirstOrLastLi(true) && isFirstOrLastLi()) { // Is first and last list item then replace the OL/UL with a text block dom.replace(newBlock, containerBlock); } else if (isFirstOrLastLi(true)) { // First LI in list then remove LI and add text block before list containerBlock.parentNode.insertBefore(newBlock, containerBlock); } else if (isFirstOrLastLi()) { // Last LI in list then temove LI and add text block after list dom.insertAfter(newBlock, containerBlock); } else { // Middle LI in list the split the list and insert a text block in the middle // Extract after fragment and insert it after the current block tmpRng = rng.cloneRange(); tmpRng.setStartAfter(parentBlock); tmpRng.setEndAfter(containerBlock); fragment = tmpRng.extractContents(); dom.insertAfter(fragment, containerBlock); dom.insertAfter(newBlock, containerBlock); } dom.remove(parentBlock); moveToCaretPosition(newBlock); undoManager.add(); }; // Walks the parent block to the right and look for BR elements function hasRightSideBr() { var walker = new TreeWalker(container, parentBlock), node; while (node = walker.current()) { if (node.nodeName == 'BR') { return true; } node = walker.next(); } } // Inserts a BR element if the forced_root_block option is set to false or empty string function insertBr() { var brElm, extraBr; if (container && container.nodeType == 3 && offset >= container.nodeValue.length) { // Insert extra BR element at the end block elements if (!tinymce.isIE && !hasRightSideBr()) { brElm = dom.create('br') rng.insertNode(brElm); rng.setStartAfter(brElm); rng.setEndAfter(brElm); extraBr = true; } } brElm = dom.create('br'); rng.insertNode(brElm); // Rendering modes below IE8 doesn't display BR elements in PRE unless we have a \n before it if (tinymce.isIE && parentBlockName == 'PRE' && (!documentMode || documentMode < 8)) { brElm.parentNode.insertBefore(dom.doc.createTextNode('\r'), brElm); } if (!extraBr) { rng.setStartAfter(brElm); rng.setEndAfter(brElm); } else { rng.setStartBefore(brElm); rng.setEndBefore(brElm); } selection.setRng(rng); undoManager.add(); }; // Trims any linebreaks at the beginning of node user for example when pressing enter in a PRE element function trimLeadingLineBreaks(node) { do { if (node.nodeType === 3) { node.nodeValue = node.nodeValue.replace(/^[\r\n]+/, ''); } node = node.firstChild; } while (node); }; function getEditableRoot(node) { var root = dom.getRoot(), parent, editableRoot; // Get all parents until we hit a non editable parent or the root parent = node; while (parent !== root && dom.getContentEditable(parent) !== "false") { if (dom.getContentEditable(parent) === "true") { editableRoot = parent; } parent = parent.parentNode; } return parent !== root ? editableRoot : root; }; // Delete any selected contents if (!rng.collapsed) { editor.execCommand('Delete'); return; } // Event is blocked by some other handler for example the lists plugin if (evt.isDefaultPrevented()) { return; } // Setup range items and newBlockName container = rng.startContainer; offset = rng.startOffset; newBlockName = settings.forced_root_block; newBlockName = newBlockName ? newBlockName.toUpperCase() : ''; documentMode = dom.doc.documentMode; // Resolve node index if (container.nodeType == 1 && container.hasChildNodes()) { isAfterLastNodeInContainer = offset > container.childNodes.length - 1; container = container.childNodes[Math.min(offset, container.childNodes.length - 1)] || container; offset = 0; } // Get editable root node normaly the body element but sometimes a div or span editableRoot = getEditableRoot(container); // If there is no editable root then enter is done inside a contentEditable false element if (!editableRoot) { return; } undoManager.beforeChange(); // If editable root isn't block nor the root of the editor if (!dom.isBlock(editableRoot) && editableRoot != dom.getRoot()) { if (!newBlockName || evt.shiftKey) { insertBr(); } return; } // Wrap the current node and it's sibling in a default block if it's needed. // for example this <td>text|<b>text2</b></td> will become this <td><p>text|<b>text2</p></b></td> // This won't happen if root blocks are disabled or the shiftKey is pressed if ((newBlockName && !evt.shiftKey) || (!newBlockName && evt.shiftKey)) { container = wrapSelfAndSiblingsInDefaultBlock(container, offset); } // Find parent block and setup empty block paddings parentBlock = dom.getParent(container, dom.isBlock); containerBlock = parentBlock ? dom.getParent(parentBlock.parentNode, dom.isBlock) : null; // Setup block names parentBlockName = parentBlock ? parentBlock.nodeName.toUpperCase() : ''; // IE < 9 & HTML5 containerBlockName = containerBlock ? containerBlock.nodeName.toUpperCase() : ''; // IE < 9 & HTML5 // Handle enter inside an empty list item if (parentBlockName == 'LI' && dom.isEmpty(parentBlock)) { // Let the list plugin or browser handle nested lists for now if (/^(UL|OL|LI)$/.test(containerBlock.parentNode.nodeName)) { return false; } handleEmptyListItem(); return; } // Don't split PRE tags but insert a BR instead easier when writing code samples etc if (parentBlockName == 'PRE' && settings.br_in_pre !== false) { if (!evt.shiftKey) { insertBr(); return; } } else { // If no root block is configured then insert a BR by default or if the shiftKey is pressed if ((!newBlockName && !evt.shiftKey && parentBlockName != 'LI') || (newBlockName && evt.shiftKey)) { insertBr(); return; } } // Default block name if it's not configured newBlockName = newBlockName || 'P'; // Insert new block before/after the parent block depending on caret location if (isCaretAtStartOrEndOfBlock()) { // If the caret is at the end of a header we produce a P tag after it similar to Word unless we are in a hgroup if (/^(H[1-6]|PRE)$/.test(parentBlockName) && containerBlockName != 'HGROUP') { newBlock = createNewBlock(newBlockName); } else { newBlock = createNewBlock(); } // Split the current container block element if enter is pressed inside an empty inner block element if (settings.end_container_on_empty_block && canSplitBlock(containerBlock) && dom.isEmpty(parentBlock)) { // Split container block for example a BLOCKQUOTE at the current blockParent location for example a P newBlock = dom.split(containerBlock, parentBlock); } else { dom.insertAfter(newBlock, parentBlock); } } else if (isCaretAtStartOrEndOfBlock(true)) { // Insert new block before newBlock = parentBlock.parentNode.insertBefore(createNewBlock(), parentBlock); } else { // Extract after fragment and insert it after the current block tmpRng = rng.cloneRange(); tmpRng.setEndAfter(parentBlock); fragment = tmpRng.extractContents(); trimLeadingLineBreaks(fragment); newBlock = fragment.firstChild; dom.insertAfter(fragment, parentBlock); } dom.setAttrib(newBlock, 'id', ''); // Remove ID since it needs to be document unique moveToCaretPosition(newBlock); undoManager.add(); } editor.onKeyDown.add(function(ed, evt) { if (evt.keyCode == 13) { if (handleEnterKey(evt) !== false) { evt.preventDefault(); } } }); }; })(tinymce);
define(["../../polymer/polymer-legacy.js"], function (_polymerLegacy) { "use strict"; /** @license Copyright (c) 2016 The Polymer Project Authors. All rights reserved. This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by Google as part of the polymer project is also subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */ /** app-grid is a helper class useful for creating responsive, fluid grid layouts using custom properties. Because custom properties can be defined inside a `@media` rule, you can customize the grid layout for different responsive breakpoints. Example: Import `app-grid-style.html` and include `app-grid-style` in the style of an element's definition. Then, add the class `app-grid` to a container such as `ul` or `div`: ```html <template> <style include="app-grid-style"> :host { --app-grid-columns: 3; --app-grid-item-height: 100px; } ul { padding: 0; list-style: none; } .item { background-color: white; } </style> <ul class="app-grid"> <li class="item">1</li> <li class="item">2</li> <li class="item">3</li> </ul> </template> ``` In the example above, the grid will take 3 columns per row. ### Expandible items In many cases, it's useful to expand an item more than 1 column. To achieve this type of layout, you can specify the number of columns the item should expand to by setting the custom property `--app-grid-expandible-item-columns`. To indicate which item should expand, apply the mixin `--app-grid-expandible-item` to a rule with a selector to the item. For example: <pre><code> &lt;template> &lt;style include="app-grid-style"> :host { --app-grid-columns: 3; --app-grid-item-height: 100px; --app-grid-expandible-item-columns: 3; } /* Only the first item should expand *\/ .item:first-child { &#64;apply --app-grid-expandible-item; } &lt;/style> &lt;/template> </code></pre> ### Preserving the aspect ratio When the size of a grid item should preserve the aspect ratio, you can add the `has-aspect-ratio` attribute to the element with the class `.app-grid`. Now, every item element becomes a wrapper around the item content. For example: ```html <template> <style include="app-grid-style"> :host { --app-grid-columns: 3; /* 50% the width of the item is equivalent to 2:1 aspect ratio*\/ --app-grid-item-height: 50%; } .item { background-color: white; } </style> <ul class="app-grid" has-aspect-ratio> <li class="item"> <div>item 1</div> </li> <li class="item"> <div>item 2</div> </li> <li class="item"> <div>item 3</div> </li> </ul> </template> ``` ### Styling Custom property | Description | Default ----------------------------------------------|------------------------------------------------------------|------------------ `--app-grid-columns` | The number of columns per row. | 1 `--app-grid-gutter` | The space between two items. | 0px `--app-grid-item-height` | The height of the items. | auto `--app-grid-expandible-item-columns` | The number of columns an expandible item should expand to. | 1 @group App Elements @pseudoElement app-grid @demo app-grid/demo/index.html */ var $_documentContainer = document.createElement('template'); $_documentContainer.setAttribute('style', 'display: none;'); $_documentContainer.innerHTML = "<dom-module id=\"app-grid-style\">\n <template>\n <style>\n :host {\n /**\n * The width for the expandible item is:\n * ((100% - subPixelAdjustment) / columns * itemColumns - gutter\n *\n * - subPixelAdjustment: 0.1px (Required for IE 11)\n * - gutter: var(--app-grid-gutter)\n * - columns: var(--app-grid-columns)\n * - itemColumn: var(--app-grid-expandible-item-columns)\n */\n --app-grid-expandible-item: {\n -webkit-flex-basis: calc((100% - 0.1px) / var(--app-grid-columns, 1) * var(--app-grid-expandible-item-columns, 1) - var(--app-grid-gutter, 0px)) !important;\n flex-basis: calc((100% - 0.1px) / var(--app-grid-columns, 1) * var(--app-grid-expandible-item-columns, 1) - var(--app-grid-gutter, 0px)) !important;\n max-width: calc((100% - 0.1px) / var(--app-grid-columns, 1) * var(--app-grid-expandible-item-columns, 1) - var(--app-grid-gutter, 0px)) !important;\n };\n }\n\n .app-grid {\n display: -ms-flexbox;\n display: -webkit-flex;\n display: flex;\n\n -ms-flex-direction: row;\n -webkit-flex-direction: row;\n flex-direction: row;\n\n -ms-flex-wrap: wrap;\n -webkit-flex-wrap: wrap;\n flex-wrap: wrap;\n\n padding-top: var(--app-grid-gutter, 0px);\n padding-left: var(--app-grid-gutter, 0px);\n box-sizing: border-box;\n }\n\n .app-grid > * {\n /* Required for IE 10 */\n -ms-flex: 1 1 100%;\n -webkit-flex: 1;\n flex: 1;\n\n /* The width for an item is: (100% - subPixelAdjustment - gutter * columns) / columns */\n -webkit-flex-basis: calc((100% - 0.1px - (var(--app-grid-gutter, 0px) * var(--app-grid-columns, 1))) / var(--app-grid-columns, 1));\n flex-basis: calc((100% - 0.1px - (var(--app-grid-gutter, 0px) * var(--app-grid-columns, 1))) / var(--app-grid-columns, 1));\n\n max-width: calc((100% - 0.1px - (var(--app-grid-gutter, 0px) * var(--app-grid-columns, 1))) / var(--app-grid-columns, 1));\n margin-bottom: var(--app-grid-gutter, 0px);\n margin-right: var(--app-grid-gutter, 0px);\n height: var(--app-grid-item-height);\n box-sizing: border-box;\n }\n\n .app-grid[has-aspect-ratio] > * {\n position: relative;\n }\n\n .app-grid[has-aspect-ratio] > *::before {\n display: block;\n content: \"\";\n padding-top: var(--app-grid-item-height, 100%);\n }\n\n .app-grid[has-aspect-ratio] > * > * {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n }\n </style>\n </template>\n</dom-module>"; document.head.appendChild($_documentContainer.content); });
import React from 'react' import styled from 'styled-components' import { IdentityBadge } from '@aragon/ui' class App extends React.Component { render() { return ( <div css={` display: flex; align-items: center; justify-content: center; flex-direction: column; gap: 30px; height: 100vh; `} > <IdentityBadge customLabel="Olive Oyl" entity="0xc41e4c10b37d3397a99d4a90e7d85508a69a5c4c" connectedAccount /> <IdentityBadge entity="0x2c9341a52cfa3f2c2554ca1803134137b9366b3c" connectedAccount /> <IdentityBadge entity="0x7c708ac7db979fa06705f8880f29f82cfc406993" connectedAccount /> <IdentityBadge entity="0x7c708ac7db979fa06705f8880f29f82cfc406993" compact={true} connectedAccount /> </div> ) } } export default App
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ClientInfo = void 0; const platform = require("platform"); class ClientInfo { constructor(version) { this.sdk = 'js'; this.sdkVer = version; this.os = platform.os.family; this.osVer = platform.os.version; this.pl = platform.name; this.plVer = platform.version; } } exports.ClientInfo = ClientInfo; exports.default = ClientInfo;
const process = require('process'); const fs = require('fs'); const { execSync } = require('child_process'); const { version } = require('./package.json'); const task = process.argv.slice(2).join(' '); // eslint-disable-next-line no-console console.log(`npm-scripts.js [INFO] running task "${task}"`); switch (task) { case 'typescript:build': { build(); break; } case 'typescript:clean': { clean() break; } case 'typescript:rebuild': { clean() build() break; } case 'typescript:watch': { const TscWatchClient = require('tsc-watch/client'); clean(); const watch = new TscWatchClient(); watch.on('success', taskReplaceVersion); watch.start('--pretty'); break; } case 'lint': { execute('MEDIASOUP_NODE_LANGUAGE=typescript eslint -c .eslintrc.js --ext=ts src/'); execute('MEDIASOUP_NODE_LANGUAGE=javascript eslint -c .eslintrc.js --ext=js --ignore-pattern \'!.eslintrc.js\' .eslintrc.js npm-scripts.js test/'); break; } case 'test': { taskReplaceVersion(); execute('jest'); break; } case 'coverage': { taskReplaceVersion(); execute('jest --coverage'); execute('open-cli coverage/lcov-report/index.html'); break; } default: { throw new TypeError(`unknown task "${task}"`); } } function build() { execute("tsc"); taskReplaceVersion(); } function clean() { execute("rm -rf lib"); } function taskReplaceVersion() { const file = 'lib/main.js'; const text = fs.readFileSync(file, { encoding: 'utf8' }); const result = text.replace(/__MEDIASOUP_CLIENT_VERSION__/g, version); fs.writeFileSync(file, result, { encoding: 'utf8' }); } function execute(command) { // eslint-disable-next-line no-console console.log(`npm-scripts.js [INFO] executing command: ${command}`); try { execSync(command, { stdio: [ 'ignore', process.stdout, process.stderr ] }); } catch (error) { process.exit(1); } }
/// Copyright (c) 2012 Ecma International. All rights reserved. /// Ecma International makes this code available under the terms and conditions set /// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the /// "Use Terms"). Any redistribution of this code must retain the above /// copyright and this notice and otherwise comply with the Use Terms. /** * @path ch15/15.4/15.4.4/15.4.4.14/15.4.4.14-7-2.js * @description Array.prototype.indexOf returns correct index when 'fromIndex' is length of array - 1 */ function testcase() { return [1, 2, 3].indexOf(3, 2) === 2; } runTestCase(testcase);
//// [superInObjectLiterals_ES5.ts] var obj = { __proto__: { method() { } }, method() { super.method(); }, get prop() { super.method(); return 10; }, set prop(value) { super.method(); }, p1: function () { super.method(); }, p2: function f() { super.method(); }, p3: () => { super.method(); } }; class A { method() { } } class B extends A { f() { var obj = { __proto__: { method() { } }, method() { super.method(); }, get prop() { super.method(); return 10; }, set prop(value) { super.method(); }, p1: function () { super.method(); }, p2: function f() { super.method(); }, p3: () => { super.method(); } }; } } //// [superInObjectLiterals_ES5.js] var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var obj = { __proto__: { method: function () { } }, method: function () { _super.prototype.method.call(this); }, get prop() { _super.prototype.method.call(this); return 10; }, set prop(value) { _super.prototype.method.call(this); }, p1: function () { _super.method.call(this); }, p2: function f() { _super.method.call(this); }, p3: function () { _super.method.call(this); } }; var A = (function () { function A() { } A.prototype.method = function () { }; return A; }()); var B = (function (_super) { __extends(B, _super); function B() { _super.apply(this, arguments); } B.prototype.f = function () { var _this = this; var obj = { __proto__: { method: function () { } }, method: function () { _super.prototype.method.call(this); }, get prop() { _super.prototype.method.call(this); return 10; }, set prop(value) { _super.prototype.method.call(this); }, p1: function () { _super.method.call(this); }, p2: function f() { _super.method.call(this); }, p3: function () { _super.prototype.method.call(_this); } }; }; return B; }(A));
/* globals describe it expect */ /* eslint-disable flowtype/require-valid-file-annotation */ import * as React from 'react' import ShallowRenderer from 'react-test-renderer/shallow' import { FioAddressRegistered } from '../../components/scenes/FioAddressRegisteredScene' import { getTheme } from '../../components/services/ThemeContext.js' describe('FioAddressRegistered', () => { it('should render with loading props', () => { const renderer = new ShallowRenderer() const props = { state: { contacts: [ { hasThumbnail: true, emailAddresses: ['myemail@yahoo'], postalAddresses: ['123 Home St.'], middleName: 'John', company: 'Edge', jobTitle: 'Boss', familyName: 'Savage', thumbnailPath: 'Fio.png', recordID: '123', givenName: 'John Wick' } ], deviceReferral: { messages: [ { message: 'Refferal', uri: `%BTC`, iconUri: `%BTC`, startDate: '', durationDays: 11 } ], plugins: ['PluginTweaks'] }, exchangeRates: ['USD/FIO'], nextUsername: 'string', pendingDeepLink: { type: 'other', protocol: 'FIO', uri: `%BTC` }, account: { accountReferral: { promotions: ['promotion'], ignoreAccountSwap: true, hiddenAccountMessages: [false] }, accountReferralLoaded: true, referralCache: { accountMessages: [], accountPlugins: [] } }, network: { isConnected: true } }, wallets: [ { id: '0x34653463', type: 'FIO wallet', name: 'MyFio', primaryNativeBalance: '1', nativeBalances: ['FIO'], currencyNames: ['FIO'], currencyCode: 'FIO', isoFiatCurrencyCode: 'iso: USD', fiatCurrencyCode: 'USD', symbolImage: 'fio logo', symbolImageDarkMono: 'Fio image', metaTokens: [ { currencyCode: 'FIO', currencyName: 'Fio', denominations: [ { multiplier: '10000000', name: 'FIO' } ] } ], enabledTokens: ['FIO'], receiveAddress: { publicAddress: '0x434dsfv455' } & { metadata: { bizId: 20, category: 'Fio wallet' }, nativeAmount: '100' }, blockHeight: 35 } ], fioWallets: ['walletId'], fioDisplayDenomination: { multiplier: '100000000', name: 'FIO' }, isConnected: true, route: { params: { fioAddress: '0x34263463', selectedWallet: 'walletId', selectedDomain: 'MyFio@edge' } }, onSelectWallet: (walletId, currencyCode) => undefined, theme: getTheme() } const actual = renderer.render(<FioAddressRegistered {...props} />) expect(actual).toMatchSnapshot() }) })
// Copyright 2016, Google, Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. 'use strict'; var landmarkDetectionSample = require('../landmarkDetection'); var inputFile = 'https://cloud-samples-tests.storage.googleapis.com/vision/water.jpg'; describe('vision:landmarkDetection', function () { it('should detect landmarks', function (done) { landmarkDetectionSample.main(inputFile, function (err, landmarks) { assert.ifError(err); assert(landmarks.length > 0); assert(console.log.calledWith('Found landmark: Taitung, Famous Places "up the water flow" marker for ' + inputFile)); done(); }); }); });
var React = require('react'), rlapi = require('livereactload-api') var Map = rlapi.expose(React.createClass({ componentDidMount: function() { var mapOptions = { center: {lat: 60.2058215, lng: 24.8819948}, zoom: 12, draggable: false, zoomControl: false, scrollwheel: false, disableDoubleClickZoom: true } this.props.onMap(new google.maps.Map(React.findDOMNode(this), mapOptions)) }, render: function() { return <div className="map" style={{position: 'absolute', height: '100%', width: '100%'}} /> } }), 'Map') module.exports = React.createClass({ getInitialState: function() { return {map: null} }, onMapMounted: function(map) { this.setState({map: map}) }, render: function() { var markers = this.state.map ? withMap(this.props.children, this.state.map) : this.props.children return ( <div> <Map onMap={this.onMapMounted} /> <div style={{position: 'absolute'}}>{markers}</div> </div> ) function withMap(children, map) { return React.Children.map(children, function(child) { return React.cloneElement(child, {map: map, key: child.key}) }) } } })
/** * requestAnimationFrame */ window.requestAnimationFrame = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) { window.setTimeout(callback, 1000 / 60); }; })(); /** * Vector */ function Vector(x, y) { this.x = x || 0; this.y = y || 0; } Vector.add = function(a, b) { return new Vector(a.x + b.x, a.y + b.y); }; Vector.sub = function(a, b) { return new Vector(a.x - b.x, a.y - b.y); }; Vector.scale = function(v, s) { return v.clone().scale(s); }; Vector.random = function() { return new Vector( Math.random() * 2 - 1, Math.random() * 2 - 1 ); }; Vector.prototype = { set: function(x, y) { if (typeof x === 'object') { y = x.y; x = x.x; } this.x = x || 0; this.y = y || 0; return this; }, add: function(v) { this.x += v.x; this.y += v.y; return this; }, sub: function(v) { this.x -= v.x; this.y -= v.y; return this; }, scale: function(s) { this.x *= s; this.y *= s; return this; }, length: function() { return Math.sqrt(this.x * this.x + this.y * this.y); }, lengthSq: function() { return this.x * this.x + this.y * this.y; }, normalize: function() { var m = Math.sqrt(this.x * this.x + this.y * this.y); if (m) { this.x /= m; this.y /= m; } return this; }, angle: function() { return Math.atan2(this.y, this.x); }, angleTo: function(v) { var dx = v.x - this.x, dy = v.y - this.y; return Math.atan2(dy, dx); }, distanceTo: function(v) { var dx = v.x - this.x, dy = v.y - this.y; return Math.sqrt(dx * dx + dy * dy); }, distanceToSq: function(v) { var dx = v.x - this.x, dy = v.y - this.y; return dx * dx + dy * dy; }, lerp: function(v, t) { this.x += (v.x - this.x) * t; this.y += (v.y - this.y) * t; return this; }, clone: function() { return new Vector(this.x, this.y); }, toString: function() { return '(x:' + this.x + ', y:' + this.y + ')'; } }; /** * GravityPoint */ function GravityPoint(x, y, radius, targets) { Vector.call(this, x, y); this.radius = radius; this.currentRadius = radius * 0.5; this._targets = { particles: targets.particles || [], gravities: targets.gravities || [] }; this._speed = new Vector(); } GravityPoint.RADIUS_LIMIT = 80; GravityPoint.interferenceToPoint = true; GravityPoint.prototype = (function(o) { var s = new Vector(0, 0), p; for (p in o) s[p] = o[p]; return s; })({ gravity: 0.05, isMouseOver: false, dragging: false, destroyed: false, _easeRadius: 0, _dragDistance: null, _collapsing: false, hitTest: function(p) { return this.distanceTo(p) < this.radius; }, startDrag: function(dragStartPoint) { this._dragDistance = Vector.sub(dragStartPoint, this); this.dragging = true; }, drag: function(dragToPoint) { this.x = dragToPoint.x - this._dragDistance.x; this.y = dragToPoint.y - this._dragDistance.y; }, endDrag: function() { this._dragDistance = null; this.dragging = false; }, addSpeed: function(d) { this._speed = this._speed.add(d); }, collapse: function(e) { this.currentRadius *= 1.75; this._collapsing = true; }, render: function(ctx) { if (this.destroyed) return; var particles = this._targets.particles, i, len; for (i = 0, len = particles.length; i < len; i++) { particles[i].addSpeed(Vector.sub(this, particles[i]).normalize().scale(this.gravity)); } this._easeRadius = (this._easeRadius + (this.radius - this.currentRadius) * 0.07) * 0.95; this.currentRadius += this._easeRadius; if (this.currentRadius < 0) this.currentRadius = 0; if (this._collapsing) { this.radius *= 0.75; if (this.currentRadius < 1) this.destroyed = true; this._draw(ctx); return; } var gravities = this._targets.gravities, g, absorp, area = this.radius * this.radius * Math.PI, garea; for (i = 0, len = gravities.length; i < len; i++) { g = gravities[i]; if (g === this || g.destroyed) continue; if ( (this.currentRadius >= g.radius || this.dragging) && this.distanceTo(g) < (this.currentRadius + g.radius) * 0.85 ) { g.destroyed = true; this.gravity += g.gravity; absorp = Vector.sub(g, this).scale(g.radius / this.radius * 0.5); this.addSpeed(absorp); garea = g.radius * g.radius * Math.PI; this.currentRadius = Math.sqrt((area + garea * 3) / Math.PI); this.radius = Math.sqrt((area + garea) / Math.PI); } g.addSpeed(Vector.sub(this, g).normalize().scale(this.gravity)); } if (GravityPoint.interferenceToPoint && !this.dragging) this.add(this._speed); this._speed = new Vector(); if (this.currentRadius > GravityPoint.RADIUS_LIMIT) this.collapse(); this._draw(ctx); }, _draw: function(ctx) { var grd, r; ctx.save(); grd = ctx.createRadialGradient(this.x, this.y, this.radius, this.x, this.y, this.radius * 5); grd.addColorStop(0, 'rgba(0, 0, 0, 0.1)'); grd.addColorStop(1, 'rgba(0, 0, 0, 0)'); ctx.beginPath(); ctx.arc(this.x, this.y, this.radius * 5, 0, Math.PI * 2, false); ctx.fillStyle = grd; ctx.fill(); r = Math.random() * this.currentRadius * 0.7 + this.currentRadius * 0.3; grd = ctx.createRadialGradient(this.x, this.y, r, this.x, this.y, this.currentRadius); grd.addColorStop(0, 'rgba(0, 0, 0, 1)'); grd.addColorStop(1, Math.random() < 0.2 ? 'rgba(255, 196, 0, 0.15)' : 'rgba(103, 181, 191, 0.75)'); ctx.beginPath(); ctx.arc(this.x, this.y, this.currentRadius, 0, Math.PI * 2, false); ctx.fillStyle = grd; ctx.fill(); ctx.restore(); } }); /** * Particle */ function Particle(x, y, radius) { Vector.call(this, x, y); this.radius = radius; this._latest = new Vector(); this._speed = new Vector(); } Particle.prototype = (function(o) { var s = new Vector(0, 0), p; for (p in o) s[p] = o[p]; return s; })({ addSpeed: function(d) { this._speed.add(d); }, update: function() { if (this._speed.length() > 12) this._speed.normalize().scale(12); this._latest.set(this); this.add(this._speed); } // render: function(ctx) { // if (this._speed.length() > 12) this._speed.normalize().scale(12); // this._latest.set(this); // this.add(this._speed); // ctx.save(); // ctx.fillStyle = ctx.strokeStyle = '#fff'; // ctx.lineCap = ctx.lineJoin = 'round'; // ctx.lineWidth = this.radius * 2; // ctx.beginPath(); // ctx.moveTo(this.x, this.y); // ctx.lineTo(this._latest.x, this._latest.y); // ctx.stroke(); // ctx.beginPath(); // ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false); // ctx.fill(); // ctx.restore(); // } }); // Initialize (function() { // Configs var BACKGROUND_COLOR = 'rgba(15, 15, 30, 1)', // BACKGROUND_COLOR = 'rgba(255, 0, 0, 0.4)', PARTICLE_RADIUS = 1, G_POINT_RADIUS = 15, G_POINT_RADIUS_LIMITS = 650; // Vars var canvas, context, bufferCvs, bufferCtx, screenWidth, screenHeight, mouse = new Vector(), gravities = [], particles = [], grad, gui, control; // Event Listeners function resize(e) { screenWidth = canvas.width = window.innerWidth; screenHeight = canvas.height = window.innerHeight; bufferCvs.width = screenWidth; bufferCvs.height = screenHeight; context = canvas.getContext('2d'); bufferCtx = bufferCvs.getContext('2d'); var cx = canvas.width * 0.5, cy = canvas.height * 0.5; grad = context.createRadialGradient(cx, cy, 0, cx, cy, Math.sqrt(cx * cx + cy * cy)); grad.addColorStop(0, 'rgba(0, 0, 0, 0)'); grad.addColorStop(1, 'rgba(0, 0, 0, 0.35)'); } function mouseMove(e) { mouse.set(e.clientX, e.clientY); var i, g, hit = false; for (i = gravities.length - 1; i >= 0; i--) { g = gravities[i]; if ((!hit && g.hitTest(mouse)) || g.dragging) g.isMouseOver = hit = true; else g.isMouseOver = false; } canvas.style.cursor = hit ? 'pointer' : 'default'; } function mouseDown(e) { for (var i = gravities.length - 1; i >= 0; i--) { if (gravities[i].isMouseOver) { gravities[i].startDrag(mouse); return; } } gravities.push(new GravityPoint(e.clientX, e.clientY, G_POINT_RADIUS, { particles: particles, gravities: gravities })); } function mouseUp(e) { for (var i = 0, len = gravities.length; i < len; i++) { if (gravities[i].dragging) { gravities[i].endDrag(); break; } } } function doubleClick(e) { for (var i = gravities.length - 1; i >= 0; i--) { if (gravities[i].isMouseOver) { gravities[i].collapse(); break; } } } // Functions function addParticle(num) { var i, p; for (i = 0; i < num; i++) { p = new Particle( Math.floor(Math.random() * screenWidth - PARTICLE_RADIUS * 2) + 1 + PARTICLE_RADIUS, Math.floor(Math.random() * screenHeight - PARTICLE_RADIUS * 2) + 1 + PARTICLE_RADIUS, PARTICLE_RADIUS ); p.addSpeed(Vector.random()); particles.push(p); } } function removeParticle(num) { if (particles.length < num) num = particles.length; for (var i = 0; i < num; i++) { particles.pop(); } } // GUI Control control = { particleNum: 100 }; // Init canvas = document.getElementById('c'); bufferCvs = document.createElement('canvas'); window.addEventListener('resize', resize, false); resize(null); addParticle(control.particleNum); canvas.addEventListener('mousemove', mouseMove, false); canvas.addEventListener('mousedown', mouseDown, false); canvas.addEventListener('mouseup', mouseUp, false); canvas.addEventListener('dblclick', doubleClick, false); // GUI gui = new dat.GUI(); gui.add(control, 'particleNum', 0, 500).step(1).name('Particle Num').onChange(function() { var n = (control.particleNum | 0) - particles.length; if (n > 0) addParticle(n); else if (n < 0) removeParticle(-n); }); gui.add(GravityPoint, 'interferenceToPoint').name('Interference Between Point'); gui.close(); // Start Update var loop = function() { var i, len, g, p; context.save(); context.fillStyle = BACKGROUND_COLOR; context.fillRect(0, 0, screenWidth, screenHeight); context.fillStyle = grad; context.fillRect(0, 0, screenWidth, screenHeight); context.restore(); for (i = 0, len = gravities.length; i < len; i++) { g = gravities[i]; if (g.dragging) g.drag(mouse); g.render(context); if (g.destroyed) { gravities.splice(i, 1); len--; i--; } } bufferCtx.save(); bufferCtx.globalCompositeOperation = 'destination-out'; bufferCtx.globalAlpha = 0.35; bufferCtx.fillRect(0, 0, screenWidth, screenHeight); bufferCtx.restore(); // パーティクルをバッファに描画 // for (i = 0, len = particles.length; i < len; i++) { // particles[i].render(bufferCtx); // } len = particles.length; bufferCtx.save(); bufferCtx.fillStyle = bufferCtx.strokeStyle = '#fff'; bufferCtx.lineCap = bufferCtx.lineJoin = 'round'; bufferCtx.lineWidth = PARTICLE_RADIUS * 2; bufferCtx.beginPath(); for (i = 0; i < len; i++) { p = particles[i]; p.update(); bufferCtx.moveTo(p.x, p.y); bufferCtx.lineTo(p._latest.x, p._latest.y); } bufferCtx.stroke(); bufferCtx.beginPath(); for (i = 0; i < len; i++) { p = particles[i]; bufferCtx.moveTo(p.x, p.y); bufferCtx.arc(p.x, p.y, p.radius, 0, Math.PI * 2, false); } bufferCtx.fill(); bufferCtx.restore(); // バッファをキャンバスに描画 context.drawImage(bufferCvs, 0, 0); requestAnimationFrame(loop); }; loop(); })();
/* * The MIT License (MIT) * * Copyright (c) 2018 Richard Backhouse * * 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. */ import React from 'react'; import { Text, View, FlatList, StyleSheet, TouchableOpacity, ActivityIndicator, Alert, Image, Dimensions, Appearance, ActionSheetIOS, Platform } from 'react-native'; import { SearchBar, ButtonGroup } from "react-native-elements"; import { SwipeListView, SwipeRow } from 'react-native-swipe-list-view'; import Icon from 'react-native-vector-icons/Ionicons'; import MaterialCommunityIcon from 'react-native-vector-icons/MaterialCommunityIcons'; import FontAwesome5 from 'react-native-vector-icons/FontAwesome5'; import ActionButton from 'react-native-action-button'; import { ActionSheetCustom as ActionSheet } from 'react-native-actionsheet'; import MPDConnection from './MPDConnection'; import AlbumArt from './AlbumArt'; import Config from './Config'; import { StyleManager } from './Styles'; import NewPlaylistModal from './NewPlaylistModal'; class AlbumListItem extends React.PureComponent { constructor(props) { super(props); } onAlbumPress(item) { this.props.onAlbumPress(item); } onLongPress(item) { this.props.onLongPress(item); } render() { const styles = StyleManager.getStyles("artistsStyles"); const common = StyleManager.getStyles("styles"); const item = this.props.albumItem; return ( <TouchableOpacity onPress={this.onAlbumPress.bind(this, item)} onLongPress={this.onLongPress.bind(this, item)}> <View onLayout={(event) => { const {x, y, width, height} = event.nativeEvent.layout; this.props.setAlbumRowHeight(height+1); }} style={styles.itemContainer}> <View style={styles.paddingLeft}/> {item.imagePath === undefined && <FontAwesome5 name="compact-disc" size={20} style={common.icon}/> } {item.imagePath !== undefined && <Image style={styles.iconAlbumArt} source={{uri: item.imagePath}}/> } <View style={styles.itemTextContainer}> <Text style={styles.albumItem}>{item.name}</Text> <Text style={styles.albumItem}>{item.artist}</Text> </View> <Icon name="ios-more" size={20} style={common.icon}/> </View> </TouchableOpacity> ); } } class GridAlbumListItem extends React.PureComponent { constructor(props) { super(props); } onAlbumPress(item) { this.props.onAlbumPress(item); } onLongPress(item) { this.props.onLongPress(item); } render() { const styles = StyleManager.getStyles("artistsStyles"); const item = this.props.albumItem; const size = Dimensions.get('window').width/this.props.numColumns; const gridStyles = StyleSheet.create({ itemContainer: { width: size, height: size, alignItems: 'center' } }); return ( <TouchableOpacity onPress={this.onAlbumPress.bind(this, item)} onLongPress={this.onLongPress.bind(this, item)}> <View style={gridStyles.itemContainer}> {item.imagePath === undefined && <Image style={{width: size-30, height: size-30, paddingLeft: 5, paddingRight: 5, resizeMode: 'contain'}} source={require('./images/cd-large.png')}/> } {item.imagePath !== undefined && <Image style={{width: size-30, height: size-30, paddingLeft: 5, paddingRight: 5, resizeMode: 'contain'}} source={{uri: item.imagePath}}/> } <View style={styles.gridItem}> <Text numberOfLines={1} ellipsizeMode='tail' style={styles.albumGridItem}>{item.name}</Text> <Text numberOfLines={1} ellipsizeMode='tail' style={styles.albumGridItem}>{item.artist}</Text> </View> </View> </TouchableOpacity> ); } } class ArtistListItem extends React.PureComponent { constructor(props) { super(props); } onPress(item) { this.props.onPress(item); } render() { const styles = StyleManager.getStyles("artistsStyles"); const common = StyleManager.getStyles("styles"); const item = this.props.artistItem; return ( <TouchableOpacity onPress={this.onPress.bind(this, item)}> <View onLayout={(event) => { const {x, y, width, height} = event.nativeEvent.layout; this.props.setArtistRowHeight(height+1); }} style={styles.itemContainer}> <View style={styles.paddingLeft}/> {item.imagePath === undefined && <MaterialCommunityIcon name="artist" size={20} style={common.icon}/> } {item.imagePath !== undefined && <Image style={styles.iconAlbumArt} source={{uri: item.imagePath}}/> } <View style={styles.itemTextContainer}> <Text style={styles.item}>{item.name}</Text> </View> <Icon name="ios-more" size={20} style={common.icon}/> </View> </TouchableOpacity> ); } } class GenreListItem extends React.PureComponent { constructor(props) { super(props); } genreAlbums() { this.props.genreAlbums(this.props.genreMap, this.props.genreItem); } genreSongs(item) { this.props.genreSongs(this.props.genreMap, this.props.genreItem); } render() { const styles = StyleManager.getStyles("artistsStyles"); const common = StyleManager.getStyles("styles"); const item = this.props.genreItem; return ( <SwipeRow rightOpenValue={-150}> <View style={common.rowBack}> <TouchableOpacity style={[common.backRightBtn, common.backRightBtnLeft]} onPress={ _ => this.genreAlbums() }> <Text style={common.backTextWhite}>Albums</Text> </TouchableOpacity> <TouchableOpacity style={[common.backRightBtn, common.backRightBtnRight]} onPress={ _ => this.genreSongs() }> <Text style={common.backTextWhite}>Songs</Text> </TouchableOpacity> </View> <View style={[styles.genreContainer, common.rowFront]}> <MaterialCommunityIcon name="guitar-acoustic" size={20} style={common.icon}/> <View style={styles.itemTextContainer}> <Text style={styles.item}>{item.name}</Text> </View> <Icon name="ios-swap" size={20} style={common.icon}/> </View> </SwipeRow> ); } } export default class ArtistsScreen extends React.Component { static navigationOptions = ({ navigation }) => { return { title: "Browse" }; }; constructor(props) { super(props); this.artistRowHeight = 60; this.albumRowHeight = 60; this.state = { searchValue: "", searchGenreValue: "", searchAlbumValue: "", artists: [], fullset: [], genres: [], genresFullset: [], genreMap: {}, albums: [], albumsFullset: [], selectedTab: 0, loading: false, realTotal: 0, maxListSize: 0, grid: false, numColumns: 1, defaultArtistSort: true, defaultAlbumSort: true, defaultGenreSort: true, modalVisible: false, selectedItem: {} }; } componentDidMount() { if (!MPDConnection.isConnected()) { this.props.navigation.navigate('Settings'); this.props.navigation.navigate('Connections'); } Config.getGridViewConfig() .then((gridViewConfig) => { if (gridViewConfig[0]) { this.setState({grid: true}); } }); const { navigation } = this.props; navigation.setParams({ sort: this.sort }); this.load(); this.onConnect = MPDConnection.getEventEmitter().addListener( "OnConnect", () => { this.load(); } ); this.onDisconnect = MPDConnection.getEventEmitter().addListener( "OnDisconnect", () => { this.setState({artists: [], fullset: []}); } ); this.onAlbumArtEnd = AlbumArt.getEventEmitter().addListener( "OnAlbumArtEnd", (album) => { let idx = this.state.fullset.findIndex((a) => {return a.name === album.artist}); if (idx !== -1 && this.state.fullset[idx].imagePath === undefined) { this.state.fullset[idx].imagePath = "file://"+album.path; this.setState({artists: this.state.artists, fullset: this.state.fullset}); } idx = this.state.albumsFullset.findIndex((a) => {return a.name === album.name && a.artist === album.artist}); if (idx !== -1) { this.state.albumsFullset[idx].imagePath = "file://"+album.path; this.setState({albums: this.subset(this.state.albumsFullset), albumsFullset: this.state.albumsFullset}); } } ); this.onAlbumArtError = AlbumArt.getEventEmitter().addListener( "OnAlbumArtError", (details) => { let idx = this.state.fullset.findIndex((a) => {return a.name === details.album.artist}); if (idx !== -1 && this.state.fullset[idx].imagePath === undefined) { this.state.fullset[idx].imagePath = undefined; this.setState({artists: this.state.artists, fullset: this.state.fullset}); } idx = this.state.albumsFullset.findIndex((a) => {return a.name === details.album.name && a.artist === details.album.artist}); if (idx !== -1) { this.state.albumsFullset[idx].imagePath = undefined; this.setState({albums: this.subset(this.state.albumsFullset), albumsFullset: this.state.albumsFullset}); } } ); this.onAlbumArtComplete = AlbumArt.getEventEmitter().addListener( "OnAlbumArtComplete", () => { this.updateAlbumArt(); } ); this.onApperance = Appearance.addChangeListener(({ colorScheme }) => { this.setState({loading: this.state.loading}); }); Config.getMaxListSize() .then((size) => { //this.setState({maxListSize: size}); }); } updateAlbumArt() { AlbumArt.getAlbumArtForArtists() .then((artMap) => { this.state.fullset.forEach((artist) => { if (artMap[artist.name]) { artist.imagePath = "file://"+artMap[artist.name]; } }) this.setState({artists: this.state.artists, fullset: this.state.fullset}); }); AlbumArt.getAlbumArtForAlbums(this.state.albumsFullset).then((albums) => { this.setState({albums: this.subset(albums), albumsFullset: albums}); }); } load() { Config.getSortSettings() .then((sortSettings) => { const allArtist = MPDConnection.current().getAllArtists(); const allAlbums = MPDConnection.current().getAllAlbums(true, sortSettings.albumSortByArtist); const allGenres = MPDConnection.current().getAllGenres(); this.setState({loading: true, defaultAlbumSort: !sortSettings.albumSortByArtist}); Promise.all([allArtist, allAlbums, allGenres]) .then((results) => { this.setState({loading: false}); let artists = results[0]; let albums = results[1]; let genres = results[2]; artists.forEach((artist, index) => { artist.key = ""+(index+1); }); this.setState({artists: artists, fullset: artists}); AlbumArt.getAlbumArtForArtists() .then((artMap) => { artists.forEach((artist) => { if (artMap[artist.name]) { artist.imagePath = "file://"+artMap[artist.name]; } }) this.setState({artists: this.state.artists, fullset: this.state.fullset}); }); albums.forEach((album, index) => { album.key = ""+(index+1); }); AlbumArt.getAlbumArtForAlbums(albums).then((albums) => { this.setState({albums: this.subset(albums), albumsFullset: albums}); }); let genreList = []; let index = 0; for (let genre in genres) { genreList.push({ key: ""+(++index), name: genre }); } genreList.sort((a,b) => { if (a.name < b.name) { return -1; } else if (a.name > b.name) { return 1; } else { return 0; } }); this.setState({genres: genreList, genresFullset: genreList, genreMap: genres}); }) .catch((err) => { this.setState({loading: false}); Alert.alert( "MPD Error", "Error : "+err ); }); }); } componentWillUnmount() { this.onConnect.remove(); this.onDisconnect.remove(); this.onAlbumArtEnd.remove(); this.onAlbumArtComplete.remove(); this.onAlbumArtError.remove(); if (this.onApperance) { this.onApperance.remove(); } } search = (text) => { if (text.length > 0) { let filtered = this.state.fullset.filter((artist) => { return artist.name.toLowerCase().indexOf(text.toLowerCase()) > -1; }); this.setState({artists: filtered, searchValue: text}); } else { this.setState({artists: this.state.fullset, searchValue: text}); } } searchGenres = (text) => { if (text.length > 0) { let filtered = this.state.genresFullset.filter((genre) => { return genre.name.toLowerCase().indexOf(text.toLowerCase()) > -1; }); this.setState({genres: filtered, searchGenreValue: text}); } else { this.setState({genres: this.state.genresFullset, searchGenreValue: text}); } } searchAlbums = (text) => { if (text.length > 0) { let filtered = this.state.albumsFullset.filter((album) => { return album.name.toLowerCase().indexOf(text.toLowerCase()) > -1; }); this.setState({albums: this.subset(filtered), searchAlbumValue: text}); } else { this.setState({albums: this.subset(this.state.albumsFullset), searchAlbumValue: text}); } } sort = () => { if (this.state.selectedTab === 0) { const useDefault = !this.state.defaultArtistSort; this.setState({defaultArtistSort: useDefault}); this.state.artists.sort((a,b) => { let artist1 = a.name; let artist2 = b.name; let split = artist1.split(' '); if (split.length > 1 && split[0].toLowerCase() === "the" && split[1].toLowerCase() !== "the") { split.shift(); artist1 = split.join(' '); } split = artist2.split(' '); if (split.length > 1 && split[0].toLowerCase() === "the" && split[1].toLowerCase() !== "the") { split.shift(); artist2 = split.join(' '); } if (artist1 < artist2) { return useDefault ? -1 : 1; } else if (artist1 > artist2) { return useDefault ? 1 : -1; } else { return 0; } }); this.setState({artists: this.state.artists}); } else if (this.state.selectedTab === 1) { const useDefault = !this.state.defaultAlbumSort; this.setState({defaultAlbumSort: useDefault}); this.state.albums.sort((a,b) => { comp1 = a.name; comp2 = b.name; if (!useDefault && a.artist && b.artist) { comp1 = a.artist; comp2 = b.artist; } if (comp1 < comp2) { return -1; } else if (comp1 > comp2) { return 1; } else { return 0; } }); this.setState({albums: this.state.albums}); } else if (this.state.selectedTab === 2) { const useDefault = !this.state.defaultGenreSort; this.setState({defaultGenreSort: useDefault}); this.state.genres.sort((a,b) => { if (a.name < b.name) { return useDefault ? -1 : 1; } else if (a.name > b.name) { return useDefault ? 1 : -1; } else { return 0; } }); this.setState({genres: this.state.genres}); } }; onPress(item) { const { navigation } = this.props; navigation.navigate('Albums', {artist: item.name}); } onAlbumPress(item) { const { navigation } = this.props; navigation.navigate('Songs', {album: item.name}); } onLongPress(item) { if (Platform.OS === 'ios') { ActionSheetIOS.showActionSheetWithOptions({ options: ['Add to Queue', 'Add to Playlist', 'Reload Album Art', 'Cancel'], title: item.artist, message: item.name, cancelButtonIndex: 3 }, (idx) => { this.doActionSheetAction(idx, item); }); } else { this.currentItem = item; this.ActionSheet.show(); } } doActionSheetAction(idx, i) { const item = i || this.currentItem; switch (idx) { case 0: this.setState({loading: true}); MPDConnection.current().addAlbumToPlayList(item.name, item.artist) .then(() => { this.setState({loading: false}); }) .catch((err) => { this.setState({loading: false}); Alert.alert( "MPD Error", "Error : "+err ); }); break; case 1: this.setState({modalVisible: true, selectedItem: {artist: item.artist, album: item.name}}); break; case 2: this.setState({loading: true}); AlbumArt.reloadAlbumArt(item.name, item.artist) .then(()=> { this.setState({loading: false}); }) .catch((err) => { this.setState({loading: false}); }); break; } this.currentItem = undefined; } finishAdd(name, selectedItem) { this.setState({modalVisible: false}); MPDConnection.current().setCurrentPlaylistName(name); this.setState({loading: true}); MPDConnection.current().addAlbumToNamedPlayList(selectedItem.album, selectedItem.artist, MPDConnection.current().getCurrentPlaylistName()) .then(() => { this.setState({loading: false}); }) .catch((err) => { this.setState({loading: false}); Alert.alert( "MPD Error", "Error : "+err ); }); } subset(albums) { this.setState({realTotal: albums.length}); const maxListSize = this.state.maxListSize; if (maxListSize === 0) { return albums; } if (albums.length > maxListSize) { return albums.slice(0, maxListSize); } else { return albums; } } genreAlbums(rowMap, item) { if (rowMap[item.key]) { rowMap[item.key].closeRow(); } const albumNames = this.state.genreMap[item.name]; let albums = []; albumNames.forEach((albumName) => { let artist; this.state.albumsFullset.forEach((album) => { if (album.name === albumName) { artist = album.artist; } }) albums.push({name: albumName, artist: artist}); }); const { navigation } = this.props; navigation.navigate('Albums', {albums: albums, genre: item.name}); } genreSongs(rowMap, item) { if (rowMap[item.key]) { rowMap[item.key].closeRow(); } const { navigation } = this.props; navigation.navigate('Songs', {genre: item.name}); } changeTab(index) { const {height, width} = Dimensions.get('window'); if (index === 1 && this.state.grid) { Config.getGridViewColumns() .then((numColumns) => { this.setState({ selectedTab: index, numColumns: numColumns }); }); } else { this.setState({ selectedTab: index, numColumns: 1 }); } } renderSeparator = () => { const common = StyleManager.getStyles("styles"); return ( <View style={common.separator} /> ); }; renderItem = ({item}) => { const styles = StyleManager.getStyles("artistsStyles"); const common = StyleManager.getStyles("styles"); return ( <TouchableOpacity onPress={this.onPress.bind(this, item)}> <View onLayout={(event) => { const {x, y, width, height} = event.nativeEvent.layout; this.artistRowHeight = height+1; }} style={styles.itemContainer}> <View style={styles.paddingLeft}/> {item.imagePath === undefined && <MaterialCommunityIcon name="artist" size={20} style={common.icon}/> } {item.imagePath !== undefined && <Image style={styles.iconAlbumArt} source={{uri: item.imagePath}}/> } <View style={styles.itemTextContainer}> <Text style={styles.item}>{item.name}</Text> </View> <Icon name="ios-more" size={20} style={common.icon}/> </View> </TouchableOpacity> ); }; renderGenreItem = (data, map) => { const styles = StyleManager.getStyles("artistsStyles"); const common = StyleManager.getStyles("styles"); const item = data.item; return ( <SwipeRow rightOpenValue={-150}> <View style={common.rowBack}> <TouchableOpacity style={[common.backRightBtn, common.backRightBtnLeft]} onPress={ _ => this.genreAlbums(map, item) }> <Text style={common.backTextWhite}>Albums</Text> </TouchableOpacity> <TouchableOpacity style={[common.backRightBtn, common.backRightBtnRight]} onPress={ _ => this.genreSongs(map, item) }> <Text style={common.backTextWhite}>Songs</Text> </TouchableOpacity> </View> <View style={[styles.genreContainer, common.rowFront]}> <MaterialCommunityIcon name="guitar-acoustic" size={20} style={common.icon}/> <View style={styles.itemTextContainer}> <Text style={styles.item}>{item.name}</Text> </View> <Icon name="ios-swap" size={20} style={common.icon}/> </View> </SwipeRow> ); } /* renderAlbumItem = ({item}) => { const styles = StyleManager.getStyles("artistsStyles"); const common = StyleManager.getStyles("styles"); return ( <TouchableOpacity onPress={this.onAlbumPress.bind(this, item)} onLongPress={this.onLongPress.bind(this, item)}> <View onLayout={(event) => { const {x, y, width, height} = event.nativeEvent.layout; this.albumRowHeight = height+1; }} style={styles.itemContainer}> <View style={styles.paddingLeft}/> {item.imagePath === undefined && <FontAwesome5 name="compact-disc" size={20} style={common.icon}/> } {item.imagePath !== undefined && <Image style={styles.iconAlbumArt} source={{uri: item.imagePath}}/> } <View style={styles.itemTextContainer}> <Text style={styles.albumItem}>{item.name}</Text> <Text style={styles.albumItem}>{item.artist}</Text> </View> <Icon name="ios-more" size={20} style={common.icon}/> </View> </TouchableOpacity> ); } */ renderAlbumItem = ({item}) => { return ( <AlbumListItem albumItem={item} onAlbumPress={(item) => {this.onAlbumPress(item);}} onLongPress={(item) => {this.onLongPress(item);}} setAlbumRowHeight={(height) => {this.albumRowHeight = height;}}/> ); } /* renderGridAlbumItem = ({item}) => { const styles = StyleManager.getStyles("artistsStyles"); const common = StyleManager.getStyles("styles"); const size = Dimensions.get('window').width/this.state.numColumns; const gridStyles = StyleSheet.create({ itemContainer: { width: size, height: size, alignItems: 'center' } }); return ( <TouchableOpacity onPress={this.onAlbumPress.bind(this, item)} onLongPress={this.onLongPress.bind(this, item)}> <View style={gridStyles.itemContainer}> {item.imagePath === undefined && <Image style={{width: size-30, height: size-30, paddingLeft: 5, paddingRight: 5, resizeMode: 'contain'}} source={require('./images/cd-large.png')}/> } {item.imagePath !== undefined && <Image style={{width: size-30, height: size-30, paddingLeft: 5, paddingRight: 5, resizeMode: 'contain'}} source={{uri: item.imagePath}}/> } <View style={styles.gridItem}> <Text numberOfLines={1} ellipsizeMode='tail' style={styles.albumGridItem}>{item.name}</Text> <Text numberOfLines={1} ellipsizeMode='tail' style={styles.albumGridItem}>{item.artist}</Text> </View> </View> </TouchableOpacity> ); } */ renderGridAlbumItem = ({item}) => { return ( <GridAlbumListItem numColumns={this.state.numColumns} albumItem={item} onAlbumPress={(item) => {this.onAlbumPress(item);}} onLongPress={(item) => {this.onLongPress(item);}}/> ); } /* renderItem = ({item}) => { return ( <ArtistListItem artistItem={item} onPress={(item) => {this.onPress(item);}} setArtistRowHeight={(height) => {this.artistRowHeight = height;}}/> ); }; renderGenreItem = (data, map) => { const item = data.item; return ( <GenreListItem genreItem={item} genreMap={map} genreAlbums={(map, item) => {this.genreAlbums(map, item);}} genreSongs={(map, item) => {this.genreSongs(map, item);}}/> ); } */ getArtistItemLayout = (item, index) => { return {offset: this.artistRowHeight * index, length: this.artistRowHeight, index: index}; } getAlbumItemLayout = (item, index) => { return {offset: this.albumRowHeight * index, length: this.albumRowHeight, index: index}; } render() { const styles = StyleManager.getStyles("artistsStyles"); const common = StyleManager.getStyles("styles"); const {height, width} = Dimensions.get('window'); let bg = .07; let sb = .1; let fl = .84; if (width < 321) { bg = .1; fl = .8; } if (this.state.selectedTab === 0) { return ( <View style={common.container1}> <View style={{flex: bg, width: "100%"}}> <ButtonGroup onPress={(index) => { this.changeTab(index); }} selectedIndex={this.state.selectedTab} buttons={['Artists', 'Albums', 'Genres']} containerStyle={common.containerStyle} selectedButtonStyle={common.selectedButtonStyle} selectedTextStyle={common.selectedTextStyle} /> </View> <View style={{flex: sb, flexDirection: 'row', alignItems: 'center'}}> <View style={common.flex75}> <SearchBar clearIcon lightTheme round platform="ios" cancelButtonTitle="Cancel" placeholder='Search' onChangeText={this.search} value={this.state.searchValue} containerStyle={common.searchbarContainer} inputContainerStyle={common.searchbarInputContainer} inputStyle={common.searchbarInput} /> </View> <View style={common.flex25}> <Text style={common.text}> Total : {this.state.artists.length} </Text> </View> </View> <View style={{flex: fl, width: "100%"}}> <FlatList data={this.state.artists} renderItem={this.renderItem} renderSectionHeader={({section}) => <Text style={common.sectionHeader}>{section.title}</Text>} keyExtractor={item => item.key} ItemSeparatorComponent={this.renderSeparator} key={this.state.numColumns} getItemLayout={this.getArtistItemLayout} /> </View> {this.state.loading && <View style={common.loading}> <ActivityIndicator size="large" color="#0000ff"/> </View> } </View> ); } else if (this.state.selectedTab === 1) { return ( <View style={common.container1}> <View style={{flex: bg, width: "100%"}}> <ButtonGroup onPress={(index) => { this.changeTab(index); }} selectedIndex={this.state.selectedTab} buttons={['Artists', 'Albums', 'Genres']} containerStyle={common.containerStyle} selectedButtonStyle={common.selectedButtonStyle} selectedTextStyle={common.selectedTextStyle} /> </View> <View style={{flex: sb, flexDirection: 'row', alignItems: 'center'}}> <View style={common.flex75}> <SearchBar clearIcon lightTheme round platform="ios" cancelButtonTitle="Cancel" placeholder='Search' onChangeText={this.searchAlbums} value={this.state.searchAlbumValue} containerStyle={common.searchbarContainer} inputContainerStyle={common.searchbarInputContainer} inputStyle={common.searchbarInput} /> </View> <View style={common.flex25}> <Text style={common.text}> Total : {this.state.realTotal} </Text> </View> </View> <View style={{flex: fl, width: "100%"}}> {this.state.grid === false && <FlatList data={this.state.albums} renderItem={this.renderAlbumItem} renderSectionHeader={({section}) => <Text style={common.sectionHeader}>{section.title}</Text>} keyExtractor={item => item.key} ItemSeparatorComponent={this.renderSeparator} key={this.state.numColumns} getItemLayout={this.getAlbumItemLayout} /> } {this.state.grid === true && <FlatList data={this.state.albums} renderItem={this.renderGridAlbumItem} keyExtractor={item => item.key} numColumns={this.state.numColumns} columnWrapperStyle={common.row} key={this.state.numColumns} /> } </View> <NewPlaylistModal visible={this.state.modalVisible} selectedItem={this.state.selectedItem} onSet={(name, selectedItem) => {this.finishAdd(name, selectedItem);}} onCancel={() => this.setState({modalVisible: false})}></NewPlaylistModal> {Platform.OS === 'android' && <ActionSheet ref={o => this.ActionSheet = o} options={['Add to Queue', 'Add to Playlist', 'Reload Album Art', 'Cancel']} cancelButtonIndex={3} onPress={(idx) => { this.doActionSheetAction(idx); }} /> } <ActionButton buttonColor="rgba(231,76,60,1)" hideShadow={true}> <ActionButton.Item buttonColor='#3498db' title="List View" size={40} textStyle={common.actionButtonText} onPress={() => {this.setState({grid: false, numColumns: 1});}}> <Icon name="ios-list" size={20} color="white"/> </ActionButton.Item> <ActionButton.Item buttonColor='#9b59b6' title="Grid View" size={40} textStyle={common.actionButtonText} onPress={() => { Config.getGridViewColumns() .then((numColumns) => { this.setState({grid: true, numColumns: numColumns}); }); }}> <Icon name="ios-grid" size={20} color="white"/> </ActionButton.Item> </ActionButton> {this.state.loading && <View style={common.loading}> <ActivityIndicator size="large" color="#0000ff"/> </View> } </View> ); } else if (this.state.selectedTab === 2) { return ( <View style={common.container1}> <View style={{flex: bg, width: "100%"}}> <ButtonGroup onPress={(index) => { this.changeTab(index); }} selectedIndex={this.state.selectedTab} buttons={['Artists', 'Albums', 'Genres']} containerStyle={common.containerStyle} selectedButtonStyle={common.selectedButtonStyle} selectedTextStyle={common.selectedTextStyle} /> </View> <View style={{flex: sb, flexDirection: 'row', alignItems: 'center'}}> <View style={common.flex75}> <SearchBar clearIcon lightTheme round platform="ios" cancelButtonTitle="Cancel" placeholder='Search' onChangeText={this.searchGenres} value={this.state.searchGenreValue} containerStyle={common.searchbarContainer} inputContainerStyle={common.searchbarInputContainer} inputStyle={common.searchbarInput} /> </View> <View style={common.flex25}> <Text style={common.text}> Total : {this.state.genres.length} </Text> </View> </View> <View style={{flex: fl, width: "100%"}}> <SwipeListView useFlatList data={this.state.genres} keyExtractor={item => item.key} renderItem={this.renderGenreItem} renderSectionHeader={({section}) => <Text style={common.sectionHeader}>{section.title}</Text>} ItemSeparatorComponent={this.renderSeparator} /> </View> {this.state.loading && <View style={common.loading}> <ActivityIndicator size="large" color="#0000ff"/> </View> } </View> ); } } }
var path = require('path'); var webpack = require('webpack'); module.exports = { cache: true, entry: './index.js', output: { path: path.resolve('./build'), filename: 'lib.js' }, module: { rules: [ { test: /\.js?$/, exclude: /(node_modules)/, loader: 'babel-loader', options: { cacheDirectory: true } }, ] } }
// Constants: import { TOGGLE_THEME, TOGGLE_EXTENSION_VISIBILITY, UPDATE_EXTENSION_FOOTER, UPDATE_EXTENSION, UPDATE_AUTH, UPDATE_DATABASE, } from '../action-types'; // Exports: export const toggleTheme = (payload) => { return { type: TOGGLE_THEME, payload }; }; export const toggleExtensionVisibility = (payload) => { return { type: TOGGLE_EXTENSION_VISIBILITY, payload }; }; export const updateExtensionFooter = (payload) => { return { type: UPDATE_EXTENSION_FOOTER, payload }; }; export const updateExtension = (payload) => { return { type: UPDATE_EXTENSION, payload }; }; export const updateAuth = (payload) => { return { type: UPDATE_AUTH, payload }; }; export const updateDatabase = (payload) => { return { type: UPDATE_DATABASE, payload }; };
$(document).ready(function(){ $(window).scroll(function(){ var windowWidth = $(window).width(); if (windowWidth > 800){ var scroll = $(window).scrollTop(); $('header .textos').css({ transform: 'translate(0px, '+scroll/2+'%)' }); $('main .acerca-de article').css({ transform: 'translate(0px, -'+ scroll/4 +'%)' }); } }); $(window).resize(function(){ var windowWidth = $(window).width(); if (windowWidth < 800){ $('main .acerca-de article').css({ transform: 'translate(0px, 0px)' }); } }) });
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var TwitterOutline = { name: 'twitter', theme: 'outline', icon: { tag: 'svg', attrs: { viewBox: '64 64 896 896' }, children: [ { tag: 'path', attrs: { d: 'M928 254.3c-30.6 13.2-63.9 22.7-98.2 26.4a170.1 170.1 0 0 0 75-94 336.64 336.64 0 0 1-108.2 41.2A170.1 170.1 0 0 0 672 174c-94.5 0-170.5 76.6-170.5 170.6 0 13.2 1.6 26.4 4.2 39.1-141.5-7.4-267.7-75-351.6-178.5a169.32 169.32 0 0 0-23.2 86.1c0 59.2 30.1 111.4 76 142.1a172 172 0 0 1-77.1-21.7v2.1c0 82.9 58.6 151.6 136.7 167.4a180.6 180.6 0 0 1-44.9 5.8c-11.1 0-21.6-1.1-32.2-2.6C211 652 273.9 701.1 348.8 702.7c-58.6 45.9-132 72.9-211.7 72.9-14.3 0-27.5-.5-41.2-2.1C171.5 822 261.2 850 357.8 850 671.4 850 843 590.2 843 364.7c0-7.4 0-14.8-.5-22.2 33.2-24.3 62.3-54.4 85.5-88.2z' } } ] } }; exports.default = TwitterOutline;
let block15 = document.querySelectorAll('.block15'); if (block15.length) { for (let index = 0; index < block15.length; index++) { let block = block15[index]; let items = block15[index].querySelectorAll('.block15__item'); for (let i = 0; i < items.length; i++) { let inner_styles = '.block15[data-block="'+index+'"] .block15__item-container[data-index="'+i+'"]:hover {' + 'max-height: '+ items[i].clientHeight + 'px;' + '}'; let styles_cont = document.createElement('style'); styles_cont.innerText = inner_styles; block.prepend(styles_cont); } } }
(function(d){d['pt-br']=Object.assign(d['pt-br']||{},{a:"Não foi possível enviar o arquivo:",b:"Image toolbar",c:"Table toolbar",d:"Itálico",e:"Negrito",f:"Escolha o título",g:"Titulo",h:"Bloco de citação",i:"Ferramenta de imagem",j:"Ferramenta de mídia",k:"Inserir mídia",l:"A URL não pode ficar em branco.",m:"A URL desta mídia não é suportada.",n:"Inserir legenda da imagem",o:"Imagem completa",p:"Imagem lateral",q:"Imagem alinhada à esquerda",r:"Imagem centralizada",s:"Imagem alinhada à direita",t:"Inserir imagem ou arquivo",u:"Inserir imagem",v:"Falha ao subir arquivo",w:"Link",x:"Lista numerada",y:"Lista com marcadores",z:"Alinhar à esquerda",aa:"Alinhar à direita",ab:"Centralizar",ac:"Justificar",ad:"Alinhamento do texto",ae:"Text alignment toolbar",af:"Inserir tabela",ag:"Coluna de cabeçalho",ah:"Inserir coluna à esquerda",ai:"Inserir coluna à direita",aj:"Excluir coluna",ak:"Coluna",al:"Linha de cabeçalho",am:"Inserir linha abaixo",an:"Inserir linha acima",ao:"Excluir linha",ap:"Linha",aq:"Mesclar acima",ar:"Mesclar à direita",as:"Mesclar abaixo",at:"Mesclar à esquerda",au:"Dividir verticalmente",av:"Dividir horizontalmente",aw:"Mesclar células",ax:"Enviando dados",ay:"Widget toolbar",az:"Parágrafo",ba:"Título 1",bb:"Título 2",bc:"Título 3",bd:"Título 4",be:"Título 5",bf:"Título 6",bg:"Alterar texto alternativo da imagem",bh:"Não foi possível obter o endereço da imagem redimensionada",bi:"Seleção da imagem redimensionada falhou",bj:"Não foi possível inserir a imagem na posição atual",bk:"Falha ao inserir imagem",bl:"Editor toolbar",bm:"Dropdown toolbar",bn:"Editor de Formatação",bo:"Editor de Formatação, %0",bp:"Salvar",bq:"Cancelar",br:"URL",bs:"Remover link",bt:"Editar link",bu:"Abrir link em nova aba",bv:"Este link não possui uma URL",bw:"%0 de %1",bx:"Anterior",by:"Próximo",bz:"Abrir em nova aba",ca:"Pode ser baixado",cb:"Texto alternativo",cc:"Desfazer",cd:"Refazer",ce:"Cole o endereço da mídia no campo.",cf:"Cole o endereço dentro do conteúdo para embutir mais rapidamente.",cg:"URL da mídia"})})(window.CKEDITOR_TRANSLATIONS||(window.CKEDITOR_TRANSLATIONS={}));
import React, { useState, useRef } from 'react' import pageStyles from '../../helpers/Styles/page-components.module.css' import styles from './results.module.css' import rangeStyles from '../Survey/range.module.css' import ResultsIntro from '../ResultsIntro' import ResultsGraph from '../ResultsGraph' import iconFullscreen from '../../img/icon-fullscreen.svg' const DEFAULT_MONTH_DISPLAYED = 13; const MOOD_DATA_URL = `${process.env.NODE_ENV === 'production'? '' : 'http://localhost:9000'}/.netlify/functions/moods` const Results = ({ surveyComplete }) => { const [monthsDisplayed, setMonthsDisplayed] = useState(DEFAULT_MONTH_DISPLAYED) const [showTrendline, setShowTrendline] = useState(true) const [moodSubmissions, setMoodSubmissions] = useState([]) const graphRef = useRef() const isCancelled = React.useRef(false); async function fetchData() { const fetcher = await window.fetch(MOOD_DATA_URL) const response = await fetcher.json() if (!isCancelled.current) { setMoodSubmissions(response) } } React.useEffect(() => { fetchData() return () => { isCancelled.current = true; }; }, []); return ( <> <ResultsIntro surveyComplete={surveyComplete} /> <hr className={pageStyles.divider} /> <div className={[pageStyles.content, styles.results].join(" ")} ref={graphRef}> <h2 className={pageStyles.pageHeading}>Volunteer mood over time (months)</h2> <div className={styles.graphRange}> <p className={styles.questionText}>Graph range</p> <label> <input className={[styles.monthsRange, rangeStyles.range].join(" ")} type="range" min="2" max="13" onChange={(e) => setMonthsDisplayed(e.currentTarget.value)} value={monthsDisplayed} /> <div className={styles.monthsText}> <span className={styles.monthsValue}>{monthsDisplayed - 1}</span> <span className={styles.monthsUnit}>{monthsDisplayed === 1? 'month' : 'months'}</span> </div> </label> </div> <div className={styles.graphSettings}> <p className={styles.questionText}>Trendline</p> <label className={styles.closedQuestion}> <input className={styles.closedAnswer} checked={showTrendline} onChange={e => setShowTrendline(e.currentTarget.checked)} type="checkbox" name="moodNegatives" /> Show average trendline </label> </div> {/* <button className={styles.fullscreenBtn} onClick={() => graphRef.current.requestFullscreen()} aria-label="Show full-screen graph"><img src={iconFullscreen} alt="fullscreen icon" aria-label="Fullscreen" /></button> */} <ResultsGraph moodSubmissions={moodSubmissions} monthsDisplayed={monthsDisplayed} showTrendline={showTrendline} /> </div> </> ) } export default Results
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.createIPXHandler = void 0; const path_1 = require("path"); const os_1 = require("os"); const ipx_1 = require("ipx"); const functions_1 = require("@netlify/functions"); const ufo_1 = require("ufo"); const etag_1 = __importDefault(require("etag")); const http_1 = require("./http"); function createIPXHandler({ cacheDir = (0, path_1.join)((0, os_1.tmpdir)(), 'ipx-cache'), basePath = '/_ipx', ...opts } = {}) { const ipx = (0, ipx_1.createIPX)({ ...opts, dir: (0, path_1.join)(cacheDir, 'cache') }); const handler = async (event, _context) => { const host = event.headers.host; const protocol = event.headers['x-forwarded-proto'] || 'http'; let domains = opts.domains || []; const requestEtag = event.headers['if-none-match']; const url = event.path.replace(basePath, ''); const [modifiers = '_', ...segments] = url.substr(1).split('/'); let id = decodeURIComponent(segments.join('/')); const requestHeaders = {}; const isLocal = !id.startsWith('http'); if (isLocal) { id = `${protocol}://${host}${id.startsWith('/') ? '' : '/'}${id}`; if (event.headers.cookie) { requestHeaders.cookie = event.headers.cookie; } if (event.headers.authorization) { requestHeaders.authorization = event.headers.authorization; } } else { if (typeof domains === 'string') { domains = domains.split(',').map(s => s.trim()); } const hosts = domains.map(domain => (0, ufo_1.parseURL)(domain, 'https://').host); // Parse id as URL const parsedUrl = (0, ufo_1.parseURL)(id, 'https://'); // Check host if (!parsedUrl.host) { return { statusCode: 403, body: 'Hostname is missing: ' + id }; } if (!hosts.find(host => parsedUrl.host === host)) { return { statusCode: 403, body: 'Hostname is missing: ' + parsedUrl.host }; } } const { response, cacheKey, responseEtag } = await (0, http_1.loadSourceImage)({ cacheDir, url: id, requestEtag, modifiers, isLocal, requestHeaders }); if (response) { return response; } const res = await (0, ipx_1.handleRequest)({ url: `/${modifiers}/${cacheKey}`, headers: event.headers }, ipx); const body = typeof res.body === 'string' ? res.body : res.body.toString('base64'); res.headers.etag = responseEtag || (0, etag_1.default)(body); delete res.headers['Last-Modified']; if (requestEtag && requestEtag === res.headers.etag) { return { statusCode: 304, message: 'Not Modified' }; } return { statusCode: res.statusCode, message: res.statusMessage, headers: res.headers, isBase64Encoded: typeof res.body !== 'string', body }; }; return (0, functions_1.builder)(handler); } exports.createIPXHandler = createIPXHandler;
const User = require('../model/user'); const { signJwt } = require('../utils/jwt'); const signIn = async (req, res) => { let user; try { user = await User.findUserInfo(req.body.emailAddress); } catch { res.status(400); return res.json({ errorMessage: 'Invalid request, probably due to data type error or invalid email address' }); } const token = await signJwt({ userId: user.userId, capability: 'createProject' }); return res.json({ token }); }; module.exports = { signIn };
import React from 'react'; // import Button from '@material-ui/core/Button'; import Menu from '../../components/Menu'; import Steeper from '../../components/Steeper'; import './styles.css'; function Autotriagem() { return ( <div className="page-autotriagem"> <Menu /> <main className="page-autotriagem-content"> <div className="page-autotriagem-info"> <h1>Autotriagem</h1> <p className="description-autotriagem"> Forneça as informações abaixo de acordo com o que está sentindo. </p> </div> <div className="form-triagem"> <Steeper /> </div> </main> </div> ); } export default Autotriagem;
var http = require ('http'); var fs = require ('fs'); require ('./Core/Core.js'); require ('./Speaker.js'); require ('../js/Timer.js'); require ('./SpeakerFriend.js'); http.globalAgent.maxSockets = 15; Core.processGlobal(); require('../app2/Mindboost/MindboostOnboardingWelcomeText.js'); require('../HelpMan/HelpManDbExercises.js'); require('../HelpMan/HelpManDb.js'); require('../lang.js'); var phrases = []; SpeakerFriend.urls = { EN: 'http://voice2.mindboost.me/voice/translate_tts?ie=UTF-8&total=1&idx=0&client=t&pitch=-105&prev=input&q=%text%&tl=en', RU: 'http://voice2.mindboost.me/voice/translate_tts?ie=UTF-8&total=1&idx=0&client=t&pitch=-75&prev=input&q=%text%&tl=ru' }; HelpManDb.map(function(it) { var text; if(it._self.match(new RegExp(global.LANG, 'i'))) { if(it.first_text) { text = it.first_text; } else if(it.text) { text = it.text; } } if(!text) { return; } if(text.match(/%time/)) { [2,5,7,10,15,20,30].map(function(time) { FireRequest(new SpeakerUser_TokenizeRq({phrase: text.replace(/%time/, time)}), function(ps) { Array.prototype.push.apply(phrases, ps); }); }) } else { FireRequest(new SpeakerUser_TokenizeRq({phrase: text}), function(ps) { Array.prototype.push.apply(phrases, ps); }); } }); Object.keys(MindboostOnboardingWelcomeText).filter(function(it) { return it.match(new RegExp(global.LANG)) }).map(function(lang) { var text = MindboostOnboardingWelcomeText[lang]; if(text.match(/%time/)) { [2,5,7,10,15,20,30].map(function(time) { FireRequest(new SpeakerUser_TokenizeRq({phrase: text.replace(/%time/, time)}), function(ps) { Array.prototype.push.apply(phrases, ps); }); }) } else { FireRequest(new SpeakerUser_TokenizeRq({phrase: text}), function(ps) { Array.prototype.push.apply(phrases, ps); }); } }); fs.writeFile('prerender.js', "SpeakerFriend.prerender = {};\n"); prerender = {}; phrases.map(function(phrase) { (function load_phrase() { http.get(SpeakerFriend.urls[phrase.match(/[абвгдеёжзиклмнопрстуфхчшщыьъэюя]+/i) ? 'RU' : 'EN'].replace(/%text%/, encodeURIComponent(phrase.trim())), function(res) { var body = new Buffer(''); res.on('data', function(chunk) { body = Buffer.concat([body, chunk]); }); res.on('end', function() { console.log('loaded: ' + phrase); //console.log(body.toString().match(/fatal/i)); if(body.toString().match(/fatal/i)) { console.log('errorka found!', body); //fs.appendFile('prerender.js', 'SpeakerFriend.prerender[' + JSON.stringify(phrase) + '] = ' + JSON.stringify('data:audio/mpeg;utf-8,' + body.toString()) + ";\n") huihui(); } else { fs.appendFile('prerender.js', 'SpeakerFriend.prerender[' + JSON.stringify(phrase.trim()) + '] = ' + JSON.stringify('data:audio/mpeg;base64,' + body.toString('base64')) + ";\n") } }); }).on('error', function() { console.log('error loading ' + phrase + ' :( retrying'); load_phrase(); }) })(); });
/* eslint-env mocha */ import './polyfills.js'; import { FontAnalyzer } from '../../src/font-analyzer.js'; import { LineHeight } from '../../src/line-height.js'; import { FONTS, loadFonts } from './fonts-info.js'; describe('Unit: LineHeight', function() { this.timeout(4 * 60 * 1000); before((done) => { loadFonts(done); }); describe('Unit: calcLineHeight', () => { for (let name in FONTS) { it(`check ${name}`, () => { expect( LineHeight.calcLineHeight( 14, FontAnalyzer.getXHeight(name), FontAnalyzer.getAscHeight(name) ) ).to.be.within( FONTS[name].optimalLineHeight - 0.2, FONTS[name].optimalLineHeight + 0.2 ); }); } }); describe('Unit: calcFontSize', () => { for (let name in FONTS) { it(`check ${name}`, () => { expect( LineHeight.calcFontSize( 19, FontAnalyzer.getXHeight(name), FontAnalyzer.getAscHeight(name) ) ).to.be.within( FONTS[name].optimalFontSize - 0.2, FONTS[name].optimalFontSize + 0.2 ); }); } }); });
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvArtTrack = (props) => ( <SvgIcon {...props}> <path d="M22 13h-8v-2h8v2zm0-6h-8v2h8V7zm-8 10h8v-2h-8v2zm-2-8v6c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V9c0-1.1.9-2 2-2h6c1.1 0 2 .9 2 2zm-1.5 6l-2.25-3-1.75 2.26-1.25-1.51L3.5 15h7z"/> </SvgIcon> ); AvArtTrack = pure(AvArtTrack); AvArtTrack.displayName = 'AvArtTrack'; AvArtTrack.muiName = 'SvgIcon'; export default AvArtTrack;
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports["touch/player-gestures"]=t():e["touch/player-gestures"]=t()}(self,(function(){return function(){var e,t,n={620:function(e,t,n){"use strict";n.r(t),n.d(t,{setBrightness:function(){return s}});const s=(e,t)=>{let n=t;n<0&&(n=0),e.style.filter=`brightness(${n})`}},931:function(e,t,n){"use strict";let s;n.d(t,{q:function(){return s}}),function(e){e.Fast="高速",e.Medium="中速",e.Slow="低速"}(s||(s={}))},99:function(e,t,n){"use strict";n.r(t),n.d(t,{setProgress:function(){return s}});const s=(e,t)=>{let n=t;n>e.duration?n=e.duration:n<0&&(n=0),unsafeWindow.player.seek(n,e.paused)}},39:function(e,t,n){"use strict";n.r(t),n.d(t,{SwipeAction:function(){return a},Swiper:function(){return c}});var s=coreApis.settings,i=n(931);function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const o=(e,t)=>{const n=(e=>{let t=0,n=0,s=e;for(;s&&!Number.isNaN(s.offsetLeft)&&!Number.isNaN(s.offsetTop);)t+=s.offsetLeft-s.scrollLeft,n+=s.offsetTop-s.scrollTop,s=s.offsetParent;return{x:t,y:n}})(t);return{x:(e.touches[0].pageX-n.x)/t.clientWidth,y:(e.touches[0].pageY-n.y)/t.clientHeight,width:t.clientWidth,height:t.clientHeight}};class a extends EventTarget{constructor(e){super(),this.element=e,r(this,"minSwipeDistance",(0,s.getComponentSettings)("touchPlayerGestures").options.swiperDistance),r(this,"startPosition",null),r(this,"lastAction",null),e.addEventListener("touchstart",(()=>{this.dispatchEvent(new CustomEvent("start"))})),e.addEventListener("touchend",(()=>{this.dispatchEvent(new CustomEvent("end",{detail:this.lastAction})),this.lastAction=null}))}startAction(e,t,n){if("vertical"===e)if(this.startPosition.x<.5){const e=Math.round(200*(t-this.minSwipeDistance)/(1.5*n.height))/100;this.dispatchEvent(new CustomEvent("brightness",{detail:e})),this.lastAction={type:"brightness",brightness:e}}else{const e=Math.round(200*(t-this.minSwipeDistance)/(1.5*n.height))/100;this.dispatchEvent(new CustomEvent("volume",{detail:e})),this.lastAction={type:"volume",volume:e}}else if("horizontal"===e)if(n.y<1/3&&(n.x<.1||n.x>.9))this.dispatchEvent(new CustomEvent("cancel")),this.lastAction=null;else{let e=0;e=this.startPosition.y<1/3?.05:this.startPosition.y>=1/3&&this.startPosition.y<=2/3?.2:1;const n={.05:i.q.Slow,.2:i.q.Medium,1:i.q.Fast};if(t>0){const s=(t-this.minSwipeDistance)*e;this.dispatchEvent(new CustomEvent("progress",{detail:{mode:n[e],progress:s}})),this.lastAction={type:"progress",seconds:s}}else{const s=(t+this.minSwipeDistance)*e;this.dispatchEvent(new CustomEvent("progress",{detail:{mode:n[e],progress:s}})),this.lastAction={type:"progress",seconds:s}}}}}class c{constructor(e){r(this,"onTouchStart",null),r(this,"onTouchEnd",null),r(this,"direction",null),r(this,"action",void 0),r(this,"xDown",void 0),r(this,"yDown",void 0),this.action=new a(e),e.addEventListener("touchstart",(t=>{this.xDown=t.touches[0].clientX,this.yDown=t.touches[0].clientY,this.onTouchStart?.(t),this.action.startPosition=o(t,e)})),e.addEventListener("touchmove",(t=>{if(!this.xDown||!this.yDown||!t.cancelable)return;const n=t.touches[0].clientX,s=t.touches[0].clientY,i=o(t,e),r=this.xDown-n,a=this.yDown-s;this.direction?"vertical"===this.direction?this.action.startAction(this.direction,a,i):"horizontal"===this.direction&&this.action.startAction(this.direction,-r,i):this.direction=Math.abs(r)>Math.abs(a)?"horizontal":"vertical",t.preventDefault()}),{passive:!1}),e.addEventListener("touchend",(e=>{this.xDown=null,this.yDown=null,this.direction=null,this.onTouchEnd?.(e),this.action.startPosition=null}))}}},977:function(e,t,n){"use strict";n.r(t),n.d(t,{syncVolumeUI:function(){return s},setVolume:function(){return i}});const s=e=>{unsafeWindow.player?.volume(e)},i=async(e,t)=>{let n=t;n>1?n=1:n<0&&(n=0),e.volume=n}},777:function(e,t,n){var s=n(645)((function(e){return e[1]}));s.push([e.id,".gesture-preview {\n color: #fff;\n background-color: rgba(0, 0, 0, 0.8);\n font-size: 16px;\n border-radius: 8px;\n width: 100%;\n height: 100%;\n max-width: 400px;\n max-height: 150px;\n position: absolute;\n left: 50%;\n top: 50%;\n transform: translateX(-50%) translateY(-50%) scale(0.95);\n opacity: 0;\n transition: 0.2s ease-out;\n display: flex;\n flex-direction: column;\n z-index: 11;\n padding: 4px 6px;\n box-sizing: border-box;\n pointer-events: none;\n}\n.gesture-preview.opened {\n transform: translateX(-50%) translateY(-50%) scale(1);\n opacity: 1;\n}\n.gesture-preview-content {\n display: flex;\n align-items: center;\n grid-gap: 0;\n gap: 0;\n justify-content: space-between;\n flex: 1 0 auto;\n}\n.gesture-preview-content .brightness,\n.gesture-preview-content .volume {\n position: relative;\n flex: 0 0 auto;\n margin: 0 12px;\n}\n.gesture-preview-content .brightness .label,\n.gesture-preview-content .volume .label {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translateX(-50%) translateY(-50%);\n white-space: nowrap;\n display: flex;\n align-items: center;\n flex-direction: column;\n grid-gap: 0;\n gap: 0;\n}\n.gesture-preview-content .brightness .label .name,\n.gesture-preview-content .volume .label .name {\n color: #aaa;\n margin-bottom: 6px;\n}\n.gesture-preview-content .progress {\n display: flex;\n align-items: center;\n flex-direction: column;\n grid-gap: 0;\n gap: 0;\n flex: 1 0 auto;\n align-self: flex-end;\n}\n.gesture-preview-content .progress .videoshot {\n height: 70px;\n width: 120px;\n margin-bottom: 8px;\n border-radius: 4px;\n}\n.gesture-preview-content .progress .name {\n color: #aaa;\n padding: 4px 6px;\n margin-bottom: 6px;\n}\n.gesture-preview-content .progress .progress-label {\n margin-bottom: 12px;\n}\n.gesture-preview-content .progress .preview {\n display: flex;\n align-items: center;\n grid-gap: 0;\n gap: 0;\n margin-bottom: 6px;\n}\n.gesture-preview-content .progress .preview .diff {\n color: var(--theme-color);\n margin-right: 6px;\n}\n.gesture-preview-content .progress .preview .seek-mode {\n padding: 4px 6px;\n border-radius: 4px;\n background-color: rgba(136,136,136,0.26667);\n}",""]),e.exports=s},645:function(e){"use strict"; // eslint-disable-next-line func-names e.exports=function(e){var t=[];return t.toString=function(){return this.map((function(t){var n=e(t);return t[2]?"@media ".concat(t[2]," {").concat(n,"}"):n})).join("")}, // eslint-disable-next-line func-names t.i=function(e,n,s){"string"==typeof e&&( // eslint-disable-next-line no-param-reassign e=[[null,e,""]]);var i={};if(s)for(var r=0;r<this.length;r++){ // eslint-disable-next-line prefer-destructuring var o=this[r][0];null!=o&&(i[o]=!0)}for(var a=0;a<e.length;a++){var c=[].concat(e[a]);s&&i[c[0]]||(n&&(c[2]?c[2]="".concat(n," and ").concat(c[2]):c[2]=n),t.push(c))}},t}},379:function(e,t,n){"use strict";var s,i=function(){return void 0===s&&( // @see http://browserhacks.com/#hack-e71d8692f65334173fee715c222cb805 // @see https://github.com/webpack-contrib/style-loader/issues/177 s=Boolean(window&&document&&document.all&&!window.atob)),s},r=function(){var e={};return function(t){if(void 0===e[t]){var n=document.querySelector(t);if(window.HTMLIFrameElement&&n instanceof window.HTMLIFrameElement)try{n=n.contentDocument.head}catch(e){n=null}e[t]=n}return e[t]}}(),o=[];function a(e){for(var t=-1,n=0;n<o.length;n++)if(o[n].identifier===e){t=n;break}return t}function c(e,t){for(var n={},s=[],i=0;i<e.length;i++){var r=e[i],c=t.base?r[0]+t.base:r[0],l=n[c]||0,u="".concat(c," ").concat(l);n[c]=l+1;var p=a(u),d={css:r[1],media:r[2],sourceMap:r[3]};-1!==p?(o[p].references++,o[p].updater(d)):o.push({identifier:u,updater:g(d,t),references:1}),s.push(u)}return s}function l(e){var t=document.createElement("style"),s=e.attributes||{};if(void 0===s.nonce){var i=n.nc;i&&(s.nonce=i)}if(Object.keys(s).forEach((function(e){t.setAttribute(e,s[e])})),"function"==typeof e.insert)e.insert(t);else{var o=r(e.insert||"head");if(!o)throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");o.appendChild(t)}return t}var u,p=(u=[],function(e,t){return u[e]=t,u.filter(Boolean).join("\n")});function d(e,t,n,s){var i=n?"":s.media?"@media ".concat(s.media," {").concat(s.css,"}"):s.css;if(e.styleSheet)e.styleSheet.cssText=p(t,i);else{var r=document.createTextNode(i),o=e.childNodes;o[t]&&e.removeChild(o[t]),o.length?e.insertBefore(r,o[t]):e.appendChild(r)}}function h(e,t,n){var s=n.css,i=n.media,r=n.sourceMap;if(i?e.setAttribute("media",i):e.removeAttribute("media"),r&&"undefined"!=typeof btoa&&(s+="\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(r))))," */")),e.styleSheet)e.styleSheet.cssText=s;else{for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(document.createTextNode(s))}}var v=null,f=0;function g(e,t){var n,s,i;if(t.singleton){var r=f++;n=v||(v=l(t)),s=d.bind(null,n,r,!1),i=d.bind(null,n,r,!0)}else n=l(t),s=h.bind(null,n,t),i=function(){!function(e){if(null===e.parentNode)return!1;e.parentNode.removeChild(e)}(n)};return s(e),function(t){if(t){if(t.css===e.css&&t.media===e.media&&t.sourceMap===e.sourceMap)return;s(e=t)}else i()}}e.exports=function(e,t){(t=t||{}).singleton||"boolean"==typeof t.singleton||(t.singleton=i());var n=c(e=e||[],t);return function(e){if(e=e||[],"[object Array]"===Object.prototype.toString.call(e)){for(var s=0;s<n.length;s++){var i=a(n[s]);o[i].references--}for(var r=c(e,t),l=0;l<n.length;l++){var u=a(n[l]);0===o[u].references&&(o[u].updater(),o.splice(u,1))}n=r}}}},332:function(e,t,n){"use strict";n.r(t),n.d(t,{default:function(){return b}});var s=function(){var e=this,t=e.$createElement,n=e._self._c||t;return n("div",{staticClass:"gesture-preview",class:{opened:e.opened}},[n("div",{staticClass:"gesture-preview-content"},[n("div",{staticClass:"brightness"},[n("ProgressRing",{attrs:{size:100,progress:100*e.preview.brightness}}),e._v(" "),n("div",{staticClass:"label"},[n("div",{staticClass:"name"},[e._v("\n 亮度\n ")]),e._v(" "),n("div",{staticClass:"value"},[e._v("\n "+e._s(e._f("percent")(e.preview.brightness))+"\n ")])])],1),e._v(" "),n("div",{staticClass:"progress"},[n("div",{staticClass:"videoshot",style:e.videoshotStyle}),e._v(" "),n("div",{directives:[{name:"show",rawName:"v-show",value:null!==e.preview.progress,expression:"preview.progress !== null"}],staticClass:"preview"},[e.progressNaN?e._e():n("div",{staticClass:"diff"},[e._v("\n "+e._s(e._f("progressDiff")(e.preview.progress-e.store.progress))+"\n ")]),e._v(" "),n("div",{staticClass:"seek-mode"},[e._v("\n "+e._s(e.progressNaN?"取消调整":e.preview.seekMode)+"\n ")])]),e._v(" "),n("div",{directives:[{name:"show",rawName:"v-show",value:null===e.preview.progress,expression:"preview.progress === null"}],staticClass:"name"},[e._v("\n 进度\n ")]),e._v(" "),n("div",{staticClass:"progress-label"},[e._v("\n "+e._s(e._f("progress")(e.progressValid?e.preview.progress:e.store.progress))+"\n ")])]),e._v(" "),n("div",{staticClass:"volume"},[n("ProgressRing",{attrs:{size:100,progress:100*e.preview.volume}}),e._v(" "),n("div",{staticClass:"label"},[n("div",{staticClass:"name"},[e._v("\n 音量\n ")]),e._v(" "),n("div",{staticClass:"value"},[e._v("\n "+e._s(e._f("percent")(e.preview.volume))+"\n ")])])],1)]),e._v(" "),n("div",{staticClass:"progress-bar"},[n("ProgressBar",{attrs:{progress:e.progressValid?e.preview.progress:e.store.progress,max:e.video.duration}})],1)])};s._withStripped=!0;var i=coreApis.ui,r=n(109),o=coreApis.utils.formatters,a=n(931);function c(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class l{constructor(){c(this,"aid",unsafeWindow.aid),c(this,"cid",unsafeWindow.cid),c(this,"viewWidth",120),c(this,"viewHeight",70),c(this,"cidData",null),c(this,"blocked",!1),c(this,"workingPromise",null)}async getVideoshot(e){if(!this.aid||!this.cid||this.blocked)return null;if(this.workingPromise)return this.workingPromise;const{getJson:t}=await Promise.resolve().then(n.t.bind(n,663,23));if(!this.cidData){this.workingPromise=t(`https://api.bilibili.com/x/player/videoshot?aid=${this.aid}&cid=${this.cid}&index=1`);const n=await this.workingPromise;return this.workingPromise=null,-412===n.code?(this.blocked=!0,null):(this.cidData=n.data,this.getVideoshot(e))}const s=this.cidData,i=s.index;let r=1;for(let t=i.length-1;t>0;t--)if(e>=i[t]){r=t;break}const o=s.image;if(null===o)return null;const a=s.img_x_len??10,c=s.img_y_len??10,l=a*this.viewWidth,u=c*this.viewHeight,p=this.viewWidth,d=this.viewHeight,h=-(r-1)%100%a*p,v=-Math.floor((r-1)%100/c)*d;return{backgroundImage:`url(${o[Math.floor(r/100)]})`,backgroundPosition:`${h}px ${v}px`,backgroundSize:`${l}px ${u}px`}}}var u=n(977);const p=(e,t,n=1,s=0)=>{const i=e+t;return i>n?n:i<s?s:i};var d=Vue.extend({components:{ProgressRing:i.ProgressRing,ProgressBar:i.ProgressBar},filters:{percent:o.formatPercent,progress:e=>(0,o.formatDuration)(e,1),progressDiff:e=>`${e>0?"+":"-"}${(e=>{e=Math.abs(e);const t=Math.floor(e/3600),n=Math.floor((e-3600*t)/60),s=e-3600*t-60*n;let i=`${(0,r.fixed)(s)}秒`;return n>0&&(i=`${n}分${i}`),t>0&&(i=`${t}时${i}`),i})(e)}`},data(){const e={progress:0,brightness:1,volume:.66};return{opened:!1,video:dq("video"),videoshot:new l,videoshotStyle:{},store:e,preview:{...e,progress:null,seekMode:a.q.Fast}}},computed:{progressNaN(){return Number.isNaN(this.preview.progress)},progressNull(){return null===this.preview.progress},progressValid(){return!this.progressNaN&&!this.progressNull}},methods:{sync(){const e=dq("video");this.video=e,this.store.volume=e.volume,this.store.progress=e.currentTime,this.store.brightness=(()=>{if(e.style.filter){const t=e.style.filter.match(/brightness\((.+)\)/);return t?parseFloat(t[1]):1}return 1})(),this.preview={...this.preview,...this.store,progress:null}},startPreview({brightness:e,volume:t,progress:n}){if(this.opened=!0,void 0!==n){this.preview.progress=p(this.store.progress,n,this.video.duration);this.videoshot.getVideoshot(this.preview.progress).then((e=>{this.videoshotStyle=e}))}else void 0!==e?this.preview.brightness=p(this.store.brightness,e,1/0):void 0!==t&&(this.preview.volume=p(this.store.volume,t)),this.apply({brightness:e,volume:t})},cancelPreview(){this.preview.progress=NaN},endPreview(){unsafeWindow.touchGestureDebug||(this.opened=!1),this.store.volume!==this.preview.volume&&(0,u.syncVolumeUI)(this.preview.volume),Number.isNaN(this.preview.progress)?this.preview.progress=null:this.store.progress!==this.preview.progress&&null!==this.preview.progress&&this.apply({progress:this.preview.progress})},async apply({brightness:e,volume:t,progress:s}){const i=this.video;if(i)if(void 0!==e){const{setBrightness:e}=await Promise.resolve().then(n.bind(n,620));e(i,this.preview.brightness)}else if(void 0!==t){const{setVolume:e}=await Promise.resolve().then(n.bind(n,977));e(i,this.preview.volume)}else if(void 0!==s){const{setProgress:e}=await Promise.resolve().then(n.bind(n,99));e(i,s)}}}}),h=n(379),v=n.n(h),f=n(777),g=n.n(f),m={insert:"head",singleton:!1};v()(g(),m),g().locals;var w=function(e,t,n,s,i,r,o,a){var c,l="function"==typeof e?e.options:e;if(t&&(l.render=t,l.staticRenderFns=n,l._compiled=!0),s&&(l.functional=!0),r&&(l._scopeId="data-v-"+r),o?(c=function(e){(e=e||this.$vnode&&this.$vnode.ssrContext||this.parent&&this.parent.$vnode&&this.parent.$vnode.ssrContext)||"undefined"==typeof __VUE_SSR_CONTEXT__||(e=__VUE_SSR_CONTEXT__),i&&i.call(this,e),e&&e._registeredComponents&&e._registeredComponents.add(o)},l._ssrRegister=c):i&&(c=a?function(){i.call(this,(l.functional?this.parent:this).$root.$options.shadowRoot)}:i),c)if(l.functional){l._injectStyles=c;var u=l.render;l.render=function(e,t){return c.call(t),u(e,t)}}else{var p=l.beforeCreate;l.beforeCreate=p?[].concat(p,c):[c]}return{exports:e,options:l}}(d,s,[],!1,null,null,null);w.options.__file="registry/lib/components/touch/player-gestures/GesturePreview.vue";var b=w.exports},663:function(e){"use strict";e.exports=coreApis.ajax},156:function(e){"use strict";e.exports=coreApis.observer},109:function(e){"use strict";e.exports=coreApis.utils}},s={};function i(e){var t=s[e];if(void 0!==t)return t.exports;var r=s[e]={id:e,exports:{}};return n[e](r,r.exports,i),r.exports}i.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return i.d(t,{a:t}),t},t=Object.getPrototypeOf?function(e){return Object.getPrototypeOf(e)}:function(e){return e.__proto__},i.t=function(n,s){if(1&s&&(n=this(n)),8&s)return n;if("object"==typeof n&&n){if(4&s&&n.__esModule)return n;if(16&s&&"function"==typeof n.then)return n}var r=Object.create(null);i.r(r);var o={};e=e||[null,t({}),t([]),t(t)];for(var a=2&s&&n;"object"==typeof a&&!~e.indexOf(a);a=t(a))Object.getOwnPropertyNames(a).forEach((function(e){o[e]=function(){return n[e]}}));return o.default=function(){return n},i.d(r,o),r},i.d=function(e,t){for(var n in t)i.o(t,n)&&!i.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},i.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},i.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var r={};return function(){"use strict";i.d(r,{component:function(){return n}});var e=coreApis.utils.urls,t=coreApis.componentApis.video.playerAgent;const n={name:"touchPlayerGestures",displayName:"播放器触摸手势",enabledByDefault:navigator.maxTouchPoints>0,tags:[componentsTags.touch],description:{"zh-CN":"为播放器启用触摸手势支持:\n- 左右滑动可调整进度\n- 上下滑动可调整音量\n- 进度调整可在左上角和右上角取消\n- 进度调整时在不同位置滑动, 可以使用3档不同的灵敏度."},entry:async()=>{const{videoChange:e}=await Promise.resolve().then(i.t.bind(i,156,23));e((async()=>{if(!await t.playerAgent.query.video.element())return;let e;if(!dq(".gesture-preview")){const n=await Promise.resolve().then(i.bind(i,332)),{mountVueComponent:s}=await Promise.resolve().then(i.t.bind(i,109,23));e=s(n),t.playerAgent.query.video.subtitle.sync()?.insertAdjacentElement("beforebegin",e.$el)}const{Swiper:n}=await Promise.resolve().then(i.bind(i,39)),s=new n(t.playerAgent.query.video.container.sync());s.action.addEventListener("start",(()=>{e.sync()})),s.action.addEventListener("cancel",(()=>{e.cancelPreview()})),s.action.addEventListener("end",(()=>{e.endPreview()})),["volume","brightness"].forEach((t=>{s.action.addEventListener(t,(n=>{e.startPreview({[t]:n.detail})}))})),s.action.addEventListener("progress",(t=>{const{progress:n,mode:s}=t.detail;e.preview.seekMode=s,e.startPreview({progress:n})}))}))},urlInclude:e.playerUrls,options:{swiperDistance:{displayName:"手势触发最小距离",defaultValue:10,hidden:!0}},commitHash:"115c9d61e8c64d705cd1287b4408e1e329e968d4"}}(),r=r.component}()}));
const usuario = { nome: 'Hallan', idade: 33, endereco: { cidade: 'Ubatuba', estado: 'SP' } }; // console.log(usuario); // console.log(usuario.nome); // console.log(usuario.endereco.cidade); const { nome, idade, endereco: { cidade, estado } } = usuario; console.log(nome); console.log(idade); console.log(cidade); console.log(estado); function mostraNome({ nome, endereco: { cidade } }) { console.log(nome); console.log(cidade); } mostraNome(usuario);
module.exports={A:{A:{"1":"A B","2":"P F D E rB"},B:{"1":"C I J K L M N v s Q VB GB"},C:{"1":"0 1 2 3 4 5 6 7 8 9 G T P F D E A B C I J K L M N U V W X Y Z a b c d e f g h i j k l m n o p q r R t u O w x y z SB WB AB BB CB DB EB H FB MB NB OB PB QB RB IB TB UB v s Q kB","2":"uB LB jB iB"},D:{"1":"0 1 2 3 4 5 6 7 8 9 T P F D E A B C I J K L M N U V W X Y Z a b c d e f g h i j k l m n o p q r R t u O w x y z SB WB AB BB CB DB EB H FB MB NB OB PB QB RB IB TB UB v s Q VB GB dB aB 1B bB","2":"G"},E:{"1":"P F D E A B C I J fB gB hB XB S HB lB mB","2":"G cB YB","4":"T eB"},F:{"1":"0 1 2 3 4 5 6 7 8 9 C K L M N U V W X Y Z a b c d e f g h i j k l m n o p q r R t u O w x y z AB BB CB DB EB H FB KB sB HB","2":"E B nB oB pB qB S"},G:{"1":"D vB wB xB yB zB 0B ZB 2B 3B 4B 5B 6B 7B 8B 9B AC BC","2":"YB tB","4":"JB"},H:{"2":"CC"},I:{"1":"Q EC FC JB HC IC","2":"LB G DC GC"},J:{"1":"F A"},K:{"1":"C O S KB HB","2":"A B"},L:{"1":"GB"},M:{"1":"H"},N:{"1":"A B"},O:{"1":"JC"},P:{"1":"G KC LC MC NC OC XB PC QC"},Q:{"1":"RC"},R:{"1":"SC"},S:{"1":"TC"}},B:1,C:"Session history management"};
const { canModifyQueue, LOCALE } = require("../util/MusicaUtils.js"); const i18n = require("i18n"); i18n.setLocale(LOCALE); module.exports = { name: "skip", aliases: ["s"], description: i18n.__("skip.description"), execute(message) { const queue = message.client.queue.get(message.guild.id); if (!queue) return message.reply(i18n.__("skip.errorNotQueue")).catch(console.error); if (!canModifyQueue(message.member)) return i18n.__("common.errorNotChannel"); queue.playing = true; queue.connection.dispatcher.end(); queue.textChannel.send(i18n.__mf("skip.result", { author: message.author })).catch(console.error); } };
/* Table Of Content 1. Bootstrap 2. Ajaxchimp 3. downCount 4. 3D Hover */ /*! * Bootstrap v3.3.7 (http://getbootstrap.com) * Copyright 2011-2016 Twitter, Inc. * Licensed under the MIT license */ if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");+function(a){"use strict";var b=a.fn.jquery.split(" ")[0].split(".");if(b[0]<2&&b[1]<9||1==b[0]&&9==b[1]&&b[2]<1||b[0]>3)throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher, but lower than version 4")}(jQuery),+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one("bsTransitionEnd",function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b(),a.support.transition&&(a.event.special.bsTransitionEnd={bindType:a.support.transition.end,delegateType:a.support.transition.end,handle:function(b){if(a(b.target).is(this))return b.handleObj.handler.apply(this,arguments)}})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var c=a(this),e=c.data("bs.alert");e||c.data("bs.alert",e=new d(this)),"string"==typeof b&&e[b].call(c)})}var c='[data-dismiss="alert"]',d=function(b){a(b).on("click",c,this.close)};d.VERSION="3.3.7",d.TRANSITION_DURATION=150,d.prototype.close=function(b){function c(){g.detach().trigger("closed.bs.alert").remove()}var e=a(this),f=e.attr("data-target");f||(f=e.attr("href"),f=f&&f.replace(/.*(?=#[^\s]*$)/,""));var g=a("#"===f?[]:f);b&&b.preventDefault(),g.length||(g=e.closest(".alert")),g.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(g.removeClass("in"),a.support.transition&&g.hasClass("fade")?g.one("bsTransitionEnd",c).emulateTransitionEnd(d.TRANSITION_DURATION):c())};var e=a.fn.alert;a.fn.alert=b,a.fn.alert.Constructor=d,a.fn.alert.noConflict=function(){return a.fn.alert=e,this},a(document).on("click.bs.alert.data-api",c,d.prototype.close)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof b&&b;e||d.data("bs.button",e=new c(this,f)),"toggle"==b?e.toggle():b&&e.setState(b)})}var c=function(b,d){this.$element=a(b),this.options=a.extend({},c.DEFAULTS,d),this.isLoading=!1};c.VERSION="3.3.7",c.DEFAULTS={loadingText:"loading..."},c.prototype.setState=function(b){var c="disabled",d=this.$element,e=d.is("input")?"val":"html",f=d.data();b+="Text",null==f.resetText&&d.data("resetText",d[e]()),setTimeout(a.proxy(function(){d[e](null==f[b]?this.options[b]:f[b]),"loadingText"==b?(this.isLoading=!0,d.addClass(c).attr(c,c).prop(c,!0)):this.isLoading&&(this.isLoading=!1,d.removeClass(c).removeAttr(c).prop(c,!1))},this),0)},c.prototype.toggle=function(){var a=!0,b=this.$element.closest('[data-toggle="buttons"]');if(b.length){var c=this.$element.find("input");"radio"==c.prop("type")?(c.prop("checked")&&(a=!1),b.find(".active").removeClass("active"),this.$element.addClass("active")):"checkbox"==c.prop("type")&&(c.prop("checked")!==this.$element.hasClass("active")&&(a=!1),this.$element.toggleClass("active")),c.prop("checked",this.$element.hasClass("active")),a&&c.trigger("change")}else this.$element.attr("aria-pressed",!this.$element.hasClass("active")),this.$element.toggleClass("active")};var d=a.fn.button;a.fn.button=b,a.fn.button.Constructor=c,a.fn.button.noConflict=function(){return a.fn.button=d,this},a(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(c){var d=a(c.target).closest(".btn");b.call(d,"toggle"),a(c.target).is('input[type="radio"], input[type="checkbox"]')||(c.preventDefault(),d.is("input,button")?d.trigger("focus"):d.find("input:visible,button:visible").first().trigger("focus"))}).on("focus.bs.button.data-api blur.bs.button.data-api",'[data-toggle^="button"]',function(b){a(b.target).closest(".btn").toggleClass("focus",/^focus(in)?$/.test(b.type))})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b),g="string"==typeof b?b:f.slide;e||d.data("bs.carousel",e=new c(this,f)),"number"==typeof b?e.to(b):g?e[g]():f.interval&&e.pause().cycle()})}var c=function(b,c){this.$element=a(b),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=null,this.sliding=null,this.interval=null,this.$active=null,this.$items=null,this.options.keyboard&&this.$element.on("keydown.bs.carousel",a.proxy(this.keydown,this)),"hover"==this.options.pause&&!("ontouchstart"in document.documentElement)&&this.$element.on("mouseenter.bs.carousel",a.proxy(this.pause,this)).on("mouseleave.bs.carousel",a.proxy(this.cycle,this))};c.VERSION="3.3.7",c.TRANSITION_DURATION=600,c.DEFAULTS={interval:5e3,pause:"hover",wrap:!0,keyboard:!0},c.prototype.keydown=function(a){if(!/input|textarea/i.test(a.target.tagName)){switch(a.which){case 37:this.prev();break;case 39:this.next();break;default:return}a.preventDefault()}},c.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},c.prototype.getItemIndex=function(a){return this.$items=a.parent().children(".item"),this.$items.index(a||this.$active)},c.prototype.getItemForDirection=function(a,b){var c=this.getItemIndex(b),d="prev"==a&&0===c||"next"==a&&c==this.$items.length-1;if(d&&!this.options.wrap)return b;var e="prev"==a?-1:1,f=(c+e)%this.$items.length;return this.$items.eq(f)},c.prototype.to=function(a){var b=this,c=this.getItemIndex(this.$active=this.$element.find(".item.active"));if(!(a>this.$items.length-1||a<0))return this.sliding?this.$element.one("slid.bs.carousel",function(){b.to(a)}):c==a?this.pause().cycle():this.slide(a>c?"next":"prev",this.$items.eq(a))},c.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},c.prototype.next=function(){if(!this.sliding)return this.slide("next")},c.prototype.prev=function(){if(!this.sliding)return this.slide("prev")},c.prototype.slide=function(b,d){var e=this.$element.find(".item.active"),f=d||this.getItemForDirection(b,e),g=this.interval,h="next"==b?"left":"right",i=this;if(f.hasClass("active"))return this.sliding=!1;var j=f[0],k=a.Event("slide.bs.carousel",{relatedTarget:j,direction:h});if(this.$element.trigger(k),!k.isDefaultPrevented()){if(this.sliding=!0,g&&this.pause(),this.$indicators.length){this.$indicators.find(".active").removeClass("active");var l=a(this.$indicators.children()[this.getItemIndex(f)]);l&&l.addClass("active")}var m=a.Event("slid.bs.carousel",{relatedTarget:j,direction:h});return a.support.transition&&this.$element.hasClass("slide")?(f.addClass(b),f[0].offsetWidth,e.addClass(h),f.addClass(h),e.one("bsTransitionEnd",function(){f.removeClass([b,h].join(" ")).addClass("active"),e.removeClass(["active",h].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger(m)},0)}).emulateTransitionEnd(c.TRANSITION_DURATION)):(e.removeClass("active"),f.addClass("active"),this.sliding=!1,this.$element.trigger(m)),g&&this.cycle(),this}};var d=a.fn.carousel;a.fn.carousel=b,a.fn.carousel.Constructor=c,a.fn.carousel.noConflict=function(){return a.fn.carousel=d,this};var e=function(c){var d,e=a(this),f=a(e.attr("data-target")||(d=e.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""));if(f.hasClass("carousel")){var g=a.extend({},f.data(),e.data()),h=e.attr("data-slide-to");h&&(g.interval=!1),b.call(f,g),h&&f.data("bs.carousel").to(h),c.preventDefault()}};a(document).on("click.bs.carousel.data-api","[data-slide]",e).on("click.bs.carousel.data-api","[data-slide-to]",e),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var c=a(this);b.call(c,c.data())})})}(jQuery),+function(a){"use strict";function b(b){var c,d=b.attr("data-target")||(c=b.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,"");return a(d)}function c(b){return this.each(function(){var c=a(this),e=c.data("bs.collapse"),f=a.extend({},d.DEFAULTS,c.data(),"object"==typeof b&&b);!e&&f.toggle&&/show|hide/.test(b)&&(f.toggle=!1),e||c.data("bs.collapse",e=new d(this,f)),"string"==typeof b&&e[b]()})}var d=function(b,c){this.$element=a(b),this.options=a.extend({},d.DEFAULTS,c),this.$trigger=a('[data-toggle="collapse"][href="#'+b.id+'"],[data-toggle="collapse"][data-target="#'+b.id+'"]'),this.transitioning=null,this.options.parent?this.$parent=this.getParent():this.addAriaAndCollapsedClass(this.$element,this.$trigger),this.options.toggle&&this.toggle()};d.VERSION="3.3.7",d.TRANSITION_DURATION=350,d.DEFAULTS={toggle:!0},d.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},d.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var b,e=this.$parent&&this.$parent.children(".panel").children(".in, .collapsing");if(!(e&&e.length&&(b=e.data("bs.collapse"),b&&b.transitioning))){var f=a.Event("show.bs.collapse");if(this.$element.trigger(f),!f.isDefaultPrevented()){e&&e.length&&(c.call(e,"hide"),b||e.data("bs.collapse",null));var g=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[g](0).attr("aria-expanded",!0),this.$trigger.removeClass("collapsed").attr("aria-expanded",!0),this.transitioning=1;var h=function(){this.$element.removeClass("collapsing").addClass("collapse in")[g](""),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return h.call(this);var i=a.camelCase(["scroll",g].join("-"));this.$element.one("bsTransitionEnd",a.proxy(h,this)).emulateTransitionEnd(d.TRANSITION_DURATION)[g](this.$element[0][i])}}}},d.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse in").attr("aria-expanded",!1),this.$trigger.addClass("collapsed").attr("aria-expanded",!1),this.transitioning=1;var e=function(){this.transitioning=0,this.$element.removeClass("collapsing").addClass("collapse").trigger("hidden.bs.collapse")};return a.support.transition?void this.$element[c](0).one("bsTransitionEnd",a.proxy(e,this)).emulateTransitionEnd(d.TRANSITION_DURATION):e.call(this)}}},d.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()},d.prototype.getParent=function(){return a(this.options.parent).find('[data-toggle="collapse"][data-parent="'+this.options.parent+'"]').each(a.proxy(function(c,d){var e=a(d);this.addAriaAndCollapsedClass(b(e),e)},this)).end()},d.prototype.addAriaAndCollapsedClass=function(a,b){var c=a.hasClass("in");a.attr("aria-expanded",c),b.toggleClass("collapsed",!c).attr("aria-expanded",c)};var e=a.fn.collapse;a.fn.collapse=c,a.fn.collapse.Constructor=d,a.fn.collapse.noConflict=function(){return a.fn.collapse=e,this},a(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(d){var e=a(this);e.attr("data-target")||d.preventDefault();var f=b(e),g=f.data("bs.collapse"),h=g?"toggle":e.data();c.call(f,h)})}(jQuery),+function(a){"use strict";function b(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#[A-Za-z]/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}function c(c){c&&3===c.which||(a(e).remove(),a(f).each(function(){var d=a(this),e=b(d),f={relatedTarget:this};e.hasClass("open")&&(c&&"click"==c.type&&/input|textarea/i.test(c.target.tagName)&&a.contains(e[0],c.target)||(e.trigger(c=a.Event("hide.bs.dropdown",f)),c.isDefaultPrevented()||(d.attr("aria-expanded","false"),e.removeClass("open").trigger(a.Event("hidden.bs.dropdown",f)))))}))}function d(b){return this.each(function(){var c=a(this),d=c.data("bs.dropdown");d||c.data("bs.dropdown",d=new g(this)),"string"==typeof b&&d[b].call(c)})}var e=".dropdown-backdrop",f='[data-toggle="dropdown"]',g=function(b){a(b).on("click.bs.dropdown",this.toggle)};g.VERSION="3.3.7",g.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=b(e),g=f.hasClass("open");if(c(),!g){"ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a(document.createElement("div")).addClass("dropdown-backdrop").insertAfter(a(this)).on("click",c);var h={relatedTarget:this};if(f.trigger(d=a.Event("show.bs.dropdown",h)),d.isDefaultPrevented())return;e.trigger("focus").attr("aria-expanded","true"),f.toggleClass("open").trigger(a.Event("shown.bs.dropdown",h))}return!1}},g.prototype.keydown=function(c){if(/(38|40|27|32)/.test(c.which)&&!/input|textarea/i.test(c.target.tagName)){var d=a(this);if(c.preventDefault(),c.stopPropagation(),!d.is(".disabled, :disabled")){var e=b(d),g=e.hasClass("open");if(!g&&27!=c.which||g&&27==c.which)return 27==c.which&&e.find(f).trigger("focus"),d.trigger("click");var h=" li:not(.disabled):visible a",i=e.find(".dropdown-menu"+h);if(i.length){var j=i.index(c.target);38==c.which&&j>0&&j--,40==c.which&&j<i.length-1&&j++,~j||(j=0),i.eq(j).trigger("focus")}}}};var h=a.fn.dropdown;a.fn.dropdown=d,a.fn.dropdown.Constructor=g,a.fn.dropdown.noConflict=function(){return a.fn.dropdown=h,this},a(document).on("click.bs.dropdown.data-api",c).on("click.bs.dropdown.data-api",".dropdown form",function(a){a.stopPropagation()}).on("click.bs.dropdown.data-api",f,g.prototype.toggle).on("keydown.bs.dropdown.data-api",f,g.prototype.keydown).on("keydown.bs.dropdown.data-api",".dropdown-menu",g.prototype.keydown)}(jQuery),+function(a){"use strict";function b(b,d){return this.each(function(){var e=a(this),f=e.data("bs.modal"),g=a.extend({},c.DEFAULTS,e.data(),"object"==typeof b&&b);f||e.data("bs.modal",f=new c(this,g)),"string"==typeof b?f[b](d):g.show&&f.show(d)})}var c=function(b,c){this.options=c,this.$body=a(document.body),this.$element=a(b),this.$dialog=this.$element.find(".modal-dialog"),this.$backdrop=null,this.isShown=null,this.originalBodyPad=null,this.scrollbarWidth=0,this.ignoreBackdropClick=!1,this.options.remote&&this.$element.find(".modal-content").load(this.options.remote,a.proxy(function(){this.$element.trigger("loaded.bs.modal")},this))};c.VERSION="3.3.7",c.TRANSITION_DURATION=300,c.BACKDROP_TRANSITION_DURATION=150,c.DEFAULTS={backdrop:!0,keyboard:!0,show:!0},c.prototype.toggle=function(a){return this.isShown?this.hide():this.show(a)},c.prototype.show=function(b){var d=this,e=a.Event("show.bs.modal",{relatedTarget:b});this.$element.trigger(e),this.isShown||e.isDefaultPrevented()||(this.isShown=!0,this.checkScrollbar(),this.setScrollbar(),this.$body.addClass("modal-open"),this.escape(),this.resize(),this.$element.on("click.dismiss.bs.modal",'[data-dismiss="modal"]',a.proxy(this.hide,this)),this.$dialog.on("mousedown.dismiss.bs.modal",function(){d.$element.one("mouseup.dismiss.bs.modal",function(b){a(b.target).is(d.$element)&&(d.ignoreBackdropClick=!0)})}),this.backdrop(function(){var e=a.support.transition&&d.$element.hasClass("fade");d.$element.parent().length||d.$element.appendTo(d.$body),d.$element.show().scrollTop(0),d.adjustDialog(),e&&d.$element[0].offsetWidth,d.$element.addClass("in"),d.enforceFocus();var f=a.Event("shown.bs.modal",{relatedTarget:b});e?d.$dialog.one("bsTransitionEnd",function(){d.$element.trigger("focus").trigger(f)}).emulateTransitionEnd(c.TRANSITION_DURATION):d.$element.trigger("focus").trigger(f)}))},c.prototype.hide=function(b){b&&b.preventDefault(),b=a.Event("hide.bs.modal"),this.$element.trigger(b),this.isShown&&!b.isDefaultPrevented()&&(this.isShown=!1,this.escape(),this.resize(),a(document).off("focusin.bs.modal"),this.$element.removeClass("in").off("click.dismiss.bs.modal").off("mouseup.dismiss.bs.modal"),this.$dialog.off("mousedown.dismiss.bs.modal"),a.support.transition&&this.$element.hasClass("fade")?this.$element.one("bsTransitionEnd",a.proxy(this.hideModal,this)).emulateTransitionEnd(c.TRANSITION_DURATION):this.hideModal())},c.prototype.enforceFocus=function(){a(document).off("focusin.bs.modal").on("focusin.bs.modal",a.proxy(function(a){document===a.target||this.$element[0]===a.target||this.$element.has(a.target).length||this.$element.trigger("focus")},this))},c.prototype.escape=function(){this.isShown&&this.options.keyboard?this.$element.on("keydown.dismiss.bs.modal",a.proxy(function(a){27==a.which&&this.hide()},this)):this.isShown||this.$element.off("keydown.dismiss.bs.modal")},c.prototype.resize=function(){this.isShown?a(window).on("resize.bs.modal",a.proxy(this.handleUpdate,this)):a(window).off("resize.bs.modal")},c.prototype.hideModal=function(){var a=this;this.$element.hide(),this.backdrop(function(){a.$body.removeClass("modal-open"),a.resetAdjustments(),a.resetScrollbar(),a.$element.trigger("hidden.bs.modal")})},c.prototype.removeBackdrop=function(){this.$backdrop&&this.$backdrop.remove(),this.$backdrop=null},c.prototype.backdrop=function(b){var d=this,e=this.$element.hasClass("fade")?"fade":"";if(this.isShown&&this.options.backdrop){var f=a.support.transition&&e;if(this.$backdrop=a(document.createElement("div")).addClass("modal-backdrop "+e).appendTo(this.$body),this.$element.on("click.dismiss.bs.modal",a.proxy(function(a){return this.ignoreBackdropClick?void(this.ignoreBackdropClick=!1):void(a.target===a.currentTarget&&("static"==this.options.backdrop?this.$element[0].focus():this.hide()))},this)),f&&this.$backdrop[0].offsetWidth,this.$backdrop.addClass("in"),!b)return;f?this.$backdrop.one("bsTransitionEnd",b).emulateTransitionEnd(c.BACKDROP_TRANSITION_DURATION):b()}else if(!this.isShown&&this.$backdrop){this.$backdrop.removeClass("in");var g=function(){d.removeBackdrop(),b&&b()};a.support.transition&&this.$element.hasClass("fade")?this.$backdrop.one("bsTransitionEnd",g).emulateTransitionEnd(c.BACKDROP_TRANSITION_DURATION):g()}else b&&b()},c.prototype.handleUpdate=function(){this.adjustDialog()},c.prototype.adjustDialog=function(){var a=this.$element[0].scrollHeight>document.documentElement.clientHeight;this.$element.css({paddingLeft:!this.bodyIsOverflowing&&a?this.scrollbarWidth:"",paddingRight:this.bodyIsOverflowing&&!a?this.scrollbarWidth:""})},c.prototype.resetAdjustments=function(){this.$element.css({paddingLeft:"",paddingRight:""})},c.prototype.checkScrollbar=function(){var a=window.innerWidth;if(!a){var b=document.documentElement.getBoundingClientRect();a=b.right-Math.abs(b.left)}this.bodyIsOverflowing=document.body.clientWidth<a,this.scrollbarWidth=this.measureScrollbar()},c.prototype.setScrollbar=function(){var a=parseInt(this.$body.css("padding-right")||0,10);this.originalBodyPad=document.body.style.paddingRight||"",this.bodyIsOverflowing&&this.$body.css("padding-right",a+this.scrollbarWidth)},c.prototype.resetScrollbar=function(){this.$body.css("padding-right",this.originalBodyPad)},c.prototype.measureScrollbar=function(){var a=document.createElement("div");a.className="modal-scrollbar-measure",this.$body.append(a);var b=a.offsetWidth-a.clientWidth;return this.$body[0].removeChild(a),b};var d=a.fn.modal;a.fn.modal=b,a.fn.modal.Constructor=c,a.fn.modal.noConflict=function(){return a.fn.modal=d,this},a(document).on("click.bs.modal.data-api",'[data-toggle="modal"]',function(c){var d=a(this),e=d.attr("href"),f=a(d.attr("data-target")||e&&e.replace(/.*(?=#[^\s]+$)/,"")),g=f.data("bs.modal")?"toggle":a.extend({remote:!/#/.test(e)&&e},f.data(),d.data());d.is("a")&&c.preventDefault(),f.one("show.bs.modal",function(a){a.isDefaultPrevented()||f.one("hidden.bs.modal",function(){d.is(":visible")&&d.trigger("focus")})}),b.call(f,g,this)})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.tooltip"),f="object"==typeof b&&b;!e&&/destroy|hide/.test(b)||(e||d.data("bs.tooltip",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.type=null,this.options=null,this.enabled=null,this.timeout=null,this.hoverState=null,this.$element=null,this.inState=null,this.init("tooltip",a,b)};c.VERSION="3.3.7",c.TRANSITION_DURATION=150,c.DEFAULTS={animation:!0,placement:"top",selector:!1,template:'<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},c.prototype.init=function(b,c,d){if(this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.$viewport=this.options.viewport&&a(a.isFunction(this.options.viewport)?this.options.viewport.call(this,this.$element):this.options.viewport.selector||this.options.viewport),this.inState={click:!1,hover:!1,focus:!1},this.$element[0]instanceof document.constructor&&!this.options.selector)throw new Error("`selector` option must be specified when initializing "+this.type+" on the window.document object!");for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focusin",i="hover"==g?"mouseleave":"focusout";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&"number"==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},c.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},c.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusin"==b.type?"focus":"hover"]=!0),c.tip().hasClass("in")||"in"==c.hoverState?void(c.hoverState="in"):(clearTimeout(c.timeout),c.hoverState="in",c.options.delay&&c.options.delay.show?void(c.timeout=setTimeout(function(){"in"==c.hoverState&&c.show()},c.options.delay.show)):c.show())},c.prototype.isInStateTrue=function(){for(var a in this.inState)if(this.inState[a])return!0;return!1},c.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);if(c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusout"==b.type?"focus":"hover"]=!1),!c.isInStateTrue())return clearTimeout(c.timeout),c.hoverState="out",c.options.delay&&c.options.delay.hide?void(c.timeout=setTimeout(function(){"out"==c.hoverState&&c.hide()},c.options.delay.hide)):c.hide()},c.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(b);var d=a.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]);if(b.isDefaultPrevented()||!d)return;var e=this,f=this.tip(),g=this.getUID(this.type);this.setContent(),f.attr("id",g),this.$element.attr("aria-describedby",g),this.options.animation&&f.addClass("fade");var h="function"==typeof this.options.placement?this.options.placement.call(this,f[0],this.$element[0]):this.options.placement,i=/\s?auto?\s?/i,j=i.test(h);j&&(h=h.replace(i,"")||"top"),f.detach().css({top:0,left:0,display:"block"}).addClass(h).data("bs."+this.type,this),this.options.container?f.appendTo(this.options.container):f.insertAfter(this.$element),this.$element.trigger("inserted.bs."+this.type);var k=this.getPosition(),l=f[0].offsetWidth,m=f[0].offsetHeight;if(j){var n=h,o=this.getPosition(this.$viewport);h="bottom"==h&&k.bottom+m>o.bottom?"top":"top"==h&&k.top-m<o.top?"bottom":"right"==h&&k.right+l>o.width?"left":"left"==h&&k.left-l<o.left?"right":h,f.removeClass(n).addClass(h)}var p=this.getCalculatedOffset(h,k,l,m);this.applyPlacement(p,h);var q=function(){var a=e.hoverState;e.$element.trigger("shown.bs."+e.type),e.hoverState=null,"out"==a&&e.leave(e)};a.support.transition&&this.$tip.hasClass("fade")?f.one("bsTransitionEnd",q).emulateTransitionEnd(c.TRANSITION_DURATION):q()}},c.prototype.applyPlacement=function(b,c){var d=this.tip(),e=d[0].offsetWidth,f=d[0].offsetHeight,g=parseInt(d.css("margin-top"),10),h=parseInt(d.css("margin-left"),10);isNaN(g)&&(g=0),isNaN(h)&&(h=0),b.top+=g,b.left+=h,a.offset.setOffset(d[0],a.extend({using:function(a){d.css({top:Math.round(a.top),left:Math.round(a.left)})}},b),0),d.addClass("in");var i=d[0].offsetWidth,j=d[0].offsetHeight;"top"==c&&j!=f&&(b.top=b.top+f-j);var k=this.getViewportAdjustedDelta(c,b,i,j);k.left?b.left+=k.left:b.top+=k.top;var l=/top|bottom/.test(c),m=l?2*k.left-e+i:2*k.top-f+j,n=l?"offsetWidth":"offsetHeight";d.offset(b),this.replaceArrow(m,d[0][n],l)},c.prototype.replaceArrow=function(a,b,c){this.arrow().css(c?"left":"top",50*(1-a/b)+"%").css(c?"top":"left","")},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle();a.find(".tooltip-inner")[this.options.html?"html":"text"](b),a.removeClass("fade in top bottom left right")},c.prototype.hide=function(b){function d(){"in"!=e.hoverState&&f.detach(),e.$element&&e.$element.removeAttr("aria-describedby").trigger("hidden.bs."+e.type),b&&b()}var e=this,f=a(this.$tip),g=a.Event("hide.bs."+this.type);if(this.$element.trigger(g),!g.isDefaultPrevented())return f.removeClass("in"),a.support.transition&&f.hasClass("fade")?f.one("bsTransitionEnd",d).emulateTransitionEnd(c.TRANSITION_DURATION):d(),this.hoverState=null,this},c.prototype.fixTitle=function(){var a=this.$element;(a.attr("title")||"string"!=typeof a.attr("data-original-title"))&&a.attr("data-original-title",a.attr("title")||"").attr("title","")},c.prototype.hasContent=function(){return this.getTitle()},c.prototype.getPosition=function(b){b=b||this.$element;var c=b[0],d="BODY"==c.tagName,e=c.getBoundingClientRect();null==e.width&&(e=a.extend({},e,{width:e.right-e.left,height:e.bottom-e.top}));var f=window.SVGElement&&c instanceof window.SVGElement,g=d?{top:0,left:0}:f?null:b.offset(),h={scroll:d?document.documentElement.scrollTop||document.body.scrollTop:b.scrollTop()},i=d?{width:a(window).width(),height:a(window).height()}:null;return a.extend({},e,h,i,g)},c.prototype.getCalculatedOffset=function(a,b,c,d){return"bottom"==a?{top:b.top+b.height,left:b.left+b.width/2-c/2}:"top"==a?{top:b.top-d,left:b.left+b.width/2-c/2}:"left"==a?{top:b.top+b.height/2-d/2,left:b.left-c}:{top:b.top+b.height/2-d/2,left:b.left+b.width}},c.prototype.getViewportAdjustedDelta=function(a,b,c,d){var e={top:0,left:0};if(!this.$viewport)return e;var f=this.options.viewport&&this.options.viewport.padding||0,g=this.getPosition(this.$viewport);if(/right|left/.test(a)){var h=b.top-f-g.scroll,i=b.top+f-g.scroll+d;h<g.top?e.top=g.top-h:i>g.top+g.height&&(e.top=g.top+g.height-i)}else{var j=b.left-f,k=b.left+f+c;j<g.left?e.left=g.left-j:k>g.right&&(e.left=g.left+g.width-k)}return e},c.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||("function"==typeof c.title?c.title.call(b[0]):c.title)},c.prototype.getUID=function(a){do a+=~~(1e6*Math.random());while(document.getElementById(a));return a},c.prototype.tip=function(){if(!this.$tip&&(this.$tip=a(this.options.template),1!=this.$tip.length))throw new Error(this.type+" `template` option must consist of exactly 1 top-level element!");return this.$tip},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},c.prototype.enable=function(){this.enabled=!0},c.prototype.disable=function(){this.enabled=!1},c.prototype.toggleEnabled=function(){this.enabled=!this.enabled},c.prototype.toggle=function(b){var c=this;b&&(c=a(b.currentTarget).data("bs."+this.type),c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c))),b?(c.inState.click=!c.inState.click,c.isInStateTrue()?c.enter(c):c.leave(c)):c.tip().hasClass("in")?c.leave(c):c.enter(c)},c.prototype.destroy=function(){var a=this;clearTimeout(this.timeout),this.hide(function(){a.$element.off("."+a.type).removeData("bs."+a.type),a.$tip&&a.$tip.detach(),a.$tip=null,a.$arrow=null,a.$viewport=null,a.$element=null})};var d=a.fn.tooltip;a.fn.tooltip=b,a.fn.tooltip.Constructor=c,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=d,this}}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof b&&b;!e&&/destroy|hide/.test(b)||(e||d.data("bs.popover",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");c.VERSION="3.3.7",c.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:'<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'}),c.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),c.prototype.constructor=c,c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content").children().detach().end()[this.options.html?"string"==typeof c?"html":"append":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},c.prototype.hasContent=function(){return this.getTitle()||this.getContent()},c.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")};var d=a.fn.popover;a.fn.popover=b,a.fn.popover.Constructor=c,a.fn.popover.noConflict=function(){return a.fn.popover=d,this}}(jQuery),+function(a){"use strict";function b(c,d){this.$body=a(document.body),this.$scrollElement=a(a(c).is(document.body)?window:c),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",a.proxy(this.process,this)),this.refresh(),this.process()}function c(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})}b.VERSION="3.3.7",b.DEFAULTS={offset:10},b.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},b.prototype.refresh=function(){var b=this,c="offset",d=0;this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight(),a.isWindow(this.$scrollElement[0])||(c="position",d=this.$scrollElement.scrollTop()),this.$body.find(this.selector).map(function(){var b=a(this),e=b.data("target")||b.attr("href"),f=/^#./.test(e)&&a(e);return f&&f.length&&f.is(":visible")&&[[f[c]().top+d,e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){b.offsets.push(this[0]),b.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.getScrollHeight(),d=this.options.offset+c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(this.scrollHeight!=c&&this.refresh(),b>=d)return g!=(a=f[f.length-1])&&this.activate(a);if(g&&b<e[0])return this.activeTarget=null,this.clear();for(a=e.length;a--;)g!=f[a]&&b>=e[a]&&(void 0===e[a+1]||b<e[a+1])&&this.activate(f[a])},b.prototype.activate=function(b){ this.activeTarget=b,this.clear();var c=this.selector+'[data-target="'+b+'"],'+this.selector+'[href="'+b+'"]',d=a(c).parents("li").addClass("active");d.parent(".dropdown-menu").length&&(d=d.closest("li.dropdown").addClass("active")),d.trigger("activate.bs.scrollspy")},b.prototype.clear=function(){a(this.selector).parentsUntil(this.options.target,".active").removeClass("active")};var d=a.fn.scrollspy;a.fn.scrollspy=c,a.fn.scrollspy.Constructor=b,a.fn.scrollspy.noConflict=function(){return a.fn.scrollspy=d,this},a(window).on("load.bs.scrollspy.data-api",function(){a('[data-spy="scroll"]').each(function(){var b=a(this);c.call(b,b.data())})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.tab");e||d.data("bs.tab",e=new c(this)),"string"==typeof b&&e[b]()})}var c=function(b){this.element=a(b)};c.VERSION="3.3.7",c.TRANSITION_DURATION=150,c.prototype.show=function(){var b=this.element,c=b.closest("ul:not(.dropdown-menu)"),d=b.data("target");if(d||(d=b.attr("href"),d=d&&d.replace(/.*(?=#[^\s]*$)/,"")),!b.parent("li").hasClass("active")){var e=c.find(".active:last a"),f=a.Event("hide.bs.tab",{relatedTarget:b[0]}),g=a.Event("show.bs.tab",{relatedTarget:e[0]});if(e.trigger(f),b.trigger(g),!g.isDefaultPrevented()&&!f.isDefaultPrevented()){var h=a(d);this.activate(b.closest("li"),c),this.activate(h,h.parent(),function(){e.trigger({type:"hidden.bs.tab",relatedTarget:b[0]}),b.trigger({type:"shown.bs.tab",relatedTarget:e[0]})})}}},c.prototype.activate=function(b,d,e){function f(){g.removeClass("active").find("> .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!1),b.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",!0),h?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu").length&&b.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!0),e&&e()}var g=d.find("> .active"),h=e&&a.support.transition&&(g.length&&g.hasClass("fade")||!!d.find("> .fade").length);g.length&&h?g.one("bsTransitionEnd",f).emulateTransitionEnd(c.TRANSITION_DURATION):f(),g.removeClass("in")};var d=a.fn.tab;a.fn.tab=b,a.fn.tab.Constructor=c,a.fn.tab.noConflict=function(){return a.fn.tab=d,this};var e=function(c){c.preventDefault(),b.call(a(this),"show")};a(document).on("click.bs.tab.data-api",'[data-toggle="tab"]',e).on("click.bs.tab.data-api",'[data-toggle="pill"]',e)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof b&&b;e||d.data("bs.affix",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.options=a.extend({},c.DEFAULTS,d),this.$target=a(this.options.target).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(b),this.affixed=null,this.unpin=null,this.pinnedOffset=null,this.checkPosition()};c.VERSION="3.3.7",c.RESET="affix affix-top affix-bottom",c.DEFAULTS={offset:0,target:window},c.prototype.getState=function(a,b,c,d){var e=this.$target.scrollTop(),f=this.$element.offset(),g=this.$target.height();if(null!=c&&"top"==this.affixed)return e<c&&"top";if("bottom"==this.affixed)return null!=c?!(e+this.unpin<=f.top)&&"bottom":!(e+g<=a-d)&&"bottom";var h=null==this.affixed,i=h?e:f.top,j=h?g:b;return null!=c&&e<=c?"top":null!=d&&i+j>=a-d&&"bottom"},c.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(c.RESET).addClass("affix");var a=this.$target.scrollTop(),b=this.$element.offset();return this.pinnedOffset=b.top-a},c.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},c.prototype.checkPosition=function(){if(this.$element.is(":visible")){var b=this.$element.height(),d=this.options.offset,e=d.top,f=d.bottom,g=Math.max(a(document).height(),a(document.body).height());"object"!=typeof d&&(f=e=d),"function"==typeof e&&(e=d.top(this.$element)),"function"==typeof f&&(f=d.bottom(this.$element));var h=this.getState(g,b,e,f);if(this.affixed!=h){null!=this.unpin&&this.$element.css("top","");var i="affix"+(h?"-"+h:""),j=a.Event(i+".bs.affix");if(this.$element.trigger(j),j.isDefaultPrevented())return;this.affixed=h,this.unpin="bottom"==h?this.getPinnedOffset():null,this.$element.removeClass(c.RESET).addClass(i).trigger(i.replace("affix","affixed")+".bs.affix")}"bottom"==h&&this.$element.offset({top:g-b-f})}};var d=a.fn.affix;a.fn.affix=b,a.fn.affix.Constructor=c,a.fn.affix.noConflict=function(){return a.fn.affix=d,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var c=a(this),d=c.data();d.offset=d.offset||{},null!=d.offsetBottom&&(d.offset.bottom=d.offsetBottom),null!=d.offsetTop&&(d.offset.top=d.offsetTop),b.call(c,d)})})}(jQuery); /* Ajaxchimp */ (function($){"use strict";$.ajaxChimp={responses:{"We have sent you a confirmation email":0,"Please enter a value":1,"An email address must contain a single @":2,"The domain portion of the email address is invalid (the portion after the @: )":3,"The username portion of the email address is invalid (the portion before the @: )":4,"This email address looks fake or invalid. Please enter a real email address":5},translations:{en:null},init:function(selector,options){$(selector).ajaxChimp(options)}};$.fn.ajaxChimp=function(options){$(this).each(function(i,elem){var form=$(elem);var email=form.find("input[type=email]");var label=form.find("label[for="+email.attr("id")+"]");var settings=$.extend({url:form.attr("action"),language:"en"},options);var url=settings.url.replace("/post?","/post-json?").concat("&c=?");form.attr("novalidate","true");email.attr("name","EMAIL");form.submit(function(){var msg;function successCallback(resp){if(resp.result==="success"){msg="We have sent you a confirmation email";label.removeClass("error").addClass("valid");email.removeClass("error").addClass("valid")}else{email.removeClass("valid").addClass("error");label.removeClass("valid").addClass("error");var index=-1;try{var parts=resp.msg.split(" - ",2);if(parts[1]===undefined){msg=resp.msg}else{var i=parseInt(parts[0],10);if(i.toString()===parts[0]){index=parts[0];msg=parts[1]}else{index=-1;msg=resp.msg}}}catch(e){index=-1;msg=resp.msg}}if(settings.language!=="en"&&$.ajaxChimp.responses[msg]!==undefined&&$.ajaxChimp.translations&&$.ajaxChimp.translations[settings.language]&&$.ajaxChimp.translations[settings.language][$.ajaxChimp.responses[msg]]){msg=$.ajaxChimp.translations[settings.language][$.ajaxChimp.responses[msg]]}label.html(msg);label.show(2e3);if(settings.callback){settings.callback(resp)}}var data={};var dataArray=form.serializeArray();$.each(dataArray,function(index,item){data[item.name]=item.value});$.ajax({url:url,data:data,success:successCallback,dataType:"jsonp",error:function(resp,text){console.log("mailchimp ajax submit error: "+text)}});var submitMsg="Submitting...";if(settings.language!=="en"&&$.ajaxChimp.translations&&$.ajaxChimp.translations[settings.language]&&$.ajaxChimp.translations[settings.language]["submit"]){submitMsg=$.ajaxChimp.translations[settings.language]["submit"]}label.html(submitMsg).show(2e3);return false})});return this}})(jQuery); /** * downCount: Simple Countdown clock with offset * Author: Sonny T. <hi@sonnyt.com>, sonnyt.com */ (function ($) { $.fn.downCount = function (options, callback) { var settings = $.extend({ date: null, offset: null }, options); // Throw error if date is not set if (!settings.date) { $.error('Date is not defined.'); } // Throw error if date is set incorectly if (!Date.parse(settings.date)) { $.error('Incorrect date format, it should look like this, 12/24/2012 12:00:00.'); } // Save container var container = this; /** * Change client's local date to match offset timezone * @return {Object} Fixed Date object. */ var currentDate = function () { // get client's current date var date = new Date(); // turn date to utc var utc = date.getTime() + (date.getTimezoneOffset() * 60000); // set new Date object var new_date = new Date(utc + (3600000*settings.offset)) return new_date; }; /** * Main downCount function that calculates everything */ function countdown () { var target_date = new Date(settings.date), // set target date current_date = currentDate(); // get fixed current date // difference of dates var difference = target_date - current_date; // if difference is negative than it's pass the target date if (difference < 0) { // stop timer clearInterval(interval); if (callback && typeof callback === 'function') callback(); return; } // basic math variables var _second = 1000, _minute = _second * 60, _hour = _minute * 60, _day = _hour * 24; // calculate dates var days = Math.floor(difference / _day), hours = Math.floor((difference % _day) / _hour), minutes = Math.floor((difference % _hour) / _minute), seconds = Math.floor((difference % _minute) / _second); // fix dates so that it will show two digets days = (String(days).length >= 2) ? days : '0' + days; hours = (String(hours).length >= 2) ? hours : '0' + hours; minutes = (String(minutes).length >= 2) ? minutes : '0' + minutes; seconds = (String(seconds).length >= 2) ? seconds : '0' + seconds; // based on the date change the refrence wording var ref_days = (days === 1) ? 'day' : 'days', ref_hours = (hours === 1) ? 'hour' : 'hours', ref_minutes = (minutes === 1) ? 'minute' : 'minutes', ref_seconds = (seconds === 1) ? 'second' : 'seconds'; // set to DOM container.find('.days').text(days); container.find('.hours').text(hours); container.find('.minutes').text(minutes); container.find('.seconds').text(seconds); container.find('.days_ref').text(ref_days); container.find('.hours_ref').text(ref_hours); container.find('.minutes_ref').text(ref_minutes); container.find('.seconds_ref').text(ref_seconds); }; // start var interval = setInterval(countdown, 1000); }; })(jQuery); !function(e){e.fn.hover3d=function(t){var r=e.extend({selector:null,perspective:1e3,sensitivity:20,invert:!1,shine:!1,hoverInClass:"hover-in",hoverOutClass:"hover-out",hoverClass:"hover-3d"},t);return this.each(function(){function t(e){i.addClass(r.hoverInClass+" "+r.hoverClass),currentX=currentY=0,setTimeout(function(){i.removeClass(r.hoverInClass)},1e3)}function s(e){var t=i.innerWidth(),s=i.innerHeight(),n=Math.round(e.pageX-i.offset().left),o=Math.round(e.pageY-i.offset().top),v=r.invert?(t/2-n)/r.sensitivity:-(t/2-n)/r.sensitivity,c=r.invert?-(s/2-o)/r.sensitivity:(s/2-o)/r.sensitivity,u=n-t/2,p=o-s/2,f=Math.atan2(p,u),h=180*f/Math.PI-90;0>h&&(h+=360),i.css({perspective:r.perspective+"px",transformStyle:"preserve-3d",transform:"rotateY("+v+"deg) rotateX("+c+"deg)"}),a.css("background","linear-gradient("+h+"deg, rgba(255,255,255,"+e.offsetY/s*.5+") 0%,rgba(255,255,255,0) 80%)")}function n(){i.addClass(r.hoverOutClass+" "+r.hoverClass),i.css({perspective:r.perspective+"px",transformStyle:"preserve-3d",transform:"rotateX(0) rotateY(0)"}),setTimeout(function(){i.removeClass(r.hoverOutClass+" "+r.hoverClass),currentX=currentY=0},1e3)}var o=e(this),i=o.find(r.selector);currentX=0,currentY=0,r.shine&&i.append('<div class="shine"></div>');var a=e(this).find(".shine");o.css({perspective:r.perspective+"px",transformStyle:"preserve-3d"}),i.css({perspective:r.perspective+"px",transformStyle:"preserve-3d"}),a.css({position:"absolute",top:0,left:0,bottom:0,right:0,transform:"translateZ(1px)","z-index":9}),o.on("mouseenter",function(){return t()}),o.on("mousemove",function(e){return s(e)}),o.on("mouseleave",function(){return n()})})}}(jQuery);
/*! * hnzswh-rvt-api * Copyright(c) 2015 hnzswh-rvt-api <3203317@qq.com> * MIT Licensed */ 'use strict'; var express = require('express'), flash = require('connect-flash'), velocity = require('velocityjs'), fs = require('fs'), http = require('http'), path = require('path'), cwd = process.cwd(); var util = require('speedt-utils'); var macros = require('./lib/macro'), errorHandler = require("./lib/errorHandler"), conf = require('./settings'), // session config mysqlconf = conf.mysql; var app = express(); // all environments app.set('port', process.env.PORT || 3011) .set('views', path.join(__dirname, 'views')) .set('view engine', 'html') /* use */ .use(flash()) .use(express.favicon()) .use(express.json()) .use(express.urlencoded()) .use(express.methodOverride()) .use(express.cookieParser()); // production if('production' === app.get('env')){ app.use('/public', express.static(path.join(__dirname, 'public'), { maxAge: 101000 })) .use(express.errorHandler()) .use(express.logger('dev')); } // development if('development' === app.get('env')){ app.use(express.logger('dev')) .use('/public', express.static(path.join(__dirname, 'public'))) .use(express.errorHandler({ dumpExceptions: true, showStack: true })); } app.use(express.session({ secret: conf.cookie.secret, key: mysqlconf.database, cookie: { maxAge: 1000 * 60 * 60 * 24 * 1 //30 days } })); app.use(app.router) /* velocity */ .engine('.html', function (path, options, fn){ fs.readFile(path, 'utf8', function (err, data){ if(err) return fn(err); try{ fn(null, velocity.render(data, options, macros)); } catch(ex){ fn(ex); } }); }); errorHandler.appErrorProcess(app); var Robot = require('./lib/robot'); var server = http.createServer(app); // server.setTimeout(5000); server.listen(app.get('port'), function(){ console.log('[%s] Express server listening on port %s.', util.format(), app.get('port')); require('./routes')(app); // TODO var robot = new Robot(); robot.start(function(){ console.log('[%s] Robot start.', util.format()); }); });
import { assert } from 'chai'; import fetchMock from 'fetch-mock'; import { uploadRequest } from '../src/upload-request'; describe('uploadRequest', function () { beforeEach(function () { fetchMock.post('*', new Response( '{"foo": "bar"}', { status : 200 , statusText : "OK", headers: { 'Content-Type': 'application/json', 'dropbox-api-result': '{"test":"json"}' } } )); }); afterEach(function () { fetchMock.restore(); }); it('returns a promise', function () { assert.instanceOf( uploadRequest('path', {}, 'user', 'content', 'atoken'), Promise ); }); it('posts to the correct url', function (done) { uploadRequest('files/upload', { foo: 'bar' }, 'user', 'content', 'atoken') .then(() => { assert.equal(fetchMock.calls().matched.length, 1); assert.equal(fetchMock.lastUrl(), 'https://content.dropboxapi.com/2/files/upload'); done(); }, done); }); it('sets the request type to application/octet-stream', function (done) { uploadRequest('files/upload', { foo: 'bar' }, 'user', 'content', 'atoken') .then(() => { assert.equal(fetchMock.lastOptions().headers['Content-Type'], 'application/octet-stream'); done(); }, done); }); it('sets the authorization header', function (done) { uploadRequest('files/upload', { foo: 'bar' }, 'user', 'content', 'atoken') .then((data) => { assert.equal(fetchMock.lastOptions().headers['Authorization'], 'Bearer atoken'); done(); }, done); }); it('sets the authorization and select user headers if selectUser set', function (done) { uploadRequest('files/upload', { foo: 'bar' }, 'user', 'content', 'atoken', 'selectedUserId') .then((data) => { assert.equal(fetchMock.lastOptions().headers['Authorization'], 'Bearer atoken'); assert.equal(fetchMock.lastOptions().headers['Dropbox-API-Select-User'], 'selectedUserId'); done(); }, done); }); it('sets the Dropbox-API-Arg header', function (done) { uploadRequest('files/upload', { foo: 'bar' }, 'user', 'content', 'atoken') .then((data) => { assert.equal(fetchMock.lastOptions().headers['Authorization'], 'Bearer atoken'); assert.equal(fetchMock.lastOptions().headers['Dropbox-API-Arg'], JSON.stringify({ foo: 'bar' })); done(); }, done); }); it('escapes special characters in the Dropbox-API-Arg header', function (done) { uploadRequest('files/upload', { foo: 'bar单bazá' }, 'user', 'content', 'atoken') .then((data) => { assert.equal(fetchMock.lastOptions().headers['Authorization'], 'Bearer atoken'); assert.equal(fetchMock.lastOptions().headers['Dropbox-API-Arg'], '{"foo":"bar\\u5355baz\\u00e1"}'); done(); }, done); }); it('doesn\'t include args.contents in the Dropbox-API-Arg header', function (done) { uploadRequest('files/upload', { foo: 'bar', contents: 'fakecontents' }, 'user', 'content', 'atoken') .then((data) => { assert.equal(fetchMock.lastOptions().headers['Dropbox-API-Arg'], JSON.stringify({ foo: 'bar' })); done(); }, done); }); it('returns a valid response', function (done) { uploadRequest('files/upload', { foo: 'bar' }, 'user', 'content', 'atoken') .then((data) => { assert.deepEqual(data, { foo: 'bar' }) done(); }, done); }); });
const { cuboid, cylinder, cylinderElliptic } = require('@jscad/modeling').primitives const { translate, rotateX, rotateY, rotateZ } = require('@jscad/modeling').transforms const { union, subtract } = require('@jscad/modeling').booleans const { polygon } = require('@jscad/modeling').primitives const { extrudeLinear } = require('@jscad/modeling').extrusions const Epsilon = 0.1 // a small extra for imprecise printers const Thickness = 2.0 const BoreholeDiameter = 3.0, BoreholeRadius = BoreholeDiameter/2 const BoreholeOffset = 8.0 const BoreholeDistance = BoreholeOffset - BoreholeDiameter const BoreholeSpace = BoreholeDistance/2 const ServoBodyWidth = 13.0 // a bit larger than in reality const ServoBodyLength = 23.0 // dto. const ServoBodyHeight = 27.0 // dto. const ServoFlangeOffset = 15.6 // dto. const ServoFlangeThickness = 2.5 + Epsilon const ServoFlangeLength = 5.0 + Epsilon const ServoScrewOffset = 2.0 const ServoHornAxisOffset = 6.5 // more a guess than a measurement const ScrewDiameter = 2.0, ScrewRadius = ScrewDiameter/2 const NutThickness = 3.0 const Angle90 = 90 * Math.PI/180 const Angle180 = 180 * Math.PI/180 const Angle270 = 270 * Math.PI/180 const main = () => { let Flange = subtract( // servo should be mounted from the top cuboid({ size:[ ServoFlangeLength, Thickness, ServoBodyWidth ] }), rotateX( Angle90, cylinder({ radius:ScrewRadius, height:Thickness+1.0 }) ) ) let leftFlange = translate([ -ServoFlangeLength/2, Thickness/2, ServoBodyWidth/2 ], Flange) let rightFlange = translate([ ServoFlangeLength/2+ServoBodyLength, Thickness/2, ServoBodyWidth/2 ], Flange) const BracketLength = ServoFlangeOffset + Thickness + NutThickness // gives room for a nut underneath the servo let Bracket = cuboid({ size:[ Thickness,BracketLength,ServoBodyWidth ] }) let BoreholeCount = Math.floor((BracketLength-2*Thickness)/BoreholeOffset) for (let i = 0; i < BoreholeCount; i++) { Bracket = subtract( Bracket, translate( [ 0,(i-(BoreholeCount-1)/2)*BoreholeOffset,0 ], rotateY( Angle90, cylinder({ radius:BoreholeRadius+Epsilon, height:Thickness }) ) ) ) } Bracket = translate([0,BracketLength/2,ServoBodyWidth/2], Bracket) let BracketExtension = BoreholeOffset let extendedBracket = cuboid({ size:[ Thickness,BracketLength,ServoBodyWidth+BracketExtension ] }) extendedBracket = translate([ 0,0,BracketExtension/2 ], extendedBracket) for (let i = 0; i < BoreholeCount; i++) { extendedBracket = subtract( extendedBracket, translate( [ 0,(i-(BoreholeCount-1)/2)*BoreholeOffset,0 ], rotateY( Angle90, cylinder({ radius:BoreholeRadius+Epsilon, height:Thickness }) ) ), translate( [ 0,(i-(BoreholeCount-1)/2)*BoreholeOffset,BoreholeOffset ], rotateY( Angle90, cylinder({ radius:BoreholeRadius+Epsilon, height:Thickness }) ) ) ) } extendedBracket = translate([0,BracketLength/2,ServoBodyWidth/2], extendedBracket) let leftBracket = translate([ -0.5*Thickness-ServoFlangeLength,0,0 ], extendedBracket) let rightBracket = translate([ 0.5*Thickness+ServoFlangeLength+ServoBodyLength,0,0 ], extendedBracket) const BaseLength = ServoBodyLength+2*ServoFlangeLength let Base = cuboid({ size:[ BaseLength, Thickness, ServoBodyWidth ] }) BoreholeCount = Math.floor(BaseLength/BoreholeOffset) for (let i = 0; i < BoreholeCount; i++) { Base = subtract( Base, translate( [ (i-(BoreholeCount-1)/2)*BoreholeOffset,0,0 ], rotateX( Angle90, cylinder({ radius:BoreholeRadius+Epsilon, height:Thickness }) ) ) ) } Base = translate([ ServoBodyLength/2, BracketLength-Thickness/2, ServoBodyWidth/2 ], Base) let ServoMount = union( leftFlange, leftBracket, rightFlange, rightBracket, Base ) return ServoMount } module.exports = { main }
import { Guid, Validate } from '@microsoft/sp-core-library'; var AzureActiveDirectoryInfo = (function () { function AzureActiveDirectoryInfo(data) { this._validate(data); this._instanceUrl = data.instanceUrl ? data.instanceUrl : ''; this._tenantId = Guid.parse(data.tenantId); this._userId = Guid.parse(data.userId); } AzureActiveDirectoryInfo.prototype._serialize = function () { return { tenantId: this.tenantId.toString(), userId: this.userId.toString(), instanceUrl: this.instanceUrl }; }; Object.defineProperty(AzureActiveDirectoryInfo.prototype, "instanceUrl", { get: function () { return this._instanceUrl; }, enumerable: true, configurable: true }); Object.defineProperty(AzureActiveDirectoryInfo.prototype, "tenantId", { get: function () { return this._tenantId; }, enumerable: true, configurable: true }); Object.defineProperty(AzureActiveDirectoryInfo.prototype, "userId", { get: function () { return this._userId; }, enumerable: true, configurable: true }); AzureActiveDirectoryInfo.prototype._validate = function (data) { Validate.isNotNullOrUndefined(data, 'IAzureActiveDirectoryInfo object'); Validate.isNotNullOrUndefined(Guid.tryParse(data.tenantId), 'tenantId'); Validate.isNotNullOrUndefined(Guid.tryParse(data.userId), 'userId'); }; return AzureActiveDirectoryInfo; }()); export default AzureActiveDirectoryInfo;
export const GET_CUSTOMER_PENDING = 'get_customer_pending'; export const GET_CUSTOMER_PASS = 'get_customer_passed'; export const GET_CUSTOMER_FAIL = 'get_customer_failed'; export const CREATE_CUSTOMER_PENDING = 'create_customer_pending'; export const CREATE_CUSTOMER_PASS = 'create_customer_passed'; export const CREATE_CUSTOMER_FAIL = 'create_customer_failed'; export const LOGIN_CUSTOMER_PENDING = 'login_customer_pending'; export const LOGIN_CUSTOMER_PASS = 'login_customer_passed'; export const LOGIN_CUSTOMER_FAIL = 'login_customer_failed'; export const UPDATE_CUSTOMER_DETAIL_PENDING = 'update_customer_detail_pending'; export const UPDATE_CUSTOMER_DETAIL_PASS = 'update_customer_detail_passed'; export const UPDATE_CUSTOMER_DETAIL_FAIL = 'update_customer_detail_failed'; export const UPDATE_CUSTOMER_ADDRESS_PENDING = 'update_customer_address_pending'; export const UPDATE_CUSTOMER_ADDRESS_PASS = 'update_customer_address_passed'; export const UPDATE_CUSTOMER_ADDRESS_FAIL = 'update_customer_address_failed'; export const UPDATE_CUSTOMER_CARD_PENDING = 'update_customer_card_pending'; export const UPDATE_CUSTOMER_CARD_PASS = 'update_customer_card_passed'; export const UPDATE_CUSTOMER_CARD_FAIL = 'update_customer_card_failed'; export const LOGIN_CONFIRM = 'login_cnfirmation'; export const LOGOUT_CUSTOMER_PENDING = 'logout_pending'; export const LOGOUT_CUSTOMER_PASS = 'logout_pass';
Calendar.ns('Controllers').Sync = (function() { /** * Handles all synchronization related * tasks. The intent is that this will * be the focal point for any view * to observe sync events and this * controller will decide when to actually * tell the stores when to sync. */ function Sync(app) { this.app = app; this.pending = 0; Calendar.Responder.call(this); } Sync.prototype = { __proto__: Calendar.Responder.prototype, startEvent: 'syncStart', completeEvent: 'syncComplete', _incrementPending: function() { if (!this.pending) { this.emit('syncStart'); } this.pending++; }, _resolvePending: function() { if (!(--this.pending)) { this.emit('syncComplete'); } }, /** * Sync all accounts, calendars, events. * There is no callback for all intentionally. * * Use: * * controller.once('syncComplete', cb); * */ all: function(callback) { if (callback) { this.once('syncComplete', callback); } if (this.app.offline()) { this.emit('offline'); this.emit('syncComplete'); return; } var account = this.app.store('Account'); account.all(function(err, list) { for (var key in list) { this.account(list[key]); } // If we have nothing to sync if (!this.pending) { this.emit('syncComplete'); } }.bind(this)); }, /** * Initiates a sync for a single calendar. * * @param {Object} account parent of calendar. * @param {Object} calendar specific calendar to sync. * @param {Function} [callback] optional callback. */ calendar: function(account, calendar, callback) { var store = this.app.store('Calendar'); var self = this; this._incrementPending(); store.sync(account, calendar, function(err) { self._resolvePending(); if (callback) callback(err); }); }, /** * Initiates a sync of a single account and all * associated calendars (calendars that exist after * the full sync of the account itself). * * @param {Object} account sync target. * @param {Function} [callback] optional callback. */ account: function(account, callback) { var accountStore = this.app.store('Account'); var calendarStore = this.app.store('Calendar'); var self = this; this._incrementPending(); accountStore.sync(account, function(err) { var pending = 0; function next() { if (!(--pending)) { self._resolvePending(); if (callback) callback(); } } function fetchCalendars(err, calendars) { if (err) { return callback(err); } for (var key in calendars) { pending++; self.calendar(account, calendars[key], next); } } // find all calendars var calendars = calendarStore.remotesByAccount( account._id, fetchCalendars ); }); } }; return Sync; }());
import { put, takeEvery } from 'redux-saga/effects' import store from 'react-native-simple-store' import { AppInstalledChecker } from 'react-native-check-app-install' import { Creators, Types } from '../actions/sendAction' export function * initData () { const selectedCountryIndex = yield store.get('sendSelectedCountryIndex') if (selectedCountryIndex !== null) { yield put(Creators.updateSelectedCountryIndex(selectedCountryIndex)) } const whatsAppInstalled = yield AppInstalledChecker.checkURLScheme('whatsapp') yield put(Creators.updateWhatsappInstalled(whatsAppInstalled)) } export function * onUpdateSelectedCountryIndex ({ selectedCountryIndex }) { try { yield store.save('sendSelectedCountryIndex', selectedCountryIndex) } catch (e) { console.error(e) } } function * sendSaga () { yield takeEvery(Types.INIT_DATA, initData) yield takeEvery(Types.UPDATE_SELECTED_COUNTRY_INDEX, onUpdateSelectedCountryIndex) } export default sendSaga
// @ts-check const {default: test} = require('ava'); const {spawn} = require('child_process'); const fs = require('fs-extra'); const {tmpdir} = require('os'); const path = require('path'); /** * @param {string} p * @returns {Promise<boolean>} */ async function isDirectory(p) { try { return (await fs.stat(p)).isDirectory(); } catch { return false; } } /** * @param {string} command * @param {string[]} args * @param {string} cwd * @returns {Promise<void>} */ function exec(command, args, cwd) { return new Promise((resolve, reject) => { const child = spawn(command, args, { cwd, stdio: ['ignore', 'pipe', 'ignore'], }); const outputs = []; child.stdout.on('data', buffer => outputs.push(buffer)); child.on('close', (code, signal) => { if (code || signal) { reject( new Error( `Command "${[command, ...args].join(' ')}" exited with ${ code ? `code ${code}` : `signal ${signal}` }\nOutput:\n\n${Buffer.concat(outputs).toString()}`, ), ); } else { resolve(); } }); }); } const tmpDirectory = path.join(tmpdir(), 'express-check-in'); const fixturesPath = path.join(__dirname, '__fixtures__'); /** * @param {...(() => Promise<void>)} promiseFactories * @returns {Promise<void>} */ function chain(...promiseFactories) { return promiseFactories.reduce( (promise, factory) => promise.then(() => factory()), Promise.resolve(), ); } /** * @param {string} name * @param {import('ava').ExecutionContext} t */ async function loadFixture(name, t) { const fixturePath = path.resolve(fixturesPath, name); await fs.mkdir(tmpDirectory, {recursive: true}); const repo = await fs.mkdtemp(tmpDirectory + path.sep); const repoFiles = path.join(repo, 'src'); t.teardown(() => { fs.removeSync(repo); }); /** @param {string[]} args */ function git(...args) { return exec('git', args, repo); } const [fixtureSettings] = await Promise.all([ fs.readJson(path.join(fixturePath, 'fixture.json')), git('init').then(() => Promise.all([ chain( () => git('config', 'commit.gpgSign', 'false'), () => git('config', 'user.name', 'Testy McTestface'), () => git('config', 'user.email', 'testy@example.com'), ), fs.writeFile( path.join(repo, '.git/info/exclude'), '.prettierrc.yml\n.editorconfig\n', ), ]), ), fs.copyFile( path.join(__dirname, '..', '.prettierrc.yml'), path.join(repo, '.prettierrc.yml'), ), fs.copyFile( path.join(__dirname, '..', '.editorconfig'), path.join(repo, '.editorconfig'), ), ]); { const committed = path.join(fixturePath, 'committed'); if (await isDirectory(committed)) { await fs.copy(committed, repoFiles); await git('add', '-A', ':/'); await git('commit', '-m', 'committed state'); } } { const staged = path.join(fixturePath, 'staged'); if (await isDirectory(staged)) { if (fixtureSettings.clean) { await fs.remove(repoFiles); } await fs.copy(staged, repoFiles); await git('add', '-A', ':/'); } } { const unstaged = path.join(fixturePath, 'unstaged'); if (await isDirectory(unstaged)) { if (fixtureSettings.clean) { await fs.remove(repoFiles); } await fs.copy(unstaged, repoFiles); } } await exec(fixtureSettings.command, fixtureSettings.args ?? [], repo); { const expectedWorkingDirectory = path.join( fixturePath, 'expected-working-directory', ); if (await isDirectory(expectedWorkingDirectory)) { for (const file of await fs.readdir(expectedWorkingDirectory)) { t.is( await fs.readFile(path.join(repoFiles, file), 'utf-8'), await fs.readFile(path.join(expectedWorkingDirectory, file), 'utf-8'), `Expected content of file ${file} in the working directory`, ); } } } { const expectedIndex = path.join(fixturePath, 'expected-index'); if (await isDirectory(expectedIndex)) { await git('restore', 'src'); for (const file of await fs.readdir(expectedIndex)) { t.is( await fs.readFile(path.join(repoFiles, file), 'utf-8'), await fs.readFile(path.join(expectedIndex, file), 'utf-8'), `Expected content of file ${file} in the index`, ); } } } } for (const fixture of fs.readdirSync(fixturesPath)) { test(`fixture ${fixture}`, t => loadFixture(fixture, t)); }
"use strict"; var interfaces_1 = require('./util/interfaces'); var errors_1 = require('./util/errors'); var events_1 = require('./util/events'); var path_1 = require('path'); var config_1 = require('./util/config'); var logger_1 = require('./logger/logger'); var webpackApi = require('webpack'); var events_2 = require('events'); var eventEmitter = new events_2.EventEmitter(); var INCREMENTAL_BUILD_FAILED = 'incremental_build_failed'; var INCREMENTAL_BUILD_SUCCESS = 'incremental_build_success'; /* * Due to how webpack watch works, sometimes we start an update event * but it doesn't affect the bundle at all, for example adding a new typescript file * not imported anywhere or adding an html file not used anywhere. * In this case, we'll be left hanging and have screwed up logging when the bundle is modified * because multiple promises will resolve at the same time (we queue up promises waiting for an event to occur) * To mitigate this, store pending "webpack watch"/bundle update promises in this array and only resolve the * the most recent one. reject all others at that time with an IgnorableError. */ var pendingPromises = []; function webpack(context, configFile) { configFile = config_1.getUserConfigFile(context, taskInfo, configFile); var logger = new logger_1.Logger('webpack'); return webpackWorker(context, configFile) .then(function () { context.bundleState = interfaces_1.BuildState.SuccessfulBuild; logger.finish(); }) .catch(function (err) { context.bundleState = interfaces_1.BuildState.RequiresBuild; throw logger.fail(err); }); } exports.webpack = webpack; function webpackUpdate(changedFiles, context, configFile) { var logger = new logger_1.Logger('webpack update'); var webpackConfig = getWebpackConfig(context, configFile); logger_1.Logger.debug('webpackUpdate: Starting Incremental Build'); var promisetoReturn = runWebpackIncrementalBuild(false, context, webpackConfig); events_1.emit(events_1.EventType.WebpackFilesChanged, null); return promisetoReturn.then(function (stats) { // the webpack incremental build finished, so reset the list of pending promises pendingPromises = []; logger_1.Logger.debug('webpackUpdate: Incremental Build Done, processing Data'); return webpackBuildComplete(stats, context, webpackConfig); }).then(function () { context.bundleState = interfaces_1.BuildState.SuccessfulBuild; return logger.finish(); }).catch(function (err) { context.bundleState = interfaces_1.BuildState.RequiresBuild; if (err instanceof errors_1.IgnorableError) { throw err; } throw logger.fail(err); }); } exports.webpackUpdate = webpackUpdate; function webpackWorker(context, configFile) { var webpackConfig = getWebpackConfig(context, configFile); var promise = null; if (context.isWatch) { promise = runWebpackIncrementalBuild(!context.webpackWatch, context, webpackConfig); } else { promise = runWebpackFullBuild(webpackConfig); } return promise .then(function (stats) { return webpackBuildComplete(stats, context, webpackConfig); }); } exports.webpackWorker = webpackWorker; function webpackBuildComplete(stats, context, webpackConfig) { // set the module files used in this bundle // this reference can be used elsewhere in the build (sass) var files = stats.compilation.modules.map(function (webpackObj) { if (webpackObj.resource) { return webpackObj.resource; } else { return webpackObj.context; } }).filter(function (path) { // just make sure the path is not null return path && path.length > 0; }); context.moduleFiles = files; return Promise.resolve(); } function runWebpackFullBuild(config) { return new Promise(function (resolve, reject) { var callback = function (err, stats) { if (err) { reject(new errors_1.BuildError(err)); } else { resolve(stats); } }; var compiler = webpackApi(config); compiler.run(callback); }); } function runWebpackIncrementalBuild(initializeWatch, context, config) { var promise = new Promise(function (resolve, reject) { // start listening for events, remove listeners once an event is received eventEmitter.on(INCREMENTAL_BUILD_FAILED, function (err) { logger_1.Logger.debug('Webpack Bundle Update Failed'); eventEmitter.removeAllListeners(); handleWebpackBuildFailure(resolve, reject, err, promise, pendingPromises); }); eventEmitter.on(INCREMENTAL_BUILD_SUCCESS, function (stats) { logger_1.Logger.debug('Webpack Bundle Updated'); eventEmitter.removeAllListeners(); handleWebpackBuildSuccess(resolve, reject, stats, promise, pendingPromises); }); if (initializeWatch) { startWebpackWatch(context, config); } }); pendingPromises.push(promise); return promise; } function handleWebpackBuildFailure(resolve, reject, error, promise, pendingPromises) { // check if the promise if the last promise in the list of pending promises if (pendingPromises.length > 0 && pendingPromises[pendingPromises.length - 1] === promise) { // reject this one with a build error reject(new errors_1.BuildError(error)); return; } // for all others, reject with an ignorable error reject(new errors_1.IgnorableError()); } function handleWebpackBuildSuccess(resolve, reject, stats, promise, pendingPromises) { // check if the promise if the last promise in the list of pending promises if (pendingPromises.length > 0 && pendingPromises[pendingPromises.length - 1] === promise) { logger_1.Logger.debug('handleWebpackBuildSuccess: Resolving with Webpack data'); resolve(stats); return; } // for all others, reject with an ignorable error logger_1.Logger.debug('handleWebpackBuildSuccess: Rejecting with ignorable error'); reject(new errors_1.IgnorableError()); } function startWebpackWatch(context, config) { logger_1.Logger.debug('Starting Webpack watch'); var compiler = webpackApi(config); context.webpackWatch = compiler.watch({}, function (err, stats) { if (err) { eventEmitter.emit(INCREMENTAL_BUILD_FAILED, err); } else { eventEmitter.emit(INCREMENTAL_BUILD_SUCCESS, stats); } }); } function getWebpackConfig(context, configFile) { configFile = config_1.getUserConfigFile(context, taskInfo, configFile); var webpackConfig = config_1.fillConfigDefaults(configFile, taskInfo.defaultConfigFile); webpackConfig.entry = config_1.replacePathVars(context, webpackConfig.entry); webpackConfig.output.path = config_1.replacePathVars(context, webpackConfig.output.path); return webpackConfig; } exports.getWebpackConfig = getWebpackConfig; function getOutputDest(context) { var webpackConfig = getWebpackConfig(context, null); return path_1.join(webpackConfig.output.path, webpackConfig.output.filename); } exports.getOutputDest = getOutputDest; var taskInfo = { fullArg: '--webpack', shortArg: '-w', envVar: 'IONIC_WEBPACK', packageConfig: 'ionic_webpack', defaultConfigFile: 'webpack.config' };
import { createResolved, createRejected, createResolvedOrRejected, delay } from './s22e01-create.js'; describe('Creating promises', () => { describe('createResolved', () => { it('should return a promise which resolves with provided value', () => { const value = Symbol('value'); return expect(createResolved(value)).resolves.toBe(value); }); }); describe('createRejected', () => { it('should return a promise which is rejected with provided error', () => { const error = Symbol('error'); return expect(createRejected(error)).rejects.toBe(error); }); }); describe('createResolvedOrRejected', () => { it('should return a promise which is resolved when "true" is provided as a parameter', () => { return expect(createResolvedOrRejected(true)).resolves.not.toThrow(); }); it('should return a promise which is rejected when "false" is provided as a parameter', () => { return expect(createResolvedOrRejected(false)).rejects.toBeUndefined(); }); }); describe('delay', () => { beforeEach(() => jest.useFakeTimers()); afterEach(() => jest.useRealTimers()); it('should return a promise', () => { expect(delay(100)).toEqual(expect.any(Promise)); }); it('delay(100) should be resolved between 80ms and 120ms', async () => { const spy = jest.fn(); delay(100).then(spy); // <= resolve after 100ms jest.advanceTimersByTime(80); // <= advance less than 100ms await Promise.resolve(); // let any pending callbacks in PromiseJobs run expect(spy).not.toHaveBeenCalled(); jest.advanceTimersByTime(40); // <= advance the rest of the time await Promise.resolve(); // let any pending callbacks in PromiseJobs run expect(spy).toHaveBeenCalled(); }); }); });
$(document).ready(function() { $('.banners-carousel').owlCarousel({ loop: false, autoplay: true, autoplayTimeout: 5000, autoplayHoverPause: true, nav: true, dots: false, smartSpeed: 1000, items: 1, navText : ['<svg width="50" height="50"><use href="#arrow-left"></use></svg>', '<svg width="50" height="50"><use href="#arrow-right"></use></svg>'] }); $('.clients-carousel').owlCarousel({ loop: true, nav: true, navText : ['<svg width="50" height="50"><use href="#angle-left"></use></svg>', '<svg width="50" height="50"><use href="#angle-right"></use></svg>'], dots: false, margin: 20, smartSpeed: 700, items: 2, responsive:{ 576: { items: 3 }, 768: { items: 4 }, 991: { items: 5 } } }); $('.products-carousel').each(function(){ $(this).owlCarousel({ loop: false, nav: true, navText : ['<svg width="50" height="50"><use href="#angle-left"></use></svg>', '<svg width="50" height="50"><use href="#angle-right"></use></svg>'], dots: false, margin: 30, smartSpeed: 500, items: 1, responsive:{ 376: { items: 2 }, 768: { items: 3 }, 991: { items: 4 } } }); }); var productionCarousel = $('.production-carousel').owlCarousel({ loop: true, autoplay: true, drag: false, autoplayTimeout: 3000, smartSpeed:700, arrows: false, dots: false, items: 1, fade: true }); $('.production .production-item-name').on('mouseenter', function(event) { var index = $('.production .production-item-name').index($(this)); productionCarousel.trigger('to.owl.carousel', index); productionCarousel.trigger('stop.owl.autoplay'); }); $('.production .production-item-name').on('mouseleave', function(event) { productionCarousel.trigger('play.owl.autoplay'); }); var productImages = $('.product-images-carousel'); var productMiniImages = $('.product-mini-images-carousel'); var productImagesCarousel = productImages.owlCarousel({ loop: false, arrows: false, dots: false, items: 1, smartSpeed: 500 }); var productMiniImagesCarousel = productMiniImages.owlCarousel({ loop: false, arrows: false, nav: true, navText : ['<svg width="30" height="30"><use href="#angle-left"></use></svg>', '<svg width="30" height="30"><use href="#angle-right"></use></svg>'], dots: false, items: 4, smartSpeed: 500, margin: 5 }); var currentImageIndex = 0; productMiniImages.find('.product-image').eq(currentImageIndex).addClass('active'); productMiniImages.find('.product-image').hover(function(event) { var index = productMiniImages.find('.product-image').index($(this)); productImagesCarousel.trigger('to.owl.carousel', index); if (currentImageIndex != index) { productMiniImages.find('.product-image').eq(currentImageIndex).removeClass('active'); $(this).addClass('active'); currentImageIndex = index; } }, function(event) {}); $('.scroll-top-btn').click(function(event) { window.scrollTo({ top: 0, behavior: 'smooth' }); }); }); window.addEventListener('scroll', function(argument) { if ($(window).scrollTop() > 100) { $('.scroll-top-btn').addClass('visible'); } else { $('.scroll-top-btn').removeClass('visible'); } if ($(window).scrollTop() > $('header .header-top').outerHeight()) { if (!$('header').hasClass('fixed')) { var headerHeight = $('header').outerHeight(); if ($(window).width() >= 768) { headerHeight -= 15; } $('header').css('height', headerHeight + 'px'); $('header').addClass('fixed'); } } else { $('header').removeClass('fixed'); $('header').css('height', ''); } var block = $('.main-page .production'); if (block.length == 0) { return; } var height = block.height(); var top = ($(window).scrollTop() - block.offset().top) / 3; block.find('.parallax-background').css( 'transform', 'translateY('+ top +'px)' ); });
module.exports = new Date(2018, 7, 19)
import React from 'react'; import { graphql, useStaticQuery } from 'gatsby'; /** * Higher order component wraps layout to track page * @param {Component} Layout */ const withReleaseInfo = (Component) => { function ReleaseInfoHOC(props) { const data = useStaticQuery(graphql` query { gitBranch(current: { eq: true }) { ...GitInfo } } `); return <Component release={data.gitBranch.commit} {...props} />; } return ReleaseInfoHOC; }; export default withReleaseInfo;
const path = require('path') const { createIO } = require('../io') const io = createIO() const directoryPath = process.cwd() const packageJsonPath = path.resolve(directoryPath, 'package.json') const errFilePath = path.resolve(directoryPath, 'package.err') const newFilePath = path.resolve(directoryPath, 'newfile.txt') const filesInDirectory = [ path.resolve(directoryPath, '.gitignore'), path.resolve(directoryPath, 'package.json'), path.resolve(directoryPath, 'package-lock.json'), ] test('Test readFile scenarios', () => { expect(io.File.readFile(packageJsonPath)).not.toBe(null) expect(() => { io.File.readFile(directoryPath) }).toThrow(io.errorMessages.pathIsNotFile) expect(() => { io.File.readFile(errFilePath) }).toThrow(io.errorMessages.invalidPath) expect(() => { io.File.readFile() }).toThrow(io.errorMessages.invalidPath) expect(() => { io.File.readFile(5) }).toThrow(io.errorMessages.invalidPath) expect(() => { io.File.readFile({}) }).toThrow(io.errorMessages.invalidPath) }) test('Test isFile method', () => { expect(io.File.isFile(packageJsonPath)).toBe(true) expect(io.File.isFile(directoryPath)).toBe(false) expect(() => { io.File.isFile(errFilePath) }).toThrow(io.errorMessages.invalidPath) expect(() => { io.File.isFile() }).toThrow(io.errorMessages.invalidPath) expect(() => { io.File.isFile(5) }).toThrow(io.errorMessages.invalidPath) expect(() => { io.File.isFile({}) }).toThrow(io.errorMessages.invalidPath) }) test('Test isDirectory method', () => { expect(io.Directory.isDirectory(packageJsonPath)).toBe(false) expect(io.Directory.isDirectory(directoryPath)).toBe(true) expect(() => { io.Directory.isDirectory(errFilePath) }).toThrow(io.errorMessages.invalidPath) expect(() => { io.Directory.isDirectory() }).toThrow(io.errorMessages.invalidPath) expect(() => { io.Directory.isDirectory(5) }).toThrow(io.errorMessages.invalidPath) expect(() => { io.Directory.isDirectory({}) }).toThrow(io.errorMessages.invalidPath) }) test('Test getFilesFromDirectory method', () => { // Sorting arrays because 'toEqual' takes the items order in consideration expect(io.File.getFilesFromDirectory(directoryPath).sort()).toEqual(filesInDirectory.sort()) expect(() => { io.File.getFilesFromDirectory(errFilePath) }).toThrow(io.errorMessages.invalidPath) expect(() => { io.File.getFilesFromDirectory() }).toThrow(io.errorMessages.invalidPath) expect(() => { io.File.getFilesFromDirectory(5) }).toThrow(io.errorMessages.invalidPath) expect(() => { io.File.getFilesFromDirectory({}) }).toThrow(io.errorMessages.invalidPath) }) test('Test createFileMethod', () => { expect(() => { io.File.createFile(newFilePath, null) }).toThrow(io.errorMessages.invalidBuffer) expect(() => { io.File.createFile(newFilePath, 5) }).toThrow(io.errorMessages.invalidBuffer) expect(() => { io.File.createFile(newFilePath, 'buffer') }).toThrow(io.errorMessages.invalidBuffer) })
(function () { module("ComboBox AngularJS integration", { teardown: function() { kendo.destroy(QUnit.fixture); } }); ngTest("combobox recognizes selected primitive items with k-ng-model", 1, function() { angular.module("kendo.tests").controller("mine", function($scope) { $scope.colors = [ "red", "green", "blue" ]; $scope.selectedColor = "red"; }); QUnit.fixture.html('<div ng-controller=mine><select kendo-combo-box k-ng-model=selectedColor k-data-source=colors></select></div>'); }, function() { equal(QUnit.fixture.find("select").getKendoComboBox().value(), "red"); }); ngTest("combobox recognizes custom primitive with k-ng-model", 1, function() { angular.module("kendo.tests").controller("mine", function($scope) { $scope.colors = [ "red", "green", "blue" ]; $scope.selectedColor = "black"; }); QUnit.fixture.html('<div ng-controller=mine><select kendo-combo-box k-ng-model=selectedColor k-data-source=colors></select></div>'); }, function() { equal(QUnit.fixture.find("select").getKendoComboBox().value(), "black"); }); ngTest("combobox recognizes selected object items with k-ng-model", 1, function() { angular.module("kendo.tests").controller("mine", function($scope) { $scope.colors = [ { color: "red" }, { color: "green" }, { color: "blue" } ]; $scope.selectedColor = $scope.colors[0]; }); QUnit.fixture.html('<div ng-controller=mine><select kendo-combo-box k-ng-model=selectedColor k-data-source=colors k-data-value-field="\'color\'"></select></div>'); }, function() { equal(JSON.stringify(QUnit.fixture.find("select").getKendoComboBox().dataItem()), JSON.stringify({ color: "red" })); }); ngTest("combobox works with data-value-primitive in k-ng-model", 1, function() { angular.module("kendo.tests").controller("mine", function($scope) { $scope.colors = [ { color: "red" }, { color: "green" }, { color: "blue" } ]; $scope.selectedColor = "red"; }); QUnit.fixture.html('<div ng-controller=mine><select kendo-combo-box k-value-primitive="true" k-ng-model=selectedColor k-data-source=colors k-data-value-field="\'color\'"></select></div>'); }, function() { equal(QUnit.fixture.find("select").getKendoComboBox().value(), "red"); }); ngTest("combobox works with data-value-primitive and custom value in k-ng-model", 1, function() { angular.module("kendo.tests").controller("mine", function($scope) { $scope.colors = [ { color: "red" }, { color: "green" }, { color: "blue" } ]; $scope.selectedColor = "black"; }); QUnit.fixture.html('<div ng-controller=mine><select kendo-combo-box k-value-primitive="true" k-ng-model=selectedColor k-data-source=colors k-data-value-field="\'color\'"></select></div>'); }, function() { equal(QUnit.fixture.find("select").getKendoComboBox().value(), "black"); }); ngTest("combobox returns objects to model", 1, function() { angular.module("kendo.tests").controller("mine", function($scope) { $scope.colors = [ { color: "red" }, { color: "green" }, { color: "blue" } ]; $scope.selectedColor = $scope.colors[0]; }); QUnit.fixture.html('<div ng-controller=mine><select kendo-combo-box k-ng-model=selectedColor k-data-source=colors k-data-value-field="\'color\'"></select></div>'); }, function() { var combobox = QUnit.fixture.find("select").getKendoComboBox(); var scope = combobox.element.scope(); combobox.value('blue'); combobox.trigger('change'); equal(JSON.stringify(scope.selectedColor), JSON.stringify({ color: 'blue' })); }); ngTest("combobox returns null when custom value", 1, function() { angular.module("kendo.tests").controller("mine", function($scope) { $scope.colors = [ { color: "red" }, { color: "green" }, { color: "blue" } ]; $scope.selectedColor = $scope.colors[0]; }); QUnit.fixture.html('<div ng-controller=mine><select kendo-combo-box k-ng-model=selectedColor k-data-source=colors k-data-value-field="\'color\'"></select></div>'); }, function() { var combobox = QUnit.fixture.find("select").getKendoComboBox(); var scope = combobox.element.scope(); combobox.value('black'); combobox.trigger('change'); equal(scope.selectedColor, null); }); ngTest("combobox returns primitives to model with primitive", 1, function() { angular.module("kendo.tests").controller("mine", function($scope) { $scope.colors = [ { color: "red" }, { color: "green" }, { color: "blue" } ]; $scope.selectedColor = "red"; }); QUnit.fixture.html('<div ng-controller=mine><select kendo-combo-box k-value-primitive="true" k-ng-model=selectedColor k-data-source=colors k-data-value-field="\'color\'"></select></div>'); }, function() { var combobox = QUnit.fixture.find("select").getKendoComboBox(); var scope = combobox.element.scope(); combobox.value('blue'); combobox.trigger("change"); equal(JSON.stringify(scope.selectedColor), JSON.stringify('blue')); }); })();
module.exports = { /* |-------------------------------------------------------------------------- | Authenticator |-------------------------------------------------------------------------- | | Authentication is a combination of serializer and scheme with extra | config to define on how to authenticate a user. | | Available Schemes - basic, session, jwt, api | Available Serializers - lucid, database | */ authenticator: 'session', /* |-------------------------------------------------------------------------- | Session |-------------------------------------------------------------------------- | | Session authenticator makes use of sessions to authenticate a user. | Session authentication is always persistent. | */ session: { serializer: 'lucid', model: 'App/Models/User', scheme: 'session', uid: 'email', password: 'password' }, /* |-------------------------------------------------------------------------- | Basic Auth |-------------------------------------------------------------------------- | | The basic auth authenticator uses basic auth header to authenticate a | user. | | NOTE: | This scheme is not persistent and users are supposed to pass | login credentials on each request. | */ basic: { serializer: 'lucid', model: 'App/Models/User', scheme: 'basic', uid: 'email', password: 'password' }, /* |-------------------------------------------------------------------------- | Jwt |-------------------------------------------------------------------------- | | The jwt authenticator works by passing a jwt token on each HTTP request | via HTTP `Authorization` header. | */ jwt: { serializer: 'lucid', model: 'App/Models/User', scheme: 'jwt', uid: 'email', password: 'password', options: { secret: 'self::app.appKey' } } }
const makeClosure = require('./make-closure'); makeClosure('dist/global/experimental.umd.js');
dojo.provide("dojox.lang.aspect"); (function(){ var d = dojo, aop = dojox.lang.aspect, ap = Array.prototype, contextStack = [], context; // this class implements a topic-based double-linked list var Advice = function(){ this.next_before = this.prev_before = this.next_around = this.prev_around = this.next_afterReturning = this.prev_afterReturning = this.next_afterThrowing = this.prev_afterThrowing = this; this.counter = 0; }; d.extend(Advice, { add: function(advice){ var dyn = d.isFunction(advice), node = {advice: advice, dynamic: dyn}; this._add(node, "before", "", dyn, advice); this._add(node, "around", "", dyn, advice); this._add(node, "after", "Returning", dyn, advice); this._add(node, "after", "Throwing", dyn, advice); ++this.counter; return node; }, _add: function(node, topic, subtopic, dyn, advice){ var full = topic + subtopic; if(dyn || advice[topic] || (subtopic && advice[full])){ var next = "next_" + full, prev = "prev_" + full; (node[prev] = this[prev])[next] = node; (node[next] = this)[prev] = node; } }, remove: function(node){ this._remove(node, "before"); this._remove(node, "around"); this._remove(node, "afterReturning"); this._remove(node, "afterThrowing"); --this.counter; }, _remove: function(node, topic){ var next = "next_" + topic, prev = "prev_" + topic; if(node[next]){ node[next][prev] = node[prev]; node[prev][next] = node[next]; } }, isEmpty: function(){ return !this.counter; } }); var getDispatcher = function(){ return function(){ var self = arguments.callee, // the join point advices = self.advices, // list of advices for this joinpoint ret, i, a, e, t; // push context if(context){ contextStack.push(context); } context = { instance: this, // object instance joinPoint: self, // join point depth: contextStack.length, // current level of depth starting from 0 around: advices.prev_around, // pointer to the current around advice dynAdvices: [], // array of dynamic advices if any dynIndex: 0 // index of a dynamic advice }; try{ // process before events for(i = advices.prev_before; i != advices; i = i.prev_before){ if(i.dynamic){ // instantiate a dynamic advice context.dynAdvices.push(a = new i.advice(context)); if(t = a.before){ // intentional assignment t.apply(a, arguments); } }else{ t = i.advice; t.before.apply(t, arguments); } } // process around and after events try{ // call the around advice or the original method ret = (advices.prev_around == advices ? self.target : aop.proceed).apply(this, arguments); }catch(e){ // process after throwing and after events context.dynIndex = context.dynAdvices.length; for(i = advices.next_afterThrowing; i != advices; i = i.next_afterThrowing){ a = i.dynamic ? context.dynAdvices[--context.dynIndex] : i.advice; if(t = a.afterThrowing){ // intentional assignment t.call(a, e); } if(t = a.after){ // intentional assignment t.call(a); } } // continue the exception processing throw e; } // process after returning and after events context.dynIndex = context.dynAdvices.length; for(i = advices.next_afterReturning; i != advices; i = i.next_afterReturning){ a = i.dynamic ? context.dynAdvices[--context.dynIndex] : i.advice; if(t = a.afterReturning){ // intentional assignment t.call(a, ret); } if(t = a.after){ // intentional assignment t.call(a); } } // process dojo.connect() listeners var ls = self._listeners; for(i in ls){ if(!(i in ap)){ ls[i].apply(this, arguments); } } }finally{ // destroy dynamic advices for(i = 0; i < context.dynAdvices.length; ++i){ a = context.dynAdvices[i]; if(a.destroy){ a.destroy(); } } // pop context context = contextStack.length ? contextStack.pop() : null; } return ret; }; }; aop.advise = function(/*Object*/ obj, /*String|RegExp|Array*/ method, /*Object|Function|Array*/ advice ){ // summary: // Attach AOP-style advices to a method. // // description: // Attaches AOP-style advices to a method. Can attach several // advices at once and operate on several methods of an object. // The latter is achieved when a RegExp is specified as // a method name, or an array of strings and regular expressions // is used. In this case all functional methods that // satisfy the RegExp condition are processed. This function // returns a handle, which can be used to unadvise, or null, // if advising has failed. // // This function is a convenience wrapper for // dojox.lang.aspect.adviseRaw(). // // obj: // A source object for the advised function. Cannot be a DOM node. // If this object is a constructor, its prototype is advised. // // method: // A string name of the function in obj. In case of RegExp all // methods of obj matching the regular expression are advised. // // advice: // An object, which defines advises, or a function, which // returns such object, or an array of previous items. // The advice object can define following member functions: // before, around, afterReturning, afterThrowing, after. // If the function is supplied, it is called with a context // object once per call to create a temporary advice object, which // is destroyed after the processing. The temporary advice object // can implement a destroy() method, if it wants to be called when // not needed. if(typeof obj != "object"){ obj = obj.prototype; } var methods = []; if(!(method instanceof Array)){ method = [method]; } // identify advised methods for(var j = 0; j < method.length; ++j){ var t = method[j]; if(t instanceof RegExp){ for(var i in obj){ if(d.isFunction(obj[i]) && t.test(i)){ methods.push(i); } } }else{ if(d.isFunction(obj[t])){ methods.push(t); } } } if(!d.isArray(advice)){ advice = [advice]; } return aop.adviseRaw(obj, methods, advice); // Object }; aop.adviseRaw = function(/*Object*/ obj, /*Array*/ methods, /*Array*/ advices ){ // summary: // Attach AOP-style advices to methods. // // description: // Attaches AOP-style advices to object's methods. Can attach several // advices at once and operate on several methods of the object. // The latter is achieved when a RegExp is specified as // a method name. In this case all functional methods that // satisfy the RegExp condition are processed. This function // returns a handle, which can be used to unadvise, or null, // if advising has failed. // // obj: // A source object for the advised function. // Cannot be a DOM node. // // methods: // An array of method names (strings) to be advised. // // advices: // An array of advices represented by objects or functions that // return such objects on demand during the event processing. // The advice object can define following member functions: // before, around, afterReturning, afterThrowing, after. // If the function is supplied, it is called with a context // object once per call to create a temporary advice object, which // is destroyed after the processing. The temporary advice object // can implement a destroy() method, if it wants to be called when // not needed. if(!methods.length || !advices.length){ return null; } // attach advices var m = {}, al = advices.length; for(var i = methods.length - 1; i >= 0; --i){ var name = methods[i], o = obj[name], ao = new Array(al), t = o.advices; // create a stub, if needed if(!t){ var x = obj[name] = getDispatcher(); x.target = o.target || o; x.targetName = name; x._listeners = o._listeners || []; x.advices = new Advice; t = x.advices; } // attach advices for(var j = 0; j < al; ++j){ ao[j] = t.add(advices[j]); } m[name] = ao; } return [obj, m]; // Object }; aop.unadvise = function(/*Object*/ handle){ // summary: // Detach previously attached AOP-style advices. // // handle: // The object returned by dojox.lang.aspect.advise(). if(!handle){ return; } var obj = handle[0], methods = handle[1]; for(var name in methods){ var o = obj[name], t = o.advices, ao = methods[name]; for(var i = ao.length - 1; i >= 0; --i){ t.remove(ao[i]); } if(t.isEmpty()){ // check if we can remove all stubs var empty = true, ls = o._listeners; if(ls.length){ for(i in ls){ if(!(i in ap)){ empty = false; break; } } } if(empty){ // revert to the original method obj[name] = o.target; }else{ // replace with the dojo.connect() stub var x = obj[name] = d._listener.getDispatcher(); x.target = o.target; x._listeners = ls; } } } }; aop.getContext = function(){ // summary: // Returns the context information for the advice in effect. return context; // Object }; aop.getContextStack = function(){ // summary: // Returns the context stack, which reflects executing advices // up to this point. The array is ordered from oldest to newest. // In order to get the active context use dojox.lang.aspect.getContext(). return contextStack; // Array }; aop.proceed = function(){ // summary: // Call the original function (or the next level around advice) in an around advice code. // // description: // Calls the original function (or the next level around advice). // Accepts and passes on any number of arguments, and returns a value. // This function is valid only in the content of around calls. var joinPoint = context.joinPoint, advices = joinPoint.advices; for(var c = context.around; c != advices; c = context.around){ context.around = c.prev_around; // advance the pointer if(c.dynamic){ var a = context.dynAdvices[context.dynIndex++], t = a.around; if(t){ return t.apply(a, arguments); } }else{ return c.advice.around.apply(c.advice, arguments); } } return joinPoint.target.apply(context.instance, arguments); }; })(); /* Aspect = { before: function(arguments){...}, around: function(arguments){...returns value...}, afterReturning: function(ret){...}, afterThrowing: function(excp){...}, after: function(){...} }; Context = { instance: ..., // the instance we operate on joinPoint: ..., // Object (see below) depth: ... // current depth of the context stack }; JoinPoint = { target: ..., // the original function being wrapped targetName: ... // name of the method }; */
/*globals define, $, _, WebGMEGlobal*/ /*jshint browser: true*/ /** * @author rkereskenyi / https://github.com/rkereskenyi */ define([ 'js/Constants', 'js/NodePropertyNames', 'js/RegistryKeys', 'js/Utils/DisplayFormat', 'js/Decorators/DecoratorWithPortsAndPointerHelpers.Base', 'js/Widgets/DiagramDesigner/DiagramDesignerWidget.Constants', 'text!./default.svg' ], function (CONSTANTS, nodePropertyNames, REGISTRY_KEYS, displayFormat, DecoratorWithPortsAndPointerHelpers, DiagramDesignerWidgetConstants, DefaultSvgTemplate) { 'use strict'; var SVGDecoratorCore, ABSTRACT_CLASS = 'abstract', FILL_COLOR_CLASS = 'fill-color', BORDER_COLOR_CLASS = 'border-color', TEXT_COLOR_CLASS = 'text-color'; /** * Contains downloaded svg elements from the server. * @type {{}} * @private */ var SVG_CACHE = {}; /** * Svg element that can be used as a placeholder for the icon if the icon does not exist on the server. * @type {*|jQuery} * @private */ var defaultSVG = $(DefaultSvgTemplate); SVGDecoratorCore = function () { DecoratorWithPortsAndPointerHelpers.apply(this, []); this.svgCache = SVG_CACHE; }; _.extend(SVGDecoratorCore.prototype, DecoratorWithPortsAndPointerHelpers.prototype); SVGDecoratorCore.prototype._initializeVariables = function (params) { this.name = ''; this.formattedName = ''; this.$name = undefined; this.$replaceable = undefined; //Get custom data from svg if (params.data) { this.customData = []; //list of data to retrieve var i = params.data.length; while (i--) { if (this[params.data[i]] === undefined) {//Don't overwrite anything meaningful //add params.data to custom params.data list to retrieve from svg this.customData.push(params.data[i]); this[params.data[i]] = null; } } } if (params.connectors === true) { this._displayConnectors = true; } }; /**** Override from *.WidgetDecoratorBase ****/ SVGDecoratorCore.prototype.doSearch = function (searchDesc) { var searchText = searchDesc.toString(), gmeId = (this._metaInfo && this._metaInfo[CONSTANTS.GME_ID]) || ''; return (this.formattedName && this.formattedName.toLowerCase().indexOf(searchText.toLowerCase()) !== -1) || (gmeId.indexOf(searchText) > -1); }; SVGDecoratorCore.prototype._renderContent = function () { //render GME-ID in the DOM, for debugging this.$el.attr({'data-id': this._metaInfo[CONSTANTS.GME_ID]}); /* BUILD UI*/ //find placeholders this.$name = this.$el.find('.name'); this.$svgContent = this.$el.find('.svg-content'); this._update(); }; SVGDecoratorCore.prototype._update = function () { this._updateSVGContent(); this._updateColors(); this._updateName(); this._updateAbstract(); this._updatePorts();//Will be overridden by ports class if extended this._updateIsReplaceable(); }; SVGDecoratorCore.prototype._updateColors = function () { var svg = this.$svgElement, fillColorElements = svg.find('.' + FILL_COLOR_CLASS), borderColorElements = svg.find('.' + BORDER_COLOR_CLASS), textColorElements = svg.find('.' + TEXT_COLOR_CLASS); this._getNodeColorsFromRegistry(); if (this.fillColor) { fillColorElements.css({fill: this.fillColor}); } else { fillColorElements.css({fill: ''}); } if (this.borderColor) { borderColorElements.css({stroke: this.borderColor}); } else { borderColorElements.css({stroke: ''}); } if (this.textColor) { this.$el.css({color: this.textColor}); textColorElements.css({fill: this.textColor}); } else { this.$el.css({color: ''}); textColorElements.css({fill: ''}); } }; SVGDecoratorCore.prototype._getNodeColorsFromRegistry = function () { var objID = this._metaInfo[CONSTANTS.GME_ID]; this.fillColor = this.preferencesHelper.getRegistry(objID, REGISTRY_KEYS.COLOR, true); this.borderColor = this.preferencesHelper.getRegistry(objID, REGISTRY_KEYS.BORDER_COLOR, true); this.textColor = this.preferencesHelper.getRegistry(objID, REGISTRY_KEYS.TEXT_COLOR, true); }; /***** UPDATE THE NAME OF THE NODE *****/ SVGDecoratorCore.prototype._updateName = function () { var client = this._control._client, nodeObj = client.getNode(this._metaInfo[CONSTANTS.GME_ID]), noName = '(N/A)'; if (nodeObj) { //this.name = nodeObj.getAttribute(nodePropertyNames.Attributes.name); this.name = nodeObj.getFullyQualifiedName(); this.formattedName = displayFormat.resolve(nodeObj); } else { this.name = ''; this.formattedName = noName; } this.$name.text(this.formattedName); this.$name.attr('title', this.formattedName); if(this.$svgElement.data('hidename') === true){ this.$name.hide(); } else { this.$name.show(); } }; /***** UPDATE THE ABSTRACTNESS OF THE NODE *****/ SVGDecoratorCore.prototype._updateAbstract = function () { var client = this._control._client, nodeObj = client.getNode(this._metaInfo[CONSTANTS.GME_ID]); if (nodeObj) { if (nodeObj.getRegistry(REGISTRY_KEYS.IS_ABSTRACT) === true) { this.$el.addClass(ABSTRACT_CLASS); } else { this.$el.removeClass(ABSTRACT_CLASS); } } else { this.$el.removeClass(ABSTRACT_CLASS); } }; /***** UPDATE THE SVG ICON OF THE NODE *****/ SVGDecoratorCore.prototype._updateSVGContent = function () { var client = this._control._client, nodeObj = client.getNode(this._metaInfo[CONSTANTS.GME_ID]), svgContent; if (nodeObj) { //set new content this.$svgContent.empty(); this.$svgContent.removeClass(); this.$svgContent.addClass('svg-content'); //remove existing connectors (if any) this.$el.find('> .' + DiagramDesignerWidgetConstants.CONNECTOR_CLASS).remove(); svgContent = WebGMEGlobal.SvgManager.getSvgElement(nodeObj, REGISTRY_KEYS.SVG_ICON); if (svgContent) { this.$svgElement = svgContent; this._discoverCustomConnectionAreas(this.$svgElement); } else { delete this._customConnectionAreas; this.$svgElement = defaultSVG.clone(); } } else { delete this._customConnectionAreas; this.$svgElement = defaultSVG.clone(); } this._generateConnectors(); this.$svgContent.append(this.$svgElement); }; /***** FUNCTIONS TO OVERRIDE *****/ SVGDecoratorCore.prototype._updateExtras = function () { //Can be overridden for custom functionality }; /***** PORT FUNCTIONALITY *****/ //Overridden in SVGDecorator.Ports.js SVGDecoratorCore.prototype._updatePorts = function () { //If no ports in model, does nothing }; SVGDecoratorCore.prototype._fixPortContainerPosition = function () { //If no ports in model, does nothing }; /***** CONNECTION FUNCTIONALITY *****/ //Overridden in SVGDecorator.Connection.js SVGDecoratorCore.prototype._discoverCustomConnectionAreas = function () { //If no connections in model, does nothing }; //Overridden in SVGDecorator.Connection.js SVGDecoratorCore.prototype._generateConnectors = function () { //If no connections in model, does nothing }; SVGDecoratorCore.prototype._updateIsReplaceable = function () { if (this._isReplaceable()) { this.$replaceable = this.$el.find('.replaceable'); if (this.$replaceable.length === 0) { this.$replaceable = $('<div class="replaceable">' + '<i class="glyphicon glyphicon-transfer" title="This node is replaceable"></i></div>'); this.$el.append(this.$replaceable); } } else { if (this.$replaceable) { this.$replaceable.remove(); this.$replaceable = undefined; } } }; return SVGDecoratorCore; });
module.exports = { env: { browser: true, es6: true, }, extends: ['eslint:recommended', 'plugin:@typescript-eslint/eslint-recommended'], globals: { Atomics: 'readonly', SharedArrayBuffer: 'readonly', }, parser: '@typescript-eslint/parser', parserOptions: { ecmaVersion: 2018, sourceType: 'module', }, plugins: ['@typescript-eslint'], rules: { 'no-var': ['error'], 'prefer-const': ['error'], 'no-unused-vars': [ 'error', { args: 'none', vars: 'all', }, ], }, };
import getISOWeekYear from '../getISOWeekYear/index.js' import startOfISOWeek from '../startOfISOWeek/index.js' import requiredArgs from '../_lib/requiredArgs/index.js' /** * @name lastDayOfISOWeekYear * @category ISO Week-Numbering Year Helpers * @summary Return the last day of an ISO week-numbering year for the given date. * * @description * Return the last day of an ISO week-numbering year, * which always starts 3 days before the year's first Thursday. * The result will be in the local timezone. * * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date * * ### v2.0.0 breaking changes: * * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). * * - The function was renamed from `lastDayOfISOYear` to `lastDayOfISOWeekYear`. * "ISO week year" is short for [ISO week-numbering year](https://en.wikipedia.org/wiki/ISO_week_date). * This change makes the name consistent with * locale-dependent week-numbering year helpers, e.g., `getWeekYear`. * * @param {Date|Number} date - the original date * @returns {Date} the end of an ISO week-numbering year * @throws {TypeError} 1 argument required * * @example * // The last day of an ISO week-numbering year for 2 July 2005: * var result = lastDayOfISOWeekYear(new Date(2005, 6, 2)) * //=> Sun Jan 01 2006 00:00:00 */ export default function lastDayOfISOWeekYear(dirtyDate) { requiredArgs(1, arguments) var year = getISOWeekYear(dirtyDate) var fourthOfJanuary = new Date(0) fourthOfJanuary.setFullYear(year + 1, 0, 4) fourthOfJanuary.setHours(0, 0, 0, 0) var date = startOfISOWeek(fourthOfJanuary) date.setDate(date.getDate() - 1) return date }
/*! * jQuery JavaScript Library v1.9.0 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2012 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-1-14 */ (function (window, undefined) { "use strict"; var // A central reference to the root jQuery(document) rootjQuery, // The deferred used on DOM ready readyList, // Use the correct document accordingly with window argument (sandbox) document = window.document, location = window.location, // 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 = "1.9.0", // 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, // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/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 = /^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g, // 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 DOMContentLoaded = function () { if (document.addEventListener) { document.removeEventListener("DOMContentLoaded", DOMContentLoaded, false); jQuery.ready(); } else if (document.readyState === "complete") { // we're here because readyState === "complete" in oldIE // which is good enough for us to call the dom ready! document.detachEvent("onreadystatechange", DOMContentLoaded); 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) { // Handle the case where IE and Opera return items // by name instead of ID if (elem.id !== match[2]) { return rootjQuery.find(selector); } // Otherwise, we 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, // The number of elements contained in the matched element set size: function () { return this.length; }, 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({ 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; } // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if (!document.body) { return setTimeout(jQuery.ready); } // 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 || function (obj) { return jQuery.type(obj) === "array"; }, 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); } return typeof obj === "object" || typeof obj === "function" ? class2type[core_toString.call(obj)] || "object" : typeof obj; }, isPlainObject: function (obj) { // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if (!obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow(obj)) { return false; } try { // Not own constructor property must be Object if (obj.constructor && !core_hasOwn.call(obj, "constructor") && !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf")) { return false; } } catch (e) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for (key in obj) { } return key === undefined || core_hasOwn.call(obj, key); }, 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: function (data) { // Attempt to parse using the native JSON parser first if (window.JSON && window.JSON.parse) { return window.JSON.parse(data); } if (data === null) { return data; } if (typeof data === "string") { // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim(data); if (data) { // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if (rvalidchars.test(data.replace(rvalidescape, "@") .replace(rvalidtokens, "]") .replace(rvalidbraces, ""))) { return (new Function("return " + data))(); } } } jQuery.error("Invalid JSON: " + data); }, // Cross-browser xml parsing parseXML: function (data) { var xml, tmp; if (!data || typeof data !== "string") { return null; } try { if (window.DOMParser) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString(data, "text/xml"); } else { // IE xml = new ActiveXObject("Microsoft.XMLDOM"); xml.async = "false"; xml.loadXML(data); } } catch (e) { xml = undefined; } if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length) { jQuery.error("Invalid XML: " + data); } return xml; }, noop: function () { }, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function (data) { if (data && jQuery.trim(data)) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox (window.execScript || function (data) { window["eval"].call(window, data); })(data); } }, // 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; }, // Use native String.trim function wherever possible trim: core_trim && !core_trim.call("\uFEFF\xA0") ? function (text) { return text == null ? "" : core_trim.call(text); } : // Otherwise use our own trimming functionality function (text) { return text == null ? "" : (text + "").replace(rtrim, ""); }, // 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) { var len; if (arr) { if (core_indexOf) { return core_indexOf.call(arr, elem, i); } len = arr.length; i = i ? i < 0 ? Math.max(0, len + i) : i : 0; for (; i < len; i++) { // Skip accessing in sparse arrays if (i in arr && arr[i] === elem) { return i; } } } return -1; }, 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: function () { return (new Date()).getTime(); } }); 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); // Standards-based browsers support DOMContentLoaded } else if (document.addEventListener) { // Use the handy event callback document.addEventListener("DOMContentLoaded", DOMContentLoaded, false); // A fallback to window.onload, that will always work window.addEventListener("load", jQuery.ready, false); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent("onreadystatechange", DOMContentLoaded); // A fallback to window.onload, that will always work window.attachEvent("onload", jQuery.ready); // If IE and not a frame // continually check to see if the document is ready var top = false; try { top = window.frameElement == null && document.documentElement; } catch (e) { } if (top && top.doScroll) { (function doScrollCheck() { if (!jQuery.isReady) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll("left"); } catch (e) { return setTimeout(doScrollCheck, 50); } // and execute any waiting functions jQuery.ready(); } })(); } } } 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); // 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; }, // Control if a given callback is in the list has: function (fn) { return jQuery.inArray(fn, list) > -1; }, // Remove all callbacks from the list empty: function () { list = []; 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) { args = args || []; args = [context, args.slice ? args.slice() : args]; if (list && (!fired || stack)) { 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 () { var support, all, a, select, opt, input, fragment, eventName, isSupported, i, div = document.createElement("div"); // Setup div.setAttribute("className", "t"); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; // Support tests won't run in some limited or non-browser environments all = div.getElementsByTagName("*"); a = div.getElementsByTagName("a")[0]; if (!all || !a || !all.length) { return {}; } // First batch of tests select = document.createElement("select"); opt = select.appendChild(document.createElement("option")); input = div.getElementsByTagName("input")[0]; a.style.cssText = "top:1px;float:left;opacity:.5"; support = { // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) getSetAttribute: div.className !== "t", // IE strips leading whitespace when .innerHTML is used leadingWhitespace: div.firstChild.nodeType === 3, // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables tbody: !div.getElementsByTagName("tbody").length, // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE htmlSerialize: !!div.getElementsByTagName("link").length, // Get the style information from getAttribute // (IE uses .cssText instead) style: /top/.test(a.getAttribute("style")), // Make sure that URLs aren't manipulated // (IE normalizes it by default) hrefNormalized: a.getAttribute("href") === "/a", // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 opacity: /^0.5/.test(a.style.opacity), // Verify style float existence // (IE uses styleFloat instead of cssFloat) cssFloat: !!a.style.cssFloat, // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere) checkOn: !!input.value, // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) optSelected: opt.selected, // Tests for enctype support on a form (#6743) enctype: !!document.createElement("form").enctype, // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works html5Clone: document.createElement("nav").cloneNode(true).outerHTML !== "<:nav></:nav>", // jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode boxModel: document.compatMode === "CSS1Compat", // Will be defined later deleteExpando: true, noCloneEvent: true, inlineBlockNeedsLayout: false, shrinkWrapBlocks: false, reliableMarginRight: true, boxSizingReliable: true, pixelPosition: false }; // Make sure checked status is properly cloned 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; // Support: IE<9 try { delete div.test; } catch (e) { support.deleteExpando = false; } // Check if we can trust getAttribute("value") input = document.createElement("input"); input.setAttribute("value", ""); support.input = input.getAttribute("value") === ""; // Check if an input maintains its value after becoming a radio input.value = "t"; input.setAttribute("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 = document.createDocumentFragment(); fragment.appendChild(input); // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode(true).cloneNode(true).lastChild.checked; // Support: IE<9 // Opera does not clone events (and typeof div.attachEvent === undefined). // IE9-10 clones events bound via attachEvent, but they don't trigger with .click() if (div.attachEvent) { div.attachEvent("onclick", function () { support.noCloneEvent = false; }); div.cloneNode(true).click(); } // Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event) // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP), test/csp.php for (i in { submit: true, change: true, focusin: true }) { div.setAttribute(eventName = "on" + i, "t"); support[i + "Bubbles"] = eventName in window || div.attributes[eventName].expando === false; } 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, tds, divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-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"; body.appendChild(container).appendChild(div); // Support: IE8 // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>"; tds = div.getElementsByTagName("td"); tds[0].style.cssText = "padding:0;margin:0;border:0;display:none"; isSupported = (tds[0].offsetHeight === 0); tds[0].style.display = ""; tds[1].style.display = "none"; // Support: IE8 // Check if empty table cells still have offsetWidth/Height support.reliableHiddenOffsets = isSupported && (tds[0].offsetHeight === 0); // Check box-sizing and margin behavior div.innerHTML = ""; div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;"; support.boxSizing = (div.offsetWidth === 4); support.doesNotIncludeMarginInBodyOffset = (body.offsetTop !== 1); // 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"; // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // Fails in WebKit before Feb 2011 nightlies // 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); } if (typeof div.style.zoom !== "undefined") { // Support: IE<8 // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout div.innerHTML = ""; div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; support.inlineBlockNeedsLayout = (div.offsetWidth === 3); // Support: IE6 // Check if elements with layout shrink-wrap their children div.style.display = "block"; div.innerHTML = "<div></div>"; div.firstChild.style.width = "5px"; support.shrinkWrapBlocks = (div.offsetWidth !== 3); // Prevent IE 6 from affecting layout for positioned elements #11048 // Prevent IE from shrinking the body in IE 7 mode #12869 body.style.zoom = 1; } body.removeChild(container); // Null elements to avoid leaks in IE container = div = tds = marginDiv = null; }); // Null elements to avoid leaks in IE all = select = fragment = opt = a = input = null; return support; })(); var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; function internalData(elem, name, data, pvt /* Internal Use Only */) { if (!jQuery.acceptData(elem)) { return; } var thisCache, ret, internalKey = jQuery.expando, getByName = typeof name === "string", // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[internalKey] : elem[internalKey] && internalKey; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ((!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined) { return; } if (!id) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if (isNode) { elem[internalKey] = id = core_deletedIds.pop() || jQuery.guid++; } else { id = internalKey; } } if (!cache[id]) { cache[id] = {}; // Avoids exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify if (!isNode) { cache[id].toJSON = jQuery.noop; } } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if (typeof name === "object" || typeof name === "function") { if (pvt) { cache[id] = jQuery.extend(cache[id], name); } else { cache[id].data = jQuery.extend(cache[id].data, name); } } thisCache = cache[id]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if (!pvt) { if (!thisCache.data) { thisCache.data = {}; } thisCache = thisCache.data; } if (data !== undefined) { thisCache[jQuery.camelCase(name)] = data; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if (getByName) { // First Try to find as-is property data ret = thisCache[name]; // Test for null|undefined property data if (ret == null) { // Try to find the camelCased property ret = thisCache[jQuery.camelCase(name)]; } } else { ret = thisCache; } return ret; } function internalRemoveData(elem, name, pvt /* For internal use only */) { if (!jQuery.acceptData(elem)) { return; } var thisCache, i, l, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, id = isNode ? elem[jQuery.expando] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if (!cache[id]) { return; } if (name) { thisCache = pvt ? cache[id] : cache[id].data; if (thisCache) { // Support array or space separated string names for data keys if (!jQuery.isArray(name)) { // try the string as a key before any manipulation if (name in thisCache) { name = [name]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase(name); if (name in thisCache) { name = [name]; } else { name = name.split(" "); } } } else { // 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 = name.concat(jQuery.map(name, jQuery.camelCase)); } for (i = 0, l = name.length; i < l; i++) { delete thisCache[name[i]]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if (!(pvt ? isEmptyDataObject : jQuery.isEmptyObject)(thisCache)) { return; } } } // See jQuery.data for more information if (!pvt) { delete cache[id].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if (!isEmptyDataObject(cache[id])) { return; } } // Destroy the cache if (isNode) { jQuery.cleanData([elem], true); // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) } else if (jQuery.support.deleteExpando || cache != cache.window) { delete cache[id]; // When all else fails, null } else { cache[id] = null; } } jQuery.extend({ cache: {}, // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + (core_version + Math.random()).replace(/\D/g, ""), // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", "applet": true }, hasData: function (elem) { elem = elem.nodeType ? jQuery.cache[elem[jQuery.expando]] : elem[jQuery.expando]; return !!elem && !isEmptyDataObject(elem); }, data: function (elem, name, data) { return internalData(elem, name, data, false); }, removeData: function (elem, name) { return internalRemoveData(elem, name, false); }, // For internal use only. _data: function (elem, name, data) { return internalData(elem, name, data, true); }, _removeData: function (elem, name) { return internalRemoveData(elem, name, true); }, // A method for determining if a DOM node can handle the data expando acceptData: function (elem) { var noData = elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()]; // nodes accept data unless otherwise specified; rejection can be conditional return !noData || noData !== true && elem.getAttribute("classid") === noData; } }); 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 = jQuery.data(elem); if (elem.nodeType === 1 && !jQuery._data(elem, "parsedAttrs")) { attrs = elem.attributes; for (; i < attrs.length; i++) { name = attrs[i].name; if (!name.indexOf("data-")) { name = jQuery.camelCase(name.substring(5)); dataAttr(elem, name, data[name]); } } jQuery._data(elem, "parsedAttrs", true); } } return data; } // Sets multiple values if (typeof key === "object") { return this.each(function () { jQuery.data(this, key); }); } return jQuery.access(this, function (value) { if (value === undefined) { // Try to fetch any internally stored data first return elem ? dataAttr(elem, key, jQuery.data(elem, key)) : null; } this.each(function () { jQuery.data(this, key, value); }); }, null, value, arguments.length > 1, null, true); }, removeData: function (key) { return this.each(function () { jQuery.removeData(this, key); }); } }); function dataAttr(elem, key, data) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if (data === undefined && elem.nodeType === 1) { var 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) ? jQuery.parseJSON(data) : data; } catch (e) { } // Make sure we set the data so it isn't changed later jQuery.data(elem, key, data); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject(obj) { var name; for (name in obj) { // if the public data object is empty, the private is still empty if (name === "data" && jQuery.isEmptyObject(obj[name])) { continue; } if (name !== "toJSON") { return false; } } return true; } jQuery.extend({ queue: function (elem, type, data) { var queue; if (elem) { type = (type || "fx") + "queue"; queue = jQuery._data(elem, type); // Speed up dequeue by getting out quickly if this is just a lookup if (data) { if (!queue || jQuery.isArray(data)) { queue = jQuery._data(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--; } hooks.cur = fn; 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 jQuery._data(elem, key) || jQuery._data(elem, key, { empty: jQuery.Callbacks("once memory").add(function () { jQuery._removeData(elem, type + "queue"); jQuery._removeData(elem, 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 = jQuery._data(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]/g, rreturn = /\r/g, rfocusable = /^(?:input|select|textarea|button|object)$/i, rclickable = /^(?:a|area)$/i, rboolean = /^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i, ruseDefault = /^(?:checked|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute, getSetInput = jQuery.support.input; 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) { name = jQuery.propFix[name] || name; return this.each(function () { // try/catch handles cases where IE balks (such as removing a property on window) try { this[name] = undefined; delete this[name]; } catch (e) { } }); }, 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, isBool = typeof stateVal === "boolean"; 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), state = stateVal, classNames = value.match(core_rnotwhite) || []; while ((className = classNames[i++])) { // check each className given, space separated list state = isBool ? state : !self.hasClass(className); self[state ? "addClass" : "removeClass"](className); } // Toggle whole class name } else if (type === "undefined" || type === "boolean") { if (this.className) { // store className if set jQuery._data(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 ? "" : jQuery._data(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, self = jQuery(this); if (this.nodeType !== 1) { return; } if (isFunction) { val = value.call(this, i, self.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]; // oldIE 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 values = jQuery.makeArray(value); jQuery(elem).find("option").each(function () { this.selected = jQuery.inArray(jQuery(this).val(), values) >= 0; }); if (!values.length) { elem.selectedIndex = -1; } return values; } } }, attr: function (elem, name, value) { var ret, hooks, notxml, 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 === "undefined") { return jQuery.prop(elem, name, value); } notxml = nType !== 1 || !jQuery.isXMLDoc(elem); // All attributes are lowercase // Grab necessary hook if one is defined if (notxml) { name = name.toLowerCase(); hooks = jQuery.attrHooks[name] || (rboolean.test(name) ? boolHook : nodeHook); } if (value !== undefined) { if (value === null) { jQuery.removeAttr(elem, name); } else if (hooks && notxml && "set" in hooks && (ret = hooks.set(elem, value, name)) !== undefined) { return ret; } else { elem.setAttribute(name, value + ""); return value; } } else if (hooks && notxml && "get" in hooks && (ret = hooks.get(elem, name)) !== null) { return ret; } else { // In IE9+, Flash objects don't have .getAttribute (#12945) // Support: IE9+ if (typeof elem.getAttribute !== "undefined") { ret = elem.getAttribute(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 (rboolean.test(name)) { // Set corresponding property to false for boolean attributes // Also clear defaultChecked/defaultSelected (if appropriate) for IE<8 if (!getSetAttribute && ruseDefault.test(name)) { elem[jQuery.camelCase("default-" + name)] = elem[propName] = false; } else { elem[propName] = false; } // See #9699 for explanation of this approach (setting first, then removal) } else { jQuery.attr(elem, name, ""); } elem.removeAttribute(getSetAttribute ? name : propName); } } }, 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: { tabindex: "tabIndex", readonly: "readOnly", "for": "htmlFor", "class": "className", maxlength: "maxLength", cellspacing: "cellSpacing", cellpadding: "cellPadding", rowspan: "rowSpan", colspan: "colSpan", usemap: "useMap", frameborder: "frameBorder", contenteditable: "contentEditable" }, 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) { if (hooks && "set" in hooks && (ret = hooks.set(elem, value, name)) !== undefined) { return ret; } else { return (elem[name] = value); } } else { if (hooks && "get" in hooks && (ret = hooks.get(elem, name)) !== null) { return ret; } else { return elem[name]; } } }, propHooks: { tabIndex: { get: function (elem) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ var attributeNode = elem.getAttributeNode("tabindex"); return attributeNode && attributeNode.specified ? parseInt(attributeNode.value, 10) : rfocusable.test(elem.nodeName) || rclickable.test(elem.nodeName) && elem.href ? 0 : undefined; } } } }); // Hook for boolean attributes boolHook = { get: function (elem, name) { var // Use .prop to determine if this attribute is understood as boolean prop = jQuery.prop(elem, name), // Fetch it accordingly attr = typeof prop === "boolean" && elem.getAttribute(name), detail = typeof prop === "boolean" ? getSetInput && getSetAttribute ? attr != null : // oldIE fabricates an empty string for missing boolean attributes // and conflates checked/selected into attroperties ruseDefault.test(name) ? elem[jQuery.camelCase("default-" + name)] : !!attr : // fetch an attribute node for properties not recognized as boolean elem.getAttributeNode(name); return detail && detail.value !== false ? name.toLowerCase() : undefined; }, set: function (elem, value, name) { if (value === false) { // Remove boolean attributes when set to false jQuery.removeAttr(elem, name); } else if (getSetInput && getSetAttribute || !ruseDefault.test(name)) { // IE<8 needs the *property* name elem.setAttribute(!getSetAttribute && jQuery.propFix[name] || name, name); // Use defaultChecked and defaultSelected for oldIE } else { elem[jQuery.camelCase("default-" + name)] = elem[name] = true; } return name; } }; // fix oldIE value attroperty if (!getSetInput || !getSetAttribute) { jQuery.attrHooks.value = { get: function (elem, name) { var ret = elem.getAttributeNode(name); return jQuery.nodeName(elem, "input") ? // Ignore the value *property* by using defaultValue elem.defaultValue : ret && ret.specified ? ret.value : undefined; }, set: function (elem, value, name) { if (jQuery.nodeName(elem, "input")) { // Does not return so that setAttribute is also used elem.defaultValue = value; } else { // Use nodeHook if defined (#1954); otherwise setAttribute is fine return nodeHook && nodeHook.set(elem, value, name); } } }; } // IE6/7 do not support getting/setting some attributes with get/setAttribute if (!getSetAttribute) { // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = jQuery.valHooks.button = { get: function (elem, name) { var ret = elem.getAttributeNode(name); return ret && (name === "id" || name === "name" || name === "coords" ? ret.value !== "" : ret.specified) ? ret.value : undefined; }, set: function (elem, value, name) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode(name); if (!ret) { elem.setAttributeNode( (ret = elem.ownerDocument.createAttribute(name)) ); } ret.value = value += ""; // Break association with cloned elements by also using setAttribute (#9646) return name === "value" || value === elem.getAttribute(name) ? value : undefined; } }; // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { get: nodeHook.get, set: function (elem, value, name) { nodeHook.set(elem, value === "" ? false : value, name); } }; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each(["width", "height"], function (i, name) { jQuery.attrHooks[name] = jQuery.extend(jQuery.attrHooks[name], { set: function (elem, value) { if (value === "") { elem.setAttribute(name, "auto"); return value; } } }); }); } // Some attributes require a special call on IE // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if (!jQuery.support.hrefNormalized) { jQuery.each(["href", "src", "width", "height"], function (i, name) { jQuery.attrHooks[name] = jQuery.extend(jQuery.attrHooks[name], { get: function (elem) { var ret = elem.getAttribute(name, 2); return ret == null ? undefined : ret; } }); }); // href/src property should get the full normalized URL (#10299/#12915) jQuery.each(["href", "src"], function (i, name) { jQuery.propHooks[name] = { get: function (elem) { return elem.getAttribute(name, 4); } }; }); } if (!jQuery.support.style) { jQuery.attrHooks.style = { get: function (elem) { // Return undefined in the case of empty string // Note: IE uppercases css property names, but if we were to .toLowerCase() // .cssText, that would destroy case senstitivity in URL's, like in "background" return elem.style.cssText || undefined; }, set: function (elem, value) { return (elem.style.cssText = value + ""); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if (!jQuery.support.optSelected) { jQuery.propHooks.selected = jQuery.extend(jQuery.propHooks.selected, { get: function (elem) { var parent = elem.parentNode; if (parent) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if (parent.parentNode) { parent.parentNode.selectedIndex; } } return null; } }); } // IE6/7 call enctype encoding if (!jQuery.support.enctype) { jQuery.propFix.enctype = "encoding"; } // Radios and checkboxes getter/setter if (!jQuery.support.checkOn) { jQuery.each(["radio", "checkbox"], function () { jQuery.valHooks[this] = { get: function (elem) { // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; } }; }); } jQuery.each(["radio", "checkbox"], function () { jQuery.valHooks[this] = jQuery.extend(jQuery.valHooks[this], { set: function (elem, value) { if (jQuery.isArray(value)) { return (elem.checked = jQuery.inArray(jQuery(elem).val(), value) >= 0); } } }); }); var rformElems = /^(?:input|select|textarea)$/i, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } /* * 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, // Don't attach events to noData or text/comment nodes (but allow plain objects) elemData = elem.nodeType !== 3 && elem.nodeType !== 8 && jQuery._data(elem); 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 !== "undefined" && (!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 // jQuery(...).bind("mouseover mouseout", fn); types = (types || "").match(core_rnotwhite) || [""]; t = types.length; while (t--) { tmp = rtypenamespace.exec(types[t]) || []; type = origType = tmp[1]; namespaces = (tmp[2] || "").split(".").sort(); // 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/attachEvent if the special events handler returns false if (!special.setup || special.setup.call(elem, data, namespaces, eventHandle) === false) { // Bind the global event handler to the element if (elem.addEventListener) { elem.addEventListener(type, eventHandle, false); } else if (elem.attachEvent) { elem.attachEvent("on" + type, eventHandle); } } } 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 = jQuery.hasData(elem) && jQuery._data(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; // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery._removeData(elem, "events"); } }, trigger: function (event, data, elem, onlyHandlers) { var i, cur, tmp, bubbleType, ontype, handle, special, eventPath = [elem || document], type = event.type || event, namespaces = 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); event.isTrigger = true; 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 = (jQuery._data(cur, "events") || {})[event.type] && jQuery._data(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(elem.ownerDocument, data) === false) && !(type === "click" && jQuery.nodeName(elem, "a")) && jQuery.acceptData(elem)) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) if (ontype && 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; try { elem[type](); } catch (e) { // IE<9 dies on focus/blur to hidden element (#1486,#12518) // only reproducible on winXP IE8 native, not IE9 in IE8 mode } 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 = (jQuery._data(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; }, fix: function (event) { if (event[jQuery.expando]) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, originalEvent = event, fixHook = jQuery.event.fixHooks[event.type] || {}, 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: IE<9 // Fix target property (#1925) if (!event.target) { event.target = originalEvent.srcElement || document; } // Support: Chrome 23+, Safari? // Target should not be a text node (#504, #13143) if (event.target.nodeType === 3) { event.target = event.target.parentNode; } // Support: IE<9 // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) event.metaKey = !!event.metaKey; return fixHook.filter ? fixHook.filter(event, originalEvent) : event; }, // 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 fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function (event, original) { var eventDoc, doc, body, button = original.button, fromElement = original.fromElement; // 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 relatedTarget, if necessary if (!event.relatedTarget && fromElement) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // 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; } }, special: { load: { // Prevent triggered images.load events from bubbling to window.load noBubble: true }, click: { // For checkbox, fire native event so checked state will be right trigger: function () { if (jQuery.nodeName(this, "input") && this.type === "checkbox" && this.click) { this.click(); return false; } } }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function () { if (this !== document.activeElement && this.focus) { try { this.focus(); return false; } catch (e) { // Support: IE<9 // If we error on focus to hidden element (#1486, #12518), // let .trigger() run the handlers } } }, delegateType: "focusin" }, blur: { trigger: function () { if (this === document.activeElement && this.blur) { this.blur(); return false; } }, delegateType: "focusout" }, beforeunload: { postDispatch: function (event) { // Even when returnValue equals to undefined Firefox will still show alert 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 = document.removeEventListener ? function (elem, type, handle) { if (elem.removeEventListener) { elem.removeEventListener(type, handle, false); } } : function (elem, type, handle) { var name = "on" + type; if (elem.detachEvent) { // #8545, #7054, preventing memory leaks for custom events in IE6-8 // detachEvent needed property on element, by name of that event, to properly expose it to GC if (typeof elem[name] === "undefined") { elem[name] = null; } elem.detachEvent(name, handle); } }; 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.returnValue === false || 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) { return; } // If preventDefault exists, run it on the original event if (e.preventDefault) { e.preventDefault(); // Support: IE // Otherwise set the returnValue property of the original event to false } else { e.returnValue = false; } }, stopPropagation: function () { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if (!e) { return; } // If stopPropagation exists, run it on the original event if (e.stopPropagation) { e.stopPropagation(); } // Support: IE // Set the cancelBubble property of the original event to true e.cancelBubble = true; }, stopImmediatePropagation: function () { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks 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; } }; }); // IE submit delegation if (!jQuery.support.submitBubbles) { jQuery.event.special.submit = { setup: function () { // Only need this for delegated form submit events if (jQuery.nodeName(this, "form")) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add(this, "click._submit keypress._submit", function (e) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName(elem, "input") || jQuery.nodeName(elem, "button") ? elem.form : undefined; if (form && !jQuery._data(form, "submitBubbles")) { jQuery.event.add(form, "submit._submit", function (event) { event._submit_bubble = true; }); jQuery._data(form, "submitBubbles", true); } }); // return undefined since we don't need an event listener }, postDispatch: function (event) { // If form was submitted by the user, bubble the event up the tree if (event._submit_bubble) { delete event._submit_bubble; if (this.parentNode && !event.isTrigger) { jQuery.event.simulate("submit", this.parentNode, event, true); } } }, teardown: function () { // Only need this for delegated form submit events if (jQuery.nodeName(this, "form")) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove(this, "._submit"); } }; } // IE change delegation and checkbox/radio fix if (!jQuery.support.changeBubbles) { jQuery.event.special.change = { setup: function () { if (rformElems.test(this.nodeName)) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if (this.type === "checkbox" || this.type === "radio") { jQuery.event.add(this, "propertychange._change", function (event) { if (event.originalEvent.propertyName === "checked") { this._just_changed = true; } }); jQuery.event.add(this, "click._change", function (event) { if (this._just_changed && !event.isTrigger) { this._just_changed = false; } // Allow triggered, simulated change events (#11500) jQuery.event.simulate("change", this, event, true); }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add(this, "beforeactivate._change", function (e) { var elem = e.target; if (rformElems.test(elem.nodeName) && !jQuery._data(elem, "changeBubbles")) { jQuery.event.add(elem, "change._change", function (event) { if (this.parentNode && !event.isSimulated && !event.isTrigger) { jQuery.event.simulate("change", this.parentNode, event, true); } }); jQuery._data(elem, "changeBubbles", true); } }); }, handle: function (event) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if (this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox")) { return event.handleObj.handler.apply(this, arguments); } }, teardown: function () { jQuery.event.remove(this, "._change"); return !rformElems.test(this.nodeName); } }; } // Create "bubbling" focus and blur events 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); }); }, 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); }, 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); } }, hover: function (fnOver, fnOut) { return this.mouseenter(fnOver).mouseleave(fnOut || fnOver); } }); 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); }; if (rkeyEvent.test(name)) { jQuery.event.fixHooks[name] = jQuery.event.keyHooks; } if (rmouseEvent.test(name)) { jQuery.event.fixHooks[name] = jQuery.event.mouseHooks; } }); /*! * Sizzle CSS Selector Engine * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license * http://sizzlejs.com/ */ (function (window, undefined) { var i, cachedruns, Expr, getText, isXML, compile, hasDuplicate, outermostContext, // Local document vars setDocument, document, docElem, documentIsXML, rbuggyQSA, rbuggyMatches, matches, contains, sortOrder, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, support = {}, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), // General-purpose constants strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Array methods arr = [], pop = arr.pop, 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; }, // 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 operators = "([*^$|!~]?=)", attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:" + operators + 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 + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*"), rpseudo = new RegExp(pseudos), ridentifier = new RegExp("^" + identifier + "$"), matchExpr = { "ID": new RegExp("^#(" + characterEncoding + ")"), "CLASS": new RegExp("^\\.(" + characterEncoding + ")"), "NAME": new RegExp("^\\[name=['\"]?(" + 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"), // 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") }, rsibling = /[\x20\t\r\n\f]*[+~]/, rnative = /\{\s*\[native code\]\s*\}/, // 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, rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = /\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g, funescape = function (_, escaped) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint return high !== high ? escaped : // BMP codepoint high < 0 ? String.fromCharCode(high + 0x10000) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode(high >> 10 | 0xD800, high & 0x3FF | 0xDC00); }; // Use a stripped-down slice if we can't use a native one try { slice.call(docElem.childNodes, 0)[0].nodeType; } catch (e) { slice = function (i) { var elem, results = []; for (; (elem = this[i]); i++) { results.push(elem); } return results; }; } /** * For feature detection * @param {Function} fn The function to test for native support */ function isNative(fn) { return rnative.test(fn + ""); } /** * 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 cache, keys = []; return (cache = function (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); }); } /** * 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 { // release memory in IE div = null; } } 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 (!documentIsXML && !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, slice.call(context.getElementsByTagName(selector), 0)); return results; // Speed-up: Sizzle(".CLASS") } else if ((m = match[3]) && support.getByClassName && context.getElementsByClassName) { push.apply(results, slice.call(context.getElementsByClassName(m), 0)); return results; } } // QSA path if (support.qsa && !rbuggyQSA.test(selector)) { old = true; nid = 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, slice.call(newContext.querySelectorAll( newSelector ), 0)); return results; } catch (qsaError) { } finally { if (!old) { context.removeAttribute("id"); } } } } } // All others return select(selector.replace(rtrim, "$1"), context, results, seed); } /** * 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; }; /** * 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; // 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 documentIsXML = isXML(doc); // Check if getElementsByTagName("*") returns only elements support.tagNameNoComments = assert(function (div) { div.appendChild(doc.createComment("")); return !div.getElementsByTagName("*").length; }); // Check if attributes should be retrieved by attribute nodes support.attributes = assert(function (div) { div.innerHTML = "<select></select>"; var type = typeof div.lastChild.getAttribute("multiple"); // IE8 returns a string for some attributes even when not present return type !== "boolean" && type !== "string"; }); // Check if getElementsByClassName can be trusted support.getByClassName = assert(function (div) { // Opera can't find a second classname (in 9.6) div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>"; if (!div.getElementsByClassName || !div.getElementsByClassName("e").length) { return false; } // Safari 3.2 caches class attributes and doesn't catch changes div.lastChild.className = "e"; return div.getElementsByClassName("e").length === 2; }); // Check if getElementById returns elements by name // Check if getElementsByName privileges form controls or returns elements by ID support.getByName = assert(function (div) { // Inject content div.id = expando + 0; div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>"; docElem.insertBefore(div, docElem.firstChild); // Test var pass = doc.getElementsByName && // buggy browsers will return fewer than the correct 2 doc.getElementsByName(expando).length === 2 + // buggy browsers will return more than the correct 0 doc.getElementsByName(expando + 0).length; support.getIdNotName = !doc.getElementById(expando); // Cleanup docElem.removeChild(div); return pass; }); // IE6/7 return modified attributes Expr.attrHandle = assert(function (div) { div.innerHTML = "<a href='#'></a>"; return div.firstChild && typeof div.firstChild.getAttribute !== strundefined && div.firstChild.getAttribute("href") === "#"; }) ? {} : { "href": function (elem) { return elem.getAttribute("href", 2); }, "type": function (elem) { return elem.getAttribute("type"); } }; // ID find and filter if (support.getIdNotName) { Expr.find["ID"] = function (id, context) { if (typeof context.getElementById !== strundefined && !documentIsXML) { 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 { Expr.find["ID"] = function (id, context) { if (typeof context.getElementById !== strundefined && !documentIsXML) { var m = context.getElementById(id); return m ? m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ? [m] : undefined : []; } }; 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.tagNameNoComments ? 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 === "*") { for (; (elem = results[i]); i++) { if (elem.nodeType === 1) { tmp.push(elem); } } return tmp; } return results; }; // Name Expr.find["NAME"] = support.getByName && function (tag, context) { if (typeof context.getElementsByName !== strundefined) { return context.getElementsByName(name); } }; // Class Expr.find["CLASS"] = support.getByClassName && function (className, context) { if (typeof context.getElementsByClassName !== strundefined && !documentIsXML) { return context.getElementsByClassName(className); } }; // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21), // no need to also add to buggyMatches since matches checks buggyQSA // A support test would require too much code (would include document ready) rbuggyQSA = [":focus"]; if ((support.qsa = isNative(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 explictly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select><option selected=''></option></select>"; // IE8 - Some boolean attributes are not treated correctly if (!div.querySelectorAll("[selected]").length) { rbuggyQSA.push("\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)"); } // 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) { // Opera 10-12/IE8 - ^= $= *= and empty values // Should not select anything div.innerHTML = "<input type='hidden' i=''/>"; if (div.querySelectorAll("[i^='']").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 = isNative((matches = docElem.matchesSelector || docElem.mozMatchesSelector || docElem.webkitMatchesSelector || 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 = new RegExp(rbuggyQSA.join("|")); rbuggyMatches = new RegExp(rbuggyMatches.join("|")); // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = isNative(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; }; // Document order sorting sortOrder = docElem.compareDocumentPosition ? function (a, b) { var compare; if (a === b) { hasDuplicate = true; return 0; } if ((compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition(b))) { if (compare & 1 || a.parentNode && a.parentNode.nodeType === 11) { if (a === doc || contains(preferredDoc, a)) { return -1; } if (b === doc || contains(preferredDoc, b)) { return 1; } return 0; } return compare & 4 ? -1 : 1; } return a.compareDocumentPosition ? -1 : 1; } : function (a, b) { var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [a], bp = [b]; // The nodes are identical, we can exit early if (a === b) { hasDuplicate = true; return 0; // Fallback to using sourceIndex (in IE) if it's available on both nodes } else if (a.sourceIndex && b.sourceIndex) { return (~b.sourceIndex || MAX_NEGATIVE) - (contains(preferredDoc, a) && ~a.sourceIndex || MAX_NEGATIVE); // Parentless nodes are either documents or disconnected } else if (!aup || !bup) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : 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; }; // Always assume the presence of duplicates if sort doesn't // pass them to our comparison function (as in Google Chrome). hasDuplicate = false; [0, 0].sort(sortOrder); support.detectDuplicates = hasDuplicate; return document; }; 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']"); // rbuggyQSA always contains :focus, so no need for an existence check if (support.matchesSelector && !documentIsXML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && !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) { var val; // Set document vars if needed if ((elem.ownerDocument || elem) !== document) { setDocument(elem); } if (!documentIsXML) { name = name.toLowerCase(); } if ((val = Expr.attrHandle[name])) { return val(elem); } if (documentIsXML || support.attributes) { return elem.getAttribute(name); } return ((val = elem.getAttributeNode(name)) || elem.getAttribute(name)) && elem[name] === true ? name : val && val.specified ? val.value : null; }; Sizzle.error = function (msg) { throw new Error("Syntax error, unrecognized expression: " + msg); }; // Document sorting and removing duplicates Sizzle.uniqueSort = function (results) { var elem, duplicates = [], i = 1, j = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; results.sort(sortOrder); if (hasDuplicate) { for (; (elem = results[i]); i++) { if (elem === results[i - 1]) { j = duplicates.push(i); } } while (j--) { results.splice(duplicates[j], 1); } } return results; }; function siblingCheck(a, b) { var cur = a && b && a.nextSibling; for (; cur; cur = cur.nextSibling) { if (cur === b) { return -1; } } return a ? 1 : -1; } // Returns a function to use in pseudos for input types 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 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 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]); } } }); }); } /** * 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, 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[4]) { 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 (nodeName) { if (nodeName === "*") { return function () { return true; }; } nodeName = nodeName.replace(runescape, funescape).toLowerCase(); return 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(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.substr(result.length - check.length) === check : operator === "~=" ? (" " + result + " ").indexOf(check) > -1 : operator === "|=" ? result === check || result.substr(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 identifider if (!ridentifier.test(lang || "")) { Sizzle.error("unsupported lang: " + lang); } lang = lang.replace(runescape, funescape).toLowerCase(); return function (elem) { var elemLang; do { if ((elemLang = documentIsXML ? elem.getAttribute("xml:lang") || elem.getAttribute("lang") : elem.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; }) } }; // 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); } 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 && combinator.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(tokens.slice(0, i - 1)).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), // Nested matchers should use non-integer dirruns dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.E); if (outermost) { outermostContext = context !== document && context; cachedruns = matcherCachedRuns; } // Add elements passing elementMatchers directly to results for (; (elem = elems[i]) != null; i++) { if (byElement && elem) { for (j = 0; (matcher = elementMatchers[j]); 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 // `i` starts as a string, so matchedCount would equal "00" if there are no elements matchedCount += i; if (bySet && i !== matchedCount) { for (j = 0; (matcher = setMatchers[j]); 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" && context.nodeType === 9 && !documentIsXML && 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 for (i = matchExpr["needsContext"].test(selector) ? -1 : tokens.length - 1; i >= 0; 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, slice.call(seed, 0)); 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, documentIsXML, results, rsibling.test(selector) ); return results; } // Deprecated Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Easy API for creating new setFilters function setFilters() { } Expr.filters = setFilters.prototype = Expr.pseudos; Expr.setFilters = new setFilters(); // Initialize with the default document setDocument(); // Override sizzle attribute retrieval Sizzle.attr = jQuery.attr; 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); var runtil = /Until$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, isSimple = /^.[^:#\[\.,]*$/, 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; if (typeof selector !== "string") { self = this; return this.pushStack(jQuery(selector).filter(function () { for (i = 0; i < self.length; i++) { if (jQuery.contains(self[i], this)) { return true; } } })); } ret = []; for (i = 0; i < this.length; i++) { jQuery.find(selector, this[i], ret); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack(jQuery.unique(ret)); ret.selector = (this.selector ? this.selector + " " : "") + selector; return ret; }, has: function (target) { var i, targets = jQuery(target, this), len = targets.length; return this.filter(function () { for (i = 0; i < len; i++) { if (jQuery.contains(this, targets[i])) { return true; } } }); }, not: function (selector) { return this.pushStack(winnow(this, selector, false)); }, filter: function (selector) { return this.pushStack(winnow(this, selector, true)); }, is: function (selector) { return !!selector && ( typeof selector === "string" ? // 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". rneedsContext.test(selector) ? jQuery(selector, this.context).index(this[0]) >= 0 : jQuery.filter(selector, this).length > 0 : this.filter(selector).length > 0); }, closest: function (selectors, context) { var cur, i = 0, l = this.length, ret = [], pos = rneedsContext.test(selectors) || typeof selectors !== "string" ? jQuery(selectors, context || this.context) : 0; for (; i < l; i++) { cur = this[i]; while (cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11) { if (pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors)) { ret.push(cur); break; } cur = cur.parentNode; } } return this.pushStack(ret.length > 1 ? jQuery.unique(ret) : ret); }, // 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 jQuery.inArray(this[0], jQuery(elem)); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this); }, 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) ); } }); jQuery.fn.andSelf = jQuery.fn.addBack; function sibling(cur, dir) { do { cur = cur[dir]; } while (cur && 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 jQuery.nodeName(elem, "iframe") ? elem.contentDocument || elem.contentWindow.document : jQuery.merge([], elem.childNodes); } }, function (name, fn) { jQuery.fn[name] = function (until, selector) { var ret = jQuery.map(this, fn, until); if (!runtil.test(name)) { selector = until; } if (selector && typeof selector === "string") { ret = jQuery.filter(selector, ret); } ret = this.length > 1 && !guaranteedUnique[name] ? jQuery.unique(ret) : ret; if (this.length > 1 && rparentsprev.test(name)) { ret = ret.reverse(); } return this.pushStack(ret); }; }); jQuery.extend({ filter: function (expr, elems, not) { if (not) { expr = ":not(" + expr + ")"; } return elems.length === 1 ? jQuery.find.matchesSelector(elems[0], expr) ? [elems[0]] : [] : jQuery.find.matches(expr, elems); }, dir: function (elem, dir, until) { var matched = [], cur = elem[dir]; while (cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery(cur).is(until))) { if (cur.nodeType === 1) { matched.push(cur); } cur = cur[dir]; } return matched; }, sibling: function (n, elem) { var r = []; for (; n; n = n.nextSibling) { if (n.nodeType === 1 && n !== elem) { r.push(n); } } return r; } }); // Implement the identical functionality for filter and not function winnow(elements, qualifier, keep) { // Can't pass null or undefined to indexOf in Firefox 4 // Set to 0 to skip string check qualifier = qualifier || 0; if (jQuery.isFunction(qualifier)) { return jQuery.grep(elements, function (elem, i) { var retVal = !!qualifier.call(elem, i, elem); return retVal === keep; }); } else if (qualifier.nodeType) { return jQuery.grep(elements, function (elem) { return (elem === qualifier) === keep; }); } else if (typeof qualifier === "string") { var filtered = jQuery.grep(elements, function (elem) { return elem.nodeType === 1; }); if (isSimple.test(qualifier)) { return jQuery.filter(qualifier, filtered, !keep); } else { qualifier = jQuery.filter(qualifier, filtered); } } return jQuery.grep(elements, function (elem) { return (jQuery.inArray(elem, qualifier) >= 0) === keep; }); } function createSafeFragment(document) { var list = nodeNames.split("|"), safeFrag = document.createDocumentFragment(); if (safeFrag.createElement) { while (list.length) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, 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 = { option: [1, "<select multiple='multiple'>", "</select>"], legend: [1, "<fieldset>", "</fieldset>"], area: [1, "<map>", "</map>"], param: [1, "<object>", "</object>"], thead: [1, "<table>", "</table>"], tr: [2, "<table><tbody>", "</tbody></table>"], col: [2, "<table><tbody></tbody><colgroup>", "</colgroup></table>"], td: [3, "<table><tbody><tr>", "</tr></tbody></table>"], // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. _default: jQuery.support.htmlSerialize ? [0, "", ""] : [1, "X<div>", "</div>"] }, safeFragment = createSafeFragment(document), fragmentDiv = safeFragment.appendChild(document.createElement("div")); 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); }, wrapAll: function (html) { 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 var 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.firstChild && elem.firstChild.nodeType === 1) { elem = elem.firstChild; } 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(); }, append: function () { return this.domManip(arguments, true, function (elem) { if (this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9) { this.appendChild(elem); } }); }, prepend: function () { return this.domManip(arguments, true, function (elem) { if (this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9) { this.insertBefore(elem, this.firstChild); } }); }, before: function () { return this.domManip(arguments, false, function (elem) { if (this.parentNode) { this.parentNode.insertBefore(elem, this); } }); }, after: function () { return this.domManip(arguments, false, 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, i = 0; for (; (elem = this[i]) != null; i++) { if (!selector || jQuery.filter(selector, [elem]).length > 0) { 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++) { // Remove element nodes and prevent memory leaks if (elem.nodeType === 1) { jQuery.cleanData(getAll(elem, false)); } // Remove any remaining nodes while (elem.firstChild) { elem.removeChild(elem.firstChild); } // If this is a select, ensure that it displays empty (#12336) // Support: IE<9 if (elem.options && jQuery.nodeName(elem, "select")) { elem.options.length = 0; } } 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) { return elem.nodeType === 1 ? elem.innerHTML.replace(rinlinejQuery, "") : undefined; } // See if we can take a shortcut and just use innerHTML if (typeof value === "string" && !rnoInnerhtml.test(value) && (jQuery.support.htmlSerialize || !rnoshimcache.test(value)) && (jQuery.support.leadingWhitespace || !rleadingWhitespace.test(value)) && !wrapMap[(rtagName.exec(value) || ["", ""])[1].toLowerCase()]) { value = value.replace(rxhtmlTag, "<$1></$2>"); try { for (; i < l; i++) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; 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 (value) { var isFunc = jQuery.isFunction(value); // Make sure that the elements are removed from the DOM before they are inserted // this can help fix replacing a parent with child elements if (!isFunc && typeof value !== "string") { value = jQuery(value).not(this).detach(); } return this.domManip([value], true, function (elem) { var next = this.nextSibling, parent = this.parentNode; if (parent && this.nodeType === 1 || this.nodeType === 11) { jQuery(this).remove(); if (next) { next.parentNode.insertBefore(elem, next); } else { parent.appendChild(elem); } } }); }, detach: function (selector) { return this.remove(selector, true); }, domManip: function (args, table, callback) { // 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, table ? self.html() : undefined); } self.domManip(args, table, callback); }); } if (l) { fragment = jQuery.buildFragment(args, this[0].ownerDocument, false, this); first = fragment.firstChild; if (fragment.childNodes.length === 1) { fragment = first; } if (first) { table = table && jQuery.nodeName(first, "tr"); 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) { jQuery.merge(scripts, getAll(node, "script")); } } callback.call( table && jQuery.nodeName(this[i], "table") ? findOrAppend(this[i], "tbody") : 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 || "") && !jQuery._data(node, "globalEval") && jQuery.contains(doc, node)) { if (node.src) { // Hope ajax is available... jQuery.ajax({ url: node.src, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } else { jQuery.globalEval((node.text || node.textContent || node.innerHTML || "").replace(rcleanScript, "")); } } } } // Fix #11809: Avoid leaking memory fragment = first = null; } } return this; } }); function findOrAppend(elem, tag) { return elem.getElementsByTagName(tag)[0] || elem.appendChild(elem.ownerDocument.createElement(tag)); } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript(elem) { var attr = elem.getAttributeNode("type"); elem.type = (attr && attr.specified) + "/" + 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 elem, i = 0; for (; (elem = elems[i]) != null; i++) { jQuery._data(elem, "globalEval", !refElements || jQuery._data(refElements[i], "globalEval")); } } function cloneCopyEvent(src, dest) { if (dest.nodeType !== 1 || !jQuery.hasData(src)) { return; } var type, i, l, oldData = jQuery._data(src), curData = jQuery._data(dest, oldData), events = oldData.events; if (events) { delete curData.handle; curData.events = {}; for (type in events) { for (i = 0, l = events[type].length; i < l; i++) { jQuery.event.add(dest, type, events[type][i]); } } } // make the cloned public data object a copy from the original if (curData.data) { curData.data = jQuery.extend({}, curData.data); } } function fixCloneNodeIssues(src, dest) { var nodeName, data, e; // We do not need to do anything for non-Elements if (dest.nodeType !== 1) { return; } nodeName = dest.nodeName.toLowerCase(); // IE6-8 copies events bound via attachEvent when using cloneNode. if (!jQuery.support.noCloneEvent && dest[jQuery.expando]) { data = jQuery._data(dest); for (e in data.events) { jQuery.removeEvent(dest, e, data.handle); } // Event data gets referenced instead of copied if the expando gets copied too dest.removeAttribute(jQuery.expando); } // IE blanks contents when cloning scripts, and tries to evaluate newly-set text if (nodeName === "script" && dest.text !== src.text) { disableScript(dest).text = src.text; restoreScript(dest); // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. } else if (nodeName === "object") { if (dest.parentNode) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if (jQuery.support.html5Clone && (src.innerHTML && !jQuery.trim(dest.innerHTML))) { dest.innerHTML = src.innerHTML; } } else if (nodeName === "input" && manipulation_rcheckableType.test(src.type)) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if (dest.value !== src.value) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if (nodeName === "option") { dest.defaultSelected = dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if (nodeName === "input" || nodeName === "textarea") { dest.defaultValue = src.defaultValue; } } jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function (name, original) { jQuery.fn[name] = function (selector) { var elems, i = 0, ret = [], insert = jQuery(selector), last = insert.length - 1; for (; i <= last; i++) { elems = i === last ? this : this.clone(true); jQuery(insert[i])[original](elems); // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() core_push.apply(ret, elems.get()); } return this.pushStack(ret); }; }); function getAll(context, tag) { var elems, elem, i = 0, found = typeof context.getElementsByTagName !== "undefined" ? context.getElementsByTagName(tag || "*") : typeof context.querySelectorAll !== "undefined" ? context.querySelectorAll(tag || "*") : undefined; if (!found) { for (found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++) { if (!tag || jQuery.nodeName(elem, tag)) { found.push(elem); } else { jQuery.merge(found, getAll(elem, tag)); } } } return tag === undefined || tag && jQuery.nodeName(context, tag) ? jQuery.merge([context], found) : found; } // Used in buildFragment, fixes the defaultChecked property function fixDefaultChecked(elem) { if (manipulation_rcheckableType.test(elem.type)) { elem.defaultChecked = elem.checked; } } jQuery.extend({ clone: function (elem, dataAndEvents, deepDataAndEvents) { var destElements, srcElements, node, i, clone, inPage = jQuery.contains(elem.ownerDocument, elem); if (jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test("<" + elem.nodeName + ">")) { clone = elem.cloneNode(true); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild(clone = fragmentDiv.firstChild); } if ((!jQuery.support.noCloneEvent || !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); // Fix all IE cloning issues for (i = 0; (node = srcElements[i]) != null; ++i) { // Ensure that the destination node is not null; Fixes #9587 if (destElements[i]) { fixCloneNodeIssues(node, 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; (node = srcElements[i]) != null; i++) { cloneCopyEvent(node, destElements[i]); } } else { cloneCopyEvent(elem, clone); } } // Preserve script evaluation history destElements = getAll(clone, "script"); if (destElements.length > 0) { setGlobalEval(destElements, !inPage && getAll(elem, "script")); } destElements = srcElements = node = null; // Return the cloned set return clone; }, buildFragment: function (elems, context, scripts, selection) { var contains, elem, tag, tmp, wrap, tbody, j, l = elems.length, // Ensure a safe fragment safe = createSafeFragment(context), nodes = [], i = 0; for (; i < l; i++) { elem = elems[i]; if (elem || elem === 0) { // Add nodes directly if (jQuery.type(elem) === "object") { 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 || safe.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; } // Manually add leading whitespace removed by IE if (!jQuery.support.leadingWhitespace && rleadingWhitespace.test(elem)) { nodes.push(context.createTextNode(rleadingWhitespace.exec(elem)[0])); } // Remove IE's autoinserted <tbody> from table fragments if (!jQuery.support.tbody) { // String was a <table>, *may* have spurious <tbody> elem = tag === "table" && !rtbody.test(elem) ? tmp.firstChild : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !rtbody.test(elem) ? tmp : 0; j = elem && elem.childNodes.length; while (j--) { if (jQuery.nodeName((tbody = elem.childNodes[j]), "tbody") && !tbody.childNodes.length) { elem.removeChild(tbody); } } } jQuery.merge(nodes, tmp.childNodes); // Fix #12392 for WebKit and IE > 9 tmp.textContent = ""; // Fix #12392 for oldIE while (tmp.firstChild) { tmp.removeChild(tmp.firstChild); } // Remember the top-level container for proper cleanup tmp = safe.lastChild; } } } // Fix #11356: Clear elements from fragment if (tmp) { safe.removeChild(tmp); } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if (!jQuery.support.appendChecked) { jQuery.grep(getAll(nodes, "input"), fixDefaultChecked); } 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(safe.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); } } } } tmp = null; return safe; }, cleanData: function (elems, /* internal */acceptData) { var data, id, elem, type, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = jQuery.support.deleteExpando, special = jQuery.event.special; for (; (elem = elems[i]) != null; i++) { if (acceptData || jQuery.acceptData(elem)) { id = elem[internalKey]; data = id && cache[id]; if (data) { if (data.events) { for (type in data.events) { 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); } } } // Remove cache only if it was not already removed by jQuery.event.remove if (cache[id]) { delete cache[id]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if (deleteExpando) { delete elem[internalKey]; } else if (typeof elem.removeAttribute !== "undefined") { elem.removeAttribute(internalKey); } else { elem[internalKey] = null; } core_deletedIds.push(id); } } } } } }); var curCSS, getStyles, iframe, ralpha = /alpha\([^)]*\)/i, ropacity = /opacity\s*=\s*([^)]*)/, rposition = /^(top|right|bottom|left)$/, // 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); } function showHide(elements, show) { var elem, values = [], index = 0, length = elements.length; for (; index < length; index++) { elem = elements[index]; if (!elem.style) { continue; } values[index] = jQuery._data(elem, "olddisplay"); if (show) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if (!values[index] && elem.style.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] = jQuery._data(elem, "olddisplay", css_defaultDisplay(elem.nodeName)); } } else if (!values[index] && !isHidden(elem)) { jQuery._data(elem, "olddisplay", 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) { var bool = typeof state === "boolean"; return this.each(function () { if (bool ? state : 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; } } } }, // Exclude the following css properties to add px cssNumber: { "columnCount": true, "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": 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": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // 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 specifing 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) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[name] = value; } catch (e) { } } } 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) { num = parseFloat(val); return extra === true || jQuery.isNumeric(num) ? num || 0 : val; } return val; }, // A method for quickly swapping in/out CSS properties to get correct calculations 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; } }); // NOTE: we've included the "window" in window.getComputedStyle // because jsdom on node.js will break without it. if (window.getComputedStyle) { getStyles = function (elem) { return window.getComputedStyle(elem, null); }; curCSS = function (elem, name, _computed) { var width, minWidth, maxWidth, computed = _computed || getStyles(elem), // 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); } // A tribute to the "awesome hack by Dean Edwards" // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right // 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; }; } else if (document.documentElement.currentStyle) { getStyles = function (elem) { return elem.currentStyle; }; curCSS = function (elem, name, _computed) { var left, rs, rsLeft, computed = _computed || getStyles(elem), ret = computed ? computed[name] : undefined, style = elem.style; // Avoid setting ret to empty string here // so we don't default to auto if (ret == null && style && style[name]) { ret = style[name]; } // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels // but not position css attributes, as those are proportional to the parent element instead // and we can't measure the parent instead because it might trigger a "stacking dolls" problem if (rnumnonpx.test(ret) && !rposition.test(name)) { // Remember the original values left = style.left; rs = elem.runtimeStyle; rsLeft = rs && rs.left; // Put in the new values to get a computed value out if (rsLeft) { rs.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ret; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if (rsLeft) { rs.left = rsLeft; } } return ret === "" ? "auto" : 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 ); } }; }); if (!jQuery.support.opacity) { jQuery.cssHooks.opacity = { get: function (elem, computed) { // IE uses filters for opacity return ropacity.test((computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "") ? (0.01 * parseFloat(RegExp.$1)) + "" : computed ? "1" : ""; }, set: function (elem, value) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric(value) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 // if value === "", then remove inline opacity #12685 if ((value >= 1 || value === "") && jQuery.trim(filter.replace(ralpha, "")) === "" && style.removeAttribute) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute("filter"); // if there is no filter style applied in a css rule or unset inline opacity, we are done if (value === "" || currentStyle && !currentStyle.filter) { return; } } // otherwise, set new filter values style.filter = ralpha.test(filter) ? filter.replace(ralpha, opacity) : filter + " " + opacity; } }; } // These hooks cannot be added until DOM ready because the support test // for it is not run until after DOM ready jQuery(function () { if (!jQuery.support.reliableMarginRight) { jQuery.cssHooks.marginRight = { get: function (elem, computed) { if (computed) { // 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) { return (elem.offsetWidth === 0 && elem.offsetHeight === 0) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css(elem, "display")) === "none"); }; 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)$/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); } } var // Document location ajaxLocParts, ajaxLocation, ajax_nonce = jQuery.now(), ajax_rquery = /\?/, rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL // #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.length); 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.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 }); }; }); 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" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": window.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 (#5866: IE7 issue with protocol-less urls) // 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; // Get response data if (responses) { response = ajaxHandleResponses(s, jqXHR, responses); } // If successful, handle type chaining if (status >= 200 && status < 300 || status === 304) { // 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 not modified if (status === 304) { isSuccess = true; statusText = "notmodified"; // If we have data } else { isSuccess = ajaxConvert(s, response); statusText = isSuccess.state; success = isSuccess.data; error = isSuccess.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; }, getScript: function (url, callback) { return jQuery.get(url, undefined, callback, "script"); }, getJSON: function (url, data, callback) { return jQuery.get(url, data, callback, "json"); } }); /* Handles responses to an ajax request: * - sets all responseXXX fields accordingly * - 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, responseFields = s.responseFields; // Fill responseXXX fields for (type in responseFields) { if (type in responses) { jqXHR[responseFields[type]] = responses[type]; } } // 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 function ajaxConvert(s, response) { var conv, conv2, current, tmp, converters = {}, i = 0, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(), prev = dataTypes[0]; // Apply the dataFilter if provided if (s.dataFilter) { response = s.dataFilter(response, s.dataType); } // Create converters map with lowercased keys if (dataTypes[1]) { for (conv in s.converters) { converters[conv.toLowerCase()] = s.converters[conv]; } } // Convert to each sequential dataType, tolerating list modification for (; (current = dataTypes[++i]); ) { // There's only work to do if current dataType is non-auto if (current !== "*") { // Convert response if prev dataType is non-auto and differs from current 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.splice(i--, 0, current); } 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 }; } } } } // Update prev for next iteration prev = 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 global jQuery.ajaxPrefilter("script", function (s) { if (s.cache === undefined) { s.cache = false; } if (s.crossDomain) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport("script", function (s) { // This transport only deals with cross domain requests if (s.crossDomain) { var script, head = document.head || jQuery("head")[0] || document.documentElement; return { send: function (_, callback) { script = document.createElement("script"); script.async = true; if (s.scriptCharset) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function (_, isAbort) { if (isAbort || !script.readyState || /loaded|complete/.test(script.readyState)) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if (script.parentNode) { script.parentNode.removeChild(script); } // Dereference the script script = null; // Callback if not abort if (!isAbort) { callback(200, "success"); } } }; // Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending // Use native DOM manipulation to avoid our domManip AJAX trickery head.insertBefore(script, head.firstChild); }, abort: function () { if (script) { script.onload(undefined, true); } } }; } }); 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"; } }); var xhrCallbacks, xhrSupported, xhrId = 0, // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject && function () { // Abort all pending requests var key; for (key in xhrCallbacks) { xhrCallbacks[key](undefined, true); } }; // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch (e) { } } function createActiveXHR() { try { return new window.ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { } } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function () { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Determine support properties xhrSupported = jQuery.ajaxSettings.xhr(); jQuery.support.cors = !!xhrSupported && ("withCredentials" in xhrSupported); xhrSupported = jQuery.support.ajax = !!xhrSupported; // Create transport if the browser can provide an xhr if (xhrSupported) { jQuery.ajaxTransport(function (s) { // Cross domain only allowed if supported through XMLHttpRequest if (!s.crossDomain || jQuery.support.cors) { var callback; return { send: function (headers, complete) { // Get a new xhr var handle, i, xhr = s.xhr(); // Open the socket // Passing null username, generates a login popup on Opera (#2865) if (s.username) { xhr.open(s.type, s.url, s.async, s.username, s.password); } else { xhr.open(s.type, s.url, s.async); } // Apply custom fields if provided if (s.xhrFields) { for (i in s.xhrFields) { xhr[i] = s.xhrFields[i]; } } // Override mime type if needed if (s.mimeType && xhr.overrideMimeType) { xhr.overrideMimeType(s.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 (!s.crossDomain && !headers["X-Requested-With"]) { headers["X-Requested-With"] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for (i in headers) { xhr.setRequestHeader(i, headers[i]); } } catch (err) { } // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send((s.hasContent && s.data) || null); // Listener callback = function (_, isAbort) { var status, statusText, responseHeaders, responses, xml; // Firefox throws exceptions when accessing properties // of an xhr when a network error occurred // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if (callback && (isAbort || xhr.readyState === 4)) { // Only called once callback = undefined; // Do not keep as active anymore if (handle) { xhr.onreadystatechange = jQuery.noop; if (xhrOnUnloadAbort) { delete xhrCallbacks[handle]; } } // If it's an abort if (isAbort) { // Abort it manually if needed if (xhr.readyState !== 4) { xhr.abort(); } } else { responses = {}; status = xhr.status; xml = xhr.responseXML; responseHeaders = xhr.getAllResponseHeaders(); // Construct response list if (xml && xml.documentElement /* #4958 */) { responses.xml = xml; } // When requesting binary data, IE6-9 will throw an exception // on any attempt to access responseText (#11426) if (typeof xhr.responseText === "string") { responses.text = xhr.responseText; } // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch (e) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if (!status && s.isLocal && !s.crossDomain) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if (status === 1223) { status = 204; } } } } catch (firefoxAccessException) { if (!isAbort) { complete(-1, firefoxAccessException); } } // Call complete if needed if (responses) { complete(status, statusText, responses, responseHeaders); } }; if (!s.async) { // if we're in sync mode we fire the callback callback(); } else if (xhr.readyState === 4) { // (IE6 & IE7) if it's in cache and has been // retrieved directly we need to fire the callback setTimeout(callback); } else { handle = ++xhrId; if (xhrOnUnloadAbort) { // Create the active xhrs callbacks list if needed // and attach the unload handler if (!xhrCallbacks) { xhrCallbacks = {}; jQuery(window).unload(xhrOnUnloadAbort); } // Add to list of active xhrs callbacks xhrCallbacks[handle] = callback; } xhr.onreadystatechange = callback; } }, abort: function () { if (callback) { callback(undefined, true); } } }; } }); } var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp("^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i"), rrun = /queueHooks$/, animationPrefilters = [defaultPrefilter], tweeners = { "*": [function (prop, value) { var end, unit, tween = this.createTween(prop, value), parts = rfxnum.exec(value), target = tween.cur(), start = +target || 0, scale = 1, maxIterations = 20; if (parts) { end = +parts[2]; unit = parts[3] || (jQuery.cssNumber[prop] ? "" : "px"); // We need to compute starting value if (unit !== "px" && start) { // Iteratively approximate from a nonzero starting point // Prefer the current property, because this process will be trivial if it uses the same units // Fallback to end or a simple constant start = jQuery.css(tween.elem, prop, true) || end || 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); } tween.unit = unit; tween.start = start; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[1] ? start + (parts[1] + 1) * end : end; } return tween; } ] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function () { fxNow = undefined; }); return (fxNow = jQuery.now()); } function createTweens(animation, props) { jQuery.each(props, function (prop, value) { var collection = (tweeners[prop] || []).concat(tweeners["*"]), index = 0, length = collection.length; for (; index < length; index++) { if (collection[index].call(animation, prop, value)) { // we're done with this property return; } } }); } 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; } } createTweens(animation, props); 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 index, prop, value, length, dataShow, toggle, tween, hooks, oldfire, anim = this, style = elem.style, orig = {}, handled = [], hidden = elem.nodeType && isHidden(elem); // 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 IE does 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") { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if (!jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay(elem.nodeName) === "inline") { style.display = "inline-block"; } else { style.zoom = 1; } } } if (opts.overflow) { style.overflow = "hidden"; if (!jQuery.support.shrinkWrapBlocks) { anim.done(function () { style.overflow = opts.overflow[0]; style.overflowX = opts.overflow[1]; style.overflowY = opts.overflow[2]; }); } } // show/hide pass for (index in props) { value = props[index]; if (rfxtypes.exec(value)) { delete props[index]; toggle = toggle || value === "toggle"; if (value === (hidden ? "hide" : "show")) { continue; } handled.push(index); } } length = handled.length; if (length) { dataShow = jQuery._data(elem, "fxshow") || jQuery._data(elem, "fxshow", {}); if ("hidden" in dataShow) { hidden = dataShow.hidden; } // 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; jQuery._removeData(elem, "fxshow"); for (prop in orig) { jQuery.style(elem, prop, orig[prop]); } }); for (index = 0; index < length; index++) { prop = handled[index]; tween = anim.createTween(prop, hidden ? dataShow[prop] : 0); orig[prop] = dataShow[prop] || jQuery.style(elem, prop); 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 a non 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, "auto"); // 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; } } } }; // Remove in 2.0 - this supports IE8's 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); doAnimation.finish = function () { anim.stop(true); }; // Empty animations, or finishing resolves immediately if (empty || jQuery._data(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 = jQuery._data(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 = jQuery._data(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.cur && hooks.cur.finish) { hooks.cur.finish.call(this); } // 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, box = { top: 0, left: 0 }, elem = this[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 !== "undefined") { box = elem.getBoundingClientRect(); } win = getWindow(doc); return { top: box.top + (win.pageYOffset || docElem.scrollTop) - (docElem.clientTop || 0), left: box.left + (win.pageXOffset || docElem.scrollLeft) - (docElem.clientLeft || 0) }; }; jQuery.offset = { setOffset: function (elem, options, i) { var position = jQuery.css(elem, "position"); // set position first, in-case top/left are set even on static elem if (position === "static") { elem.style.position = "relative"; } var curElem = jQuery(elem), curOffset = curElem.offset(), curCSSTop = jQuery.css(elem, "top"), curCSSLeft = jQuery.css(elem, "left"), calculatePosition = (position === "absolute" || position === "fixed") && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // 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, parentOffset = { top: 0, left: 0 }, elem = this[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 // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 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 || document.documentElement; while (offsetParent && (!jQuery.nodeName(offsetParent, "html") && jQuery.css(offsetParent, "position") === "static")) { offsetParent = offsetParent.offsetParent; } return offsetParent || document.documentElement; }); } }); // Create scrollLeft and scrollTop methods jQuery.each({ scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function (method, prop) { var top = /Y/.test(prop); jQuery.fn[method] = function (val) { return jQuery.access(this, function (elem, method, val) { var win = getWindow(elem); if (val === undefined) { return win ? (prop in win) ? win[prop] : win.document.documentElement[method] : elem[method]; } if (win) { win.scrollTo( !top ? val : jQuery(win).scrollLeft(), top ? val : jQuery(win).scrollTop() ); } else { elem[method] = val; } }, method, val, arguments.length, null); }; }); function getWindow(elem) { return jQuery.isWindow(elem) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // 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 // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it. 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() { // })(); // Expose jQuery to the global object window.jQuery = window.$ = jQuery; // Expose jQuery as an AMD module, but only for AMD loaders that // understand the issues with loading multiple versions of jQuery // in a page that all might call define(). The loader will indicate // they have special allowances for multiple jQuery versions by // specifying define.amd.jQuery = true. Register as a named module, // since jQuery can be concatenated with other files that may use define, // but not use 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.amd.jQuery) { define("jquery", [], function () { return jQuery; }); } })(window);
const express = require('express'); const path = require('path'); /** * This component provides the publicly accessible board routes. * * @param {Router} router */ module.exports = async (router) => { const staticDirectory = path.join(__dirname, '..', '..', 'public'); router.get('/', (req, res, next) => { res.redirect('/board'); }); // board page router.get('/board', (req, res, next) => { res.sendFile(path.join(staticDirectory, 'index.html')); }); router.get('/service-worker.js', (req, res, next) => { res.sendFile(path.join(staticDirectory, 'service-worker.js')); }); // static resources router.use('/board', express.static(staticDirectory)); };
import URI from 'urijs' const handleLocation = ({ store, listeners, location, action }) => { // TODO 2.x 统一控制日志 location.params = URI(location.search || '').search(true) let isLogined = !!store.getState().auth.id let { pathname, params } = location if (pathname === '/' && !isLogined) { return } if (listeners[pathname]) { listeners[pathname].forEach(item => { store.dispatch(item(params)) }) } } export default handleLocation
// Dependencies import React from 'react'; import Tesseract from 'tesseract.js'; // Visuals import './App.css'; import M from "materialize-css"; import "materialize-css/dist/css/materialize.min.css"; // Components import Holder from './holder.js'; // Application Main class App extends React.Component { // State for Text Recognition constructor() { super(); this.state = { image: null } } // Effects async componentDidMount() { M.AutoInit(); } // Image Helper Utility imageHelper = async () => { const img = document.getElementById('imageInput').files[0]; const url = URL.createObjectURL(img); M.toast({ html: 'Execution Started! This may take a while' }); // Check Completion Status in console await Tesseract.recognize(url, 'eng', { logger: m => console.log(m) } ) .then(({ data: { text } }) => { // Update App State Accordingly this.setState({ image: text }); M.toast({ html: 'Execution Successful' }) }); } render() { return ( <> <nav className="nav-extended purple darken-4"> <div className="nav-wrapper"> <span className="brand-logo center">Text Recognition</span> </div> </nav> <div id="image"> <br /> <Holder text={this.state.image} altText={"Tap the shutter to Get Started!"} /> <input type="file" accept="image/*" id="imageInput" capture style={{ display: "none", visibility: "hidden" }} onChange={this.imageHelper} /> <div className="fixed-action-btn"> <a id='imageButton' className="btn-floating btn-large purple" onClick={ () => document.getElementById('imageInput').click() }> <i className="large material-icons">camera</i> </a> </div> </div> </> ); } } export default App;
//= require angular //= require angular-ui-router //= require angular-resource //= require angular-rails-templates //= require angular-messages //= require_tree .
$(function() { 'use strict'; function number_format(number, decimals, dec_point, thousands_sep) { // * example: number_format(1234.56, 2, ',', ' '); // * return: '1 234,56' number = (number + '').replace(',', '').replace(' ', ''); var n = !isFinite(+number) ? 0 : +number, prec = !isFinite(+decimals) ? 0 : Math.abs(decimals), sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep, dec = (typeof dec_point === 'undefined') ? '.' : dec_point, s = '', toFixedFix = function (n, prec) { var k = Math.pow(10, prec); return '' + Math.round(n * k) / k; }; // Fix for IE parseFloat(0.55).toFixed(0) = 0; s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.'); if (s[0].length > 3) { s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep); } if ((s[1] || '').length < prec) { s[1] = s[1] || ''; s[1] += new Array(prec - s[1].length + 1).join('0'); } return s.join(dec); } $.ajax({ type: "get", url: "{{url('/getData-Chart')}}", success: function (response) { var data = { labels: response.labels, datasets: [{ label: "Doanh thu", data: response.data, backgroundColor: response.backgroundColor, borderColor: response.borderColor, borderWidth: 1, fill: false }] } var options = { scales: { yAxes: [{ ticks: { beginAtZero:true, callback: function(value, index, values) { return number_format(value); } } }] }, tooltips: { callbacks: { label: function(tooltipItem, chart){ var datasetLabel = chart.datasets[tooltipItem.datasetIndex].label || ''; return datasetLabel + ': ' + number_format(tooltipItem.yLabel, 0) + " VNĐ"; } } }, // scales: { // yAxes: [{ // ticks: { // beginAtZero: true // } // }] // }, legend: { display: false }, elements: { point: { radius: 0 } } }; if ($("#barChart").length) { var barChartCanvas = $("#barChart").get(0).getContext("2d"); // This will get the first returned node in the jQuery collection. var barChart = new Chart(barChartCanvas, { type: 'bar', data: data, options: options }); } } }); function refresh_chart(fillter){ $.ajax({ type: "get", url: "{{url('/getData-Chart')}}", data:{ fillter: fillter }, success: function (response) { var data = { labels: response.labels, datasets: [{ label: "Doanh thu", data: response.data, backgroundColor: response.backgroundColor, borderColor: response.borderColor, borderWidth: 1, fill: false }] } var options = { scales: { yAxes: [{ ticks: { beginAtZero:true, callback: function(value, index, values) { return number_format(value); } } }] }, tooltips: { callbacks: { label: function(tooltipItem, chart){ var datasetLabel = chart.datasets[tooltipItem.datasetIndex].label || ''; return datasetLabel + ': ' + number_format(tooltipItem.yLabel, 0) + " VNĐ"; } } }, legend: { display: false }, elements: { point: { radius: 0 } } }; if ($("#barChart").length) { $("#barChart").remove(); $("#cart-body").append('<canvas id="barChart"></canvas>'); var barChartCanvas = $("#barChart").get(0).getContext("2d"); // This will get the first returned node in the jQuery collection. var barChart = new Chart(barChartCanvas, { type: 'bar', data: data, options: options }); } } }); } /* ChartJS * ------- * Data and config for chartjs */ // });
const express = require("express"); const mongoose = require("mongoose"); const logger = require("morgan"); require('dotenv').config(); const PORT = process.env.PORT || 3000 const app = express(); app.use(express.urlencoded({ extended: true })); app.use(express.json()); app.use(logger("dev")); app.use(express.static("public")); mongoose.connect(process.env.MONGODB_URI || "mongodb://localhost/fitness-tracker", { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, useFindAndModify: false }); // // routes require("./public/api"); require("./routes/html-routes.js")(app); require("./routes/api-routes.js")(app); app.listen(PORT, () => { console.log(`App running on port ${PORT}!`); });
const Discord = require("discord.js"); exports.run = (bot, message, args) => { var rulesHeading={ "1":"Respect the Staff", "2":"No spam", "3":"No gory, sexual, or scary content", "4":"No harassment", "5":"Use the appropriate channels", "6":"No self or user bots", "7":"TOS of Discord", "8":"No drama", "9":"No sensitive topics", "10":"Know your limits" }; var rules={ "1":"Respect Staff Members (Owners/Admins/Mods/Welcome Team).", "2":"This includes but is not limited too, loud/obnoxious noises in voice, @mention spam, character spam, image spam, and message spam.", "3":"Screamer links, porn, nudity, death.", "4":"Including sexual harassment or encouraging of harassment.", "5":"Bot commands go in bot commands, selfies go in selfies etc. It's simple.", "6":"These are against the discord TOS and if you need a bot for something we have all you could ever wish for.", "7":"Follow the TOS of Discord in full.", "8":"Any drama from other servers will not carry on here or any drama with previous members. If you disagree with another member, just ignore them.", "9":"Any talk of suicide, self harm or rape is not allowed.", "10:":"Staff's decisions are final. Don't proceed to rant about them in DMs, it won't help you." }; var RuleNumbers=["1","2","3","4","5","6","7","8","9","10"]; message.delete(); if (!args[0]) { const RulesEmbed = new Discord.RichEmbed() .setColor("#23819C") .setTitle('Rules') .setDescription('Each Rule Violation Can Lead Up To a Ban') .addField('Read the Rules', '1: Respect Staff Members (Owners/Admins/Mods/Welcome Team).\n2. This includes but is not limited too, loud/obnoxious noises in voice, @mention spam, character spam, image spam, and message spam.\n3. No screamer links, porn, nudity, death\n4. Follow the TOS of Discord in full.'); message.channel.send(RulesEmbed); } else { if (RuleNumbers.indexOf(args[0] != -1)) { const RuleEmbed = new Discord.RichEmbed() .setColor("#23819C") .setTitle(rulesHeading[args[0]]) .setDescription(rules[args[0]]); message.channel.send(RuleEmbed); } } }; exports.conf = { enabled: true, guildOnly: true, aliases: ["rule", "r"], permLevel: "User" }; exports.help = { name: "rules", category: "Moderation", description: "Sends you the rule you specify.", usage: "rule [rule number]" };
import { hsl2hsv } from './hsl2hsv'; import { hsv2rgb } from './hsv2rgb'; /** Converts HSL components to an RGB color. Does not set the alpha value. */ export function hsl2rgb(h, s, l) { var hsv = hsl2hsv(h, s, l); return hsv2rgb(hsv.h, hsv.s, hsv.v); } //# sourceMappingURL=hsl2rgb.js.map
const expect = require('chai').expect const SortedLinkedList = require('../src/e-sorted-linked-list') let list = null describe('SortedLinkedList test', () => { beforeEach(() => { list = new SortedLinkedList() }) it('push(),isEmpty(),size(),toStriing() test', () => { expect(list.isEmpty()).to.be.true list.push(1) list.push(3) list.push(2) expect(list.isEmpty()).to.be.false expect(list.size()).to.equal(3) expect(list.toString()).to.equal('1,2,3') }) it('getElementAt(),removeAt() test', () => { expect(list.getElementAt(0)).to.be.undefined list.push(1) list.push(3) list.push(2) expect(list.getElementAt(3)).to.be.undefined expect(list.getElementAt(2).element).to.equal(3) expect(list.getElementAt(1).element).to.equal(2) expect(list.getElementAt(0).element).to.equal(1) expect(list.removeAt(0).element).to.equal(1) expect(list.size()).to.equal(2) expect(list.toString()).to.equal('2,3') expect(list.removeAt(2)).to.be.undefined }) it('insert(),indexOf(),remove() test', () => { list.insert(1, 0) list.insert(2, 0) // 1 2 list.insert(3, 1) // 1 2 3 list.insert(4, 3) // 1 2 3 4 expect(list.insert(5, 5)).to.be.true expect(list.toString()).to.equal('1,2,3,4,5') expect(list.indexOf(12)).to.equal(-1) expect(list.indexOf(4)).to.equal(3) expect(list.indexOf(2)).to.equal(1) expect(list.indexOf(3)).to.equal(2) expect(list.remove(4).element).to.equal(4) expect(list.size()).to.equal(4) expect(list.remove(2).element).to.equal(2) expect(list.size()).to.equal(3) }) })
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { }, mutations: { set(state, data){ Vue.set(state, data.key, data.value) }, unset(state, key){ Vue.set(state, key, null) }, list(state, key){ Vue.set(state, '__list', key) } }, actions: { } })
(window.webpackJsonp=window.webpackJsonp||[]).push([[136],{309:function(t,e,s){"use strict";s.r(e);var r=s(0),_=Object(r.a)({},(function(){var t=this,e=t.$createElement,s=t._self._c||e;return s("div",{staticClass:"content"},[t._m(0),t._v(" "),t._m(1),t._v(" "),t._m(2),t._v(" "),t._m(3),t._v(" "),t._m(4),t._v(" "),t._m(5),t._v(" "),t._m(6),t._v(" "),t._m(7),t._v(" "),t._m(8),t._v(" "),t._m(9),t._v(" "),t._m(10),t._v(" "),t._m(11),t._v(" "),t._m(12),t._v(" "),t._m(13),t._v(" "),s("p",[t._v("俗称人头,稍微专业点讲就是这家公司打算招的人数")]),t._v(" "),t._m(14),t._v(" "),s("p",[t._v("其实就是在原有offer上讨价还价,希望给更高的薪资")]),t._v(" "),s("p",[t._v("就是薪资argue的问题?")]),t._v(" "),t._m(15),t._v(" "),t._m(16),t._v(" "),t._m(17),t._v(" "),t._m(18),t._v(" "),t._m(19),t._v(" "),t._m(20),t._v(" "),t._m(21),t._v(" "),s("p",[t._v("是指企业动态地配置自身和其他企业的功能和服务,并利用企业外部的资源为企业内部的生产和经营服务")]),t._v(" "),t._m(22),t._v(" "),t._m(23),t._v(" "),t._m(24),t._v(" "),s("h3",{attrs:{id:"_2-2-牛客网"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#_2-2-牛客网"}},[t._v("#")]),t._v(" 2.2."),s("a",{attrs:{href:"https://www.nowcoder.com/",target:"_blank",rel:"noopener noreferrer"}},[t._v("牛客网"),s("OutboundLink")],1)]),t._v(" "),t._m(25),t._v(" "),s("h3",{attrs:{id:"_2-3-赛码网"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#_2-3-赛码网"}},[t._v("#")]),t._v(" 2.3."),s("a",{attrs:{href:"http://oj.acmcoder.com/ExamNotice.html#",target:"_blank",rel:"noopener noreferrer"}},[t._v("赛码网"),s("OutboundLink")],1)]),t._v(" "),t._m(26),t._v(" "),t._m(27),t._v(" "),t._m(28),t._v(" "),t._m(29),t._v(" "),t._m(30),t._v(" "),t._m(31),t._v(" "),t._m(32),t._v(" "),s("h3",{attrs:{id:"_3-2-腾讯会议"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#_3-2-腾讯会议"}},[t._v("#")]),t._v(" 3.2."),s("a",{attrs:{href:"https://meeting.tencent.com/index.html",target:"_blank",rel:"noopener noreferrer"}},[t._v("腾讯会议"),s("OutboundLink")],1)]),t._v(" "),t._m(33),t._v(" "),s("h3",{attrs:{id:"_3-3-zoom"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#_3-3-zoom"}},[t._v("#")]),t._v(" 3.3."),s("a",{attrs:{href:"https://zoom.us/",target:"_blank",rel:"noopener noreferrer"}},[t._v("zoom"),s("OutboundLink")],1)]),t._v(" "),t._m(34),t._v(" "),s("h3",{attrs:{id:"_3-4-showmebug"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#_3-4-showmebug"}},[t._v("#")]),t._v(" 3.4."),s("a",{attrs:{href:"https://www.showmebug.com/",target:"_blank",rel:"noopener noreferrer"}},[t._v("showmebug"),s("OutboundLink")],1)]),t._v(" "),t._m(35),t._v(" "),s("h3",{attrs:{id:"_3-5-牛客网"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#_3-5-牛客网"}},[t._v("#")]),t._v(" 3.5."),s("a",{attrs:{href:"https://www.nowcoder.com/",target:"_blank",rel:"noopener noreferrer"}},[t._v("牛客网"),s("OutboundLink")],1)]),t._v(" "),t._m(36),t._v(" "),t._m(37),t._v(" "),t._m(38),t._v(" "),s("p",[t._v("笔试编程,如果不是BAT的。\n那些中厂")]),t._v(" "),t._m(39),t._v(" "),t._m(40),t._v(" "),t._m(41),t._v(" "),t._m(42),t._v(" "),t._m(43),t._v(" "),t._m(44),t._v(" "),t._m(45),t._v(" "),t._m(46),t._v(" "),t._m(47),t._v(" "),s("p",[t._v("防止被HR压薪,自己利益受损\n也要防止自己趾高气扬,给HR不好的映像")]),t._v(" "),t._m(48),t._v(" "),t._m(49),t._v(" "),t._m(50),t._v(" "),t._m(51),t._v(" "),t._m(52),t._v(" "),t._m(53),t._v(" "),t._m(54),t._v(" "),s("ul",[t._m(55),t._v(" "),s("li",[s("p",[t._v("1.准备"),s("font",{staticStyle:{background:"yellow"}},[t._v("复习不要用很厚很厚的手册书")]),t._v(",除非你之前已经通读过一遍,这点很重要,否则你将会浪费大量时间。")],1)]),t._v(" "),t._m(56)]),t._v(" "),t._m(57),t._v(" "),t._m(58),t._v(" "),t._m(59),t._v(" "),t._m(60),t._v(" "),s("p",[t._v("注意事项:")]),t._v(" "),t._m(61),t._v(" "),t._m(62),t._m(63),t._v(" "),t._m(64),t._v(" "),t._m(65),t._v(" "),t._m(66),t._v(" "),s("p",[t._v("有人的教训")]),t._v(" "),t._m(67)])}),[function(){var t=this.$createElement,e=this._self._c||t;return e("h1",{attrs:{id:"it技术岗位求职流程和术语"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#it技术岗位求职流程和术语"}},[this._v("#")]),this._v(" IT技术岗位求职流程和术语")])},function(){var t=this.$createElement,e=this._self._c||t;return e("h2",{attrs:{id:"_1-术语类"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#_1-术语类"}},[this._v("#")]),this._v(" 1.术语类")])},function(){var t=this.$createElement,e=this._self._c||t;return e("h3",{attrs:{id:"_1-1-实习,试用期,正式员工"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#_1-1-实习,试用期,正式员工"}},[this._v("#")]),this._v(" 1.1.实习,试用期,正式员工")])},function(){var t=this,e=t.$createElement,s=t._self._c||e;return s("ul",[s("li",[t._v("1、实习期一般薪资很低")]),t._v(" "),s("li",[t._v("2、试用期,一般为正式薪资的0.8\n"),s("ul",[s("li",[t._v("有例外的公司,比如“编程猫”,试用期和正式薪资一样")]),t._v(" "),s("li",[t._v("特斯拉公司在2020年(2021届秋招)说的")])])]),t._v(" "),s("li",[t._v("3、正式员工")])])},function(){var t=this.$createElement,e=this._self._c||t;return e("h3",{attrs:{id:"_1-2-其他常用语"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#_1-2-其他常用语"}},[this._v("#")]),this._v(" 1.2.其他常用语")])},function(){var t=this.$createElement,e=this._self._c||t;return e("h4",{attrs:{id:"(1)oc(offer-call)"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#(1)oc(offer-call)"}},[this._v("#")]),this._v(" (1)OC(offer call)")])},function(){var t=this,e=t.$createElement,s=t._self._c||e;return s("ul",[s("li",[t._v("offer call比面试当场“"),s("code",[t._v("口头offer")]),t._v("”的好")]),t._v(" "),s("li",[s("code",[t._v("offer call")]),t._v(":HR打来电话告知面试通过,给"),s("strong",[t._v("口头offer")]),t._v(".")])])},function(){var t=this.$createElement,e=this._self._c||t;return e("h4",{attrs:{id:"(2)意向书"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#(2)意向书"}},[this._v("#")]),this._v(" (2)意向书")])},function(){var t=this.$createElement,e=this._self._c||t;return e("ul",[e("li",[this._v("通常都是邮件收到意向书,这时候才能算尘埃落定")]),this._v(" "),e("li",[this._v("意向书一般内容:月薪,福利,企业信息,三方签订")]),this._v(" "),e("li",[this._v("也有企业是发短信")])])},function(){var t=this.$createElement,e=this._self._c||t;return e("h4",{attrs:{id:"(3)“云证”"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#(3)“云证”"}},[this._v("#")]),this._v(" (3)“云证”")])},function(){var t=this.$createElement,e=this._self._c||t;return e("ul",[e("li",[this._v("信息核实,类似背景调查")]),this._v(" "),e("li",[this._v("我目前只听到腾讯有这个?似乎就是上传身份证啥的进行验证,这一步一般已经通过HR面了")])])},function(){var t=this.$createElement,e=this._self._c||t;return e("h4",{attrs:{id:"(4)“背景调查”"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#(4)“背景调查”"}},[this._v("#")]),this._v(" (4)“背景调查”")])},function(){var t=this.$createElement,e=this._self._c||t;return e("ul",[e("li",[this._v("只记得腾讯的背景调查很严格")])])},function(){var t=this.$createElement,e=this._self._c||t;return e("h4",{attrs:{id:"(5)hc(headcount)"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#(5)hc(headcount)"}},[this._v("#")]),this._v(" (5)HC(Headcount)")])},function(){var t=this.$createElement,e=this._self._c||t;return e("h4",{attrs:{id:"(6)argue-offer"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#(6)argue-offer"}},[this._v("#")]),this._v(" (6)argue offer")])},function(){var t=this.$createElement,e=this._self._c||t;return e("ul",[e("li",[this._v("bat级别的基本不用argue了,几乎没听说成功的,除非拿谷歌微软来,但是有谷歌你也不会去bat了\n这两天接到了谈薪电话,低于我的预期,但平台都挺好的。跟hr argue了")]),this._v(" "),e("li",[this._v("说有没有要钱的技巧,校招开奖的时候,就是那种能让hr听后感觉很舒服,很愿意给你申请高价offer\n别人有个模板,就是先表达你来该公司的强烈意愿,然后表示你拿了什么什么厂的什么价位的offer,白菜就别说了,如果sp可以说,然后表示如果能在这个价位基础之上加多少钱就更合适了,自己未来还是想来这边发展的,希望这边可以帮忙申请一下")])])},function(){var t=this.$createElement,e=this._self._c||t;return e("h4",{attrs:{id:"(7)od"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#(7)od"}},[this._v("#")]),this._v(" (7)OD")])},function(){var t=this.$createElement,e=this._self._c||t;return e("ul",[e("li",[this._v("外包的意思")]),this._v(" "),e("li",[this._v("OD一般是指的是华为的“外包”公司,比如像德科这种。网上其实有很多人都吐槽过这个招聘模式,因为招进去的人不直接是华为内部的人,挂在德科名下或其他,工作地点大部分都是在华为公司,虽然明面上同薪同酬,福利奖金与华为内部员工一致,但其实差很多,尤其是待遇和期权上面。")])])},function(){var t=this.$createElement,e=this._self._c||t;return e("h4",{attrs:{id:"(8)mentor"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#(8)mentor"}},[this._v("#")]),this._v(" (8)mentor")])},function(){var t=this.$createElement,e=this._self._c||t;return e("ul",[e("li",[this._v("mentor,n.导师;指导者;师傅")])])},function(){var t=this.$createElement,e=this._self._c||t;return e("h3",{attrs:{id:"_1-3-企业类型"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#_1-3-企业类型"}},[this._v("#")]),this._v(" 1.3.企业类型")])},function(){var t=this.$createElement,e=this._self._c||t;return e("blockquote",[e("p",[this._v("“外包”")])])},function(){var t=this.$createElement,e=this._self._c||t;return e("h2",{attrs:{id:"_2-笔试"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#_2-笔试"}},[this._v("#")]),this._v(" 2.笔试")])},function(){var t=this.$createElement,e=this._self._c||t;return e("h3",{attrs:{id:"_2-1-线下手撕"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#_2-1-线下手撕"}},[this._v("#")]),this._v(" 2.1.线下手撕")])},function(){var t=this.$createElement,e=this._self._c||t;return e("ul",[e("li",[this._v("出试卷/给白纸手撕代码")]),this._v(" "),e("li",[this._v("少见的形式")])])},function(){var t=this.$createElement,e=this._self._c||t;return e("ul",[e("li",[this._v("腾讯")]),this._v(" "),e("li",[this._v("百度")])])},function(){var t=this.$createElement,e=this._self._c||t;return e("ul",[e("li",[this._v("京东")])])},function(){var t=this.$createElement,e=this._self._c||t;return e("h3",{attrs:{id:"_2-4-自己搭建的笔试平台"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#_2-4-自己搭建的笔试平台"}},[this._v("#")]),this._v(" 2.4.自己搭建的笔试平台")])},function(){var t=this.$createElement,e=this._self._c||t;return e("ul",[e("li",[this._v("恒生(不能用本地IDE)")]),this._v(" "),e("li",[this._v("4399")])])},function(){var t=this.$createElement,e=this._self._c||t;return e("h2",{attrs:{id:"_3-面试"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#_3-面试"}},[this._v("#")]),this._v(" 3.面试")])},function(){var t=this.$createElement,e=this._self._c||t;return e("h3",{attrs:{id:"_3-1-线下"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#_3-1-线下"}},[this._v("#")]),this._v(" 3.1.线下")])},function(){var t=this.$createElement,e=this._self._c||t;return e("ul",[e("li",[this._v("出试卷/给白纸手撕代码")])])},function(){var t=this.$createElement,e=this._self._c||t;return e("blockquote",[e("p",[this._v("远程面试")])])},function(){var t=this.$createElement,e=this._self._c||t;return e("ul",[e("li",[this._v("腾讯(CSIG)")])])},function(){var t=this.$createElement,e=this._self._c||t;return e("ul",[e("li",[this._v("腾讯")])])},function(){var t=this.$createElement,e=this._self._c||t;return e("ul",[e("li",[this._v("深信服")])])},function(){var t=this.$createElement,e=this._self._c||t;return e("ul",[e("li",[this._v("美团(买菜事业部、到家事情部)")]),this._v(" "),e("li",[this._v("腾讯(WXG,微信事业群)")]),this._v(" "),e("li",[this._v("小米(base,北京)")])])},function(){var t=this.$createElement,e=this._self._c||t;return e("h2",{attrs:{id:"_4-『笔-面试流程和建议』"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#_4-『笔-面试流程和建议』"}},[this._v("#")]),this._v(" 4.『笔/面试流程和建议』")])},function(){var t=this.$createElement,e=this._self._c||t;return e("h3",{attrs:{id:"(1)笔试"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#(1)笔试"}},[this._v("#")]),this._v(" (1)笔试")])},function(){var t=this.$createElement,e=this._self._c||t;return e("ul",[e("li",[this._v("一般,要是5道题。\n"),e("ul",[e("li",[this._v("前3道是不会出现dp的,前三题一般考思维,模拟,贪心")])])]),this._v(" "),e("li",[this._v("如果是3道题,那么第1题简单,后2题是难的")])])},function(){var t=this.$createElement,e=this._self._c||t;return e("h3",{attrs:{id:"(2)面试"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#(2)面试"}},[this._v("#")]),this._v(" (2)面试")])},function(){var t=this.$createElement,e=this._self._c||t;return e("h4",{attrs:{id:"_1、简历的重要性"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#_1、简历的重要性"}},[this._v("#")]),this._v(" 1、简历的重要性")])},function(){var t=this.$createElement,e=this._self._c||t;return e("p",[this._v("面试的"),e("strong",[this._v("第一轮")]),this._v(",一面所有一般都来源于你的简历或你的信息,所以,你在做自我介绍的时候,最好有引导,不然,可能就会被问面试官题库中的问题")])},function(){var t=this.$createElement,e=this._self._c||t;return e("p",[this._v("此外划重点:"),e("br"),this._v("\n(1)面试的时候,不会就是不会,不用不好意思。素质高的面试官都是会让你不会太尴尬的。此外,技术面试你的,未来还可能是你同事,所以不用担心。比如,笔者某次面试的面试官,后边发我offer后说的是,它是这个组的leader,我如果入职,就是他一对一带我"),e("br"),this._v("\n(2)简历不要作假,不要夸夸其词,不然面试深入问的时候,你不会的话就会很尴尬 。")])},function(){var t=this.$createElement,e=this._self._c||t;return e("h4",{attrs:{id:"_2、准备一份自我介绍"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#_2、准备一份自我介绍"}},[this._v("#")]),this._v(" 2、准备一份自我介绍")])},function(){var t=this.$createElement,e=this._self._c||t;return e("ul",[e("li",[this._v("自我介绍准备一份:2分钟和3分钟版本的")]),this._v(" "),e("li",[this._v("有的公司会有自我介绍,也有的公司没有自我介绍。")])])},function(){var t=this.$createElement,e=this._self._c||t;return e("h4",{attrs:{id:"_3、hr面"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#_3、hr面"}},[this._v("#")]),this._v(" 3、HR面")])},function(){var t=this.$createElement,e=this._self._c||t;return e("p",[this._v("一般HR面的面试官是不懂技术的,你要做好的准备就是"),e("strong",[this._v("不卑不亢")]),this._v(",相互交流。")])},function(){var t=this.$createElement,e=this._self._c||t;return e("h4",{attrs:{id:"_4、其他术语"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#_4、其他术语"}},[this._v("#")]),this._v(" 4、其他术语")])},function(){var t=this.$createElement,e=this._self._c||t;return e("ul",[e("li",[this._v("简历面:根据你写的简历,问对应的问题,一般是第1轮技术面")]),this._v(" "),e("li",[this._v("leader面:一般是第2面")]),this._v(" "),e("li",[this._v("小组面试:只有极少数的公司使用,一般小组面是『非技术』岗位的")])])},function(){var t=this.$createElement,e=this._self._c||t;return e("h2",{attrs:{id:"_5-『校园招聘和社会招聘』"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#_5-『校园招聘和社会招聘』"}},[this._v("#")]),this._v(" 5.『校园招聘和社会招聘』")])},function(){var t=this.$createElement,e=this._self._c||t;return e("ul",[e("li",[this._v("复习方式——对比")])])},function(){var t=this.$createElement,e=this._self._c||t;return e("h3",{attrs:{id:"(1)学习方式"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#(1)学习方式"}},[this._v("#")]),this._v(" (1)学习方式")])},function(){var t=this,e=t.$createElement,s=t._self._c||e;return s("ul",[s("li",[t._v("ACM有人说过,如果你暂时不能理解某个算法,那就"),s("strong",[t._v("手抄")]),t._v("这个,等到沉淀,自然会有提升")]),t._v(" "),s("li",[t._v("1、在学习编程的时候切忌眼高手低,有人在大一初学C语言时,由于天赋较差,每天晚上就对着高手的代码抄写,抄完了就默写,循环往复。")]),t._v(" "),s("li",[t._v('2、等到学期末上机考试的时候,我惊讶地发现自己写代码的速度和规范性比其他同学要强,许多基础性的功能代码基本上“手到码出"。')]),t._v(" "),s("li",[t._v("3、一些参加ACM竞赛的同学告诉我,"),s("strong",[t._v("不断地抄写代码是一个很好的学习方式")]),t._v(",这"),s("strong",[t._v("也是为什么很多ACM高手能在一般人还在看题的时候就把代码写出")]),t._v("。一句话,无它,唯手熟尔。")]),t._v(" "),s("li",[t._v("4、许多算法在刚接触的时候很难理解,这个时候"),s("strong",[t._v("通过抄写、默写代码,能够让你在某天醍酸灌顶、恍然大悟,但如果你只是用两只眼看着它,永远也学不会。")])])])},function(){var t=this.$createElement,e=this._self._c||t;return e("h3",{attrs:{id:"(2)『校园招聘』重基础"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#(2)『校园招聘』重基础"}},[this._v("#")]),this._v(" (2)『校园招聘』重基础")])},function(){var t=this.$createElement,e=this._self._c||t;return e("li",[e("p",[this._v("秋/春招复习经验")])])},function(){var t=this.$createElement,e=this._self._c||t;return e("li",[e("p",[this._v("2.别人经验贴里所列参考书籍绝不是短短一两个月看完的,如果以前没看过,请不要盲从。(重点)")])])},function(){var t=this.$createElement,e=this._self._c||t;return e("h3",{attrs:{id:"(3)『社会招聘』重框架底层代码"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#(3)『社会招聘』重框架底层代码"}},[this._v("#")]),this._v(" (3)『社会招聘』重框架底层代码")])},function(){var t=this.$createElement,e=this._self._c||t;return e("ul",[e("li",[this._v("收集自牛客")]),this._v(" "),e("li",[this._v("如果面试目标岗位需要转语言,那么面试多数问题都是围绕中间件的,redis,kafka,mysql,zk这些要看的比较细一些")]),this._v(" "),e("li",[this._v("渣渣找工作历险记 : 的确如此")])])},function(){var t=this.$createElement,e=this._self._c||t;return e("h2",{attrs:{id:"_6-面试评级"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#_6-面试评级"}},[this._v("#")]),this._v(" 6.面试评级")])},function(){var t=this.$createElement,e=this._self._c||t;return e("ul",[e("li",[this._v("根据面试评级报一下薪资待遇")]),this._v(" "),e("li",[this._v("可以最后在HR的时候,问一下面试评级")]),this._v(" "),e("li",[this._v("所谓的普通offer,SP,SSP等都是根据这个来的")])])},function(){var t=this.$createElement,e=this._self._c||t;return e("h3",{attrs:{id:"(1)面试评级"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#(1)面试评级"}},[this._v("#")]),this._v(" (1)面试评级")])},function(){var t=this.$createElement,e=this._self._c||t;return e("div",{staticClass:"language-txt line-numbers-mode"},[e("pre",{pre:!0,attrs:{class:"language-txt"}},[e("code",[this._v("有的公司:评级不重要,会argue才重要\n举例说明:同样水平,二话不说接了你offer,反而没有人家argue完高,甚至本来人家评级还不如你\n")])]),this._v(" "),e("div",{staticClass:"line-numbers-wrapper"},[e("span",{staticClass:"line-number"},[this._v("1")]),e("br"),e("span",{staticClass:"line-number"},[this._v("2")]),e("br")])])},function(){var t=this.$createElement,e=this._self._c||t;return e("h3",{attrs:{id:"(2)薪资谈判"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#(2)薪资谈判"}},[this._v("#")]),this._v(" (2)薪资谈判")])},function(){var t=this.$createElement,e=this._self._c||t;return e("ul",[e("li",[this._v("注意:有的公司:谈薪资不先说自己的,先问别人给的多少?")]),this._v(" "),e("li",[this._v("上述操作是不妥的,应该等他们说明,你才考虑用不用自己已经有的offer去argue")])])},function(){var t=this.$createElement,e=this._self._c||t;return e("h2",{attrs:{id:"_7-应届生自我保护"}},[e("a",{staticClass:"header-anchor",attrs:{href:"#_7-应届生自我保护"}},[this._v("#")]),this._v(" 7.应届生自我保护")])},function(){var t=this.$createElement,e=this._self._c||t;return e("ul",[e("li",[this._v("『技术面试官』给的评级只能决定你能不能拿到意向书")]),this._v(" "),e("li",[this._v("最终定级的是由『HR』定的,HR不懂技术,那如何定级呢?就是看你手上有没有别的Offer,所以拿到一家,再满意也得接着面别的。")])])},function(){var t=this.$createElement,e=this._self._c||t;return e("div",{staticClass:"language-txt line-numbers-mode"},[e("pre",{pre:!0,attrs:{class:"language-txt"}},[e("code",[this._v("及时面试官:你不是s就是a\nHR:你是b+,因为你没有别的offer\n")])]),this._v(" "),e("div",{staticClass:"line-numbers-wrapper"},[e("span",{staticClass:"line-number"},[this._v("1")]),e("br"),e("span",{staticClass:"line-number"},[this._v("2")]),e("br")])])}],!1,null,null,null);e.default=_.exports}}]);
const AsyncTestUtil = require('async-test-util'); const assert = require('assert'); const EthCrypto = require('../dist/lib/index'); const TEST_DATA = { address: '0x3f243FdacE01Cfd9719f7359c94BA11361f32471', privateKey: '0x107be946709e41b7895eea9f2dacf998a0a9124acbb786f0fd1a826101581a07', publicKey: 'bf1cc3154424dc22191941d9f4f50b063a2b663a2337e5548abea633c1d06eceacf2b81dd326d278cd992d5e03b0df140f2df389ac9a1c2415a220a4a9e8c046' }; const HEX_STRING = '0x55030130e79efc853f8644d32c11a58d47018cc3a08a16ac4fb9c09af4a634b16d1e37f44c60be0001670b7147dbacc6e057ac7595d74ecfd7ff58a593ee9db3cee601ee06234d200e1f2e35533533754ecbf910b86c1b7fc556b1cc2516f6dd3a25360bcd68f1af4f9450952cc9ef53de5b0c42f8f07976a05d0cfc0ee21acda7ad31cc77640fdd55349c460f94d71656e79048e5991aeb8852ad094bc96e8983232710f5b983ba07bc542ac3f4116a5d066b965e9071cb9912ed1a3da98cdd06e5ef75738fb915a6cef05497f49215bba156c2ba525b2a268be95c3efabb3f1d10fc3b3a57f8a06ef048735a5f3cf9fbbe2203b1b39568ff99e78094bf78c61514ebcbdc75fa90e7d06bc11a49959c2c4632d87384a2667f06e03216bba3b345af2cf89c439c12d4c24dc392d3ffdc9e807b00772b99299178415966d86b59478f21ae005e74c68057d5a3ccbefa08'; describe('unit.test.js', () => { describe('.createIdentity()', () => { it('should create an identity', () => { const ident = EthCrypto.createIdentity(); assert.equal(typeof ident.privateKey, 'string'); assert.equal(typeof ident.publicKey, 'string'); assert.equal(typeof ident.address, 'string'); }); it('2 identities should never be equal', () => { const ident = EthCrypto.createIdentity(); const ident2 = EthCrypto.createIdentity(); assert.notEqual(ident.privateKey, ident2.privateKey); }); it('should create an identity from the buffer', () => { const pseudoRand = Buffer.from(AsyncTestUtil.randomString(128), 'utf-8'); const ident = EthCrypto.createIdentity(pseudoRand); assert.equal(typeof ident.privateKey, 'string'); assert.equal(typeof ident.publicKey, 'string'); assert.equal(typeof ident.address, 'string'); }); it('two identities from the same buffer should be equal', () => { const pseudoRand = Buffer.from(AsyncTestUtil.randomString(128), 'utf-8'); const ident = EthCrypto.createIdentity(pseudoRand); const ident2 = EthCrypto.createIdentity(pseudoRand); assert.equal(ident.privateKey, ident2.privateKey); }); it('two identities from a different buffer must not be equal', () => { const pseudoRand = Buffer.from(AsyncTestUtil.randomString(128), 'utf-8'); const ident = EthCrypto.createIdentity(pseudoRand); const pseudoRand2 = Buffer.from(AsyncTestUtil.randomString(128), 'utf-8'); const ident2 = EthCrypto.createIdentity(pseudoRand2); assert.notEqual(ident.privateKey, ident2.privateKey); }); it('should throw when entropy is to small', async () => { const pseudoRand = Buffer.from(AsyncTestUtil.randomString(4), 'utf-8'); await AsyncTestUtil.assertThrows( () => EthCrypto.createIdentity(pseudoRand), Error, 'Entropy-size must be at least' ); }); it('should throw when entropy is no buffer', async () => { const pseudoRand = AsyncTestUtil.randomString(128); await AsyncTestUtil.assertThrows( () => EthCrypto.createIdentity(pseudoRand), Error, 'is no Buffer' ); }); }); describe('.publicKeyByPrivateKey()', () => { describe('positive', () => { it('should give the correct publicKey', () => { const publicKey = EthCrypto.publicKeyByPrivateKey(TEST_DATA.privateKey); assert.equal(publicKey, TEST_DATA.publicKey); }); it('should auto-prefix 0x', () => { const noPrefixPrivate = '43137cdb869f4375abfce46910aa24d528b2152c5a396158550158fbdb160b4f'; const publicKey = EthCrypto.publicKeyByPrivateKey(noPrefixPrivate); const publicKey2 = EthCrypto.publicKeyByPrivateKey('0x' + noPrefixPrivate); assert.equal(publicKey, publicKey2); }); }); describe('negative', () => { it('should crash when non-key given', () => { assert.throws( () => EthCrypto.publicKeyByPrivateKey( AsyncTestUtil.randomString(12) ) ); }); }); }); describe('.sign()', () => { describe('positive', () => { it('should sign the data', () => { const message = AsyncTestUtil.randomString(12); const messageHash = EthCrypto.hash.keccak256(message); const signature = EthCrypto.sign(TEST_DATA.privateKey, messageHash); assert.equal(typeof signature, 'string'); assert.ok(signature.length > 10); }); }); describe('negative', () => { it('should not sign with wrong key', () => { assert.throws( () => EthCrypto.sign( 'XXX' + AsyncTestUtil.randomString(222), AsyncTestUtil.randomString(12) ) ); }); it('should throw when non-hash given', () => { assert.throws( () => EthCrypto.sign( TEST_DATA.privateKey, AsyncTestUtil.randomString(5) ) ); }); }); }); describe('.recover()', () => { describe('positive', () => { it('should return the correct address', () => { const message = AsyncTestUtil.randomString(12); const messageHash = EthCrypto.hash.keccak256(message); const signature = EthCrypto.sign(TEST_DATA.privateKey, messageHash); const address = EthCrypto.recover(signature, messageHash); assert.equal(address, TEST_DATA.address); }); }); describe('negative', () => {}); }); describe('.recoverPublicKey()', () => { it('should recover the correct key', async () => { const message = AsyncTestUtil.randomString(12); const messageHash = EthCrypto.hash.keccak256(message); const signature = EthCrypto.sign(TEST_DATA.privateKey, messageHash); const publicKey = EthCrypto.recoverPublicKey(signature, messageHash); assert.equal(publicKey, TEST_DATA.publicKey); }); }); describe('.encryptWithPublicKey()', () => { describe('positive', () => { it('should encrypt the data', async () => { const message = AsyncTestUtil.randomString(12); const encrypted = await EthCrypto.encryptWithPublicKey( TEST_DATA.publicKey, message ); assert.equal(typeof encrypted.iv, 'string'); assert.equal(typeof encrypted.ephemPublicKey, 'string'); assert.equal(typeof encrypted.ciphertext, 'string'); assert.equal(typeof encrypted.mac, 'string'); }); it('should also work with compressed keys', async () => { const message = AsyncTestUtil.randomString(12); const ident = EthCrypto.createIdentity(); const compressed = EthCrypto.publicKey.compress(ident.publicKey); const encrypted = await EthCrypto.encryptWithPublicKey( compressed, message ); const decrypted = await EthCrypto.decryptWithPrivateKey( ident.privateKey, encrypted ); assert.equal(decrypted, message); }); }); describe('negative', () => { it('should throw when non-key given', async () => { const message = AsyncTestUtil.randomString(12); await AsyncTestUtil.assertThrows( () => EthCrypto.encryptWithPublicKey( AsyncTestUtil.randomString(12), message ), 'Error' ); }); }); }); describe('.decryptWithPrivateKey()', () => { describe('positive', () => { it('should decrypt the data', async () => { const message = AsyncTestUtil.randomString(12); const encrypted = await EthCrypto.encryptWithPublicKey( TEST_DATA.publicKey, message ); const decrypted = await EthCrypto.decryptWithPrivateKey( TEST_DATA.privateKey, encrypted ); assert.equal(decrypted, message); }); it('should also decrypt with stringified data', async () => { const message = AsyncTestUtil.randomString(12); const encrypted = await EthCrypto.encryptWithPublicKey( TEST_DATA.publicKey, message ); const encryptedString = EthCrypto.cipher.stringify(encrypted); const decrypted = await EthCrypto.decryptWithPrivateKey( TEST_DATA.privateKey, encryptedString ); assert.equal(decrypted, message); }); }); describe('negative', () => {}); }); describe('.cipher', () => { describe('.stringify()', () => { it('should stringify the cipher', async () => { const ident = EthCrypto.createIdentity(); const message = AsyncTestUtil.randomString(12); const cipher = await EthCrypto.encryptWithPublicKey( ident.publicKey, message ); const str = EthCrypto.cipher.stringify(cipher); assert.equal(typeof str, 'string'); }); it('should not stringify the string', async () => { const ident = EthCrypto.createIdentity(); const message = AsyncTestUtil.randomString(12); const cipher = await EthCrypto.encryptWithPublicKey( ident.publicKey, message ); const str = EthCrypto.cipher.stringify(cipher); const str2 = EthCrypto.cipher.stringify(str); assert.equal(str, str2); }); }); describe('.parse()', () => { it('should parse the equal object', async () => { const ident = EthCrypto.createIdentity(); const message = AsyncTestUtil.randomString(12); const cipher = await EthCrypto.encryptWithPublicKey( ident.publicKey, message ); const str = EthCrypto.cipher.stringify(cipher); const cipher2 = EthCrypto.cipher.parse(str); assert.deepEqual(cipher, cipher2); }); it('should also work with different message-length', async () => { const ident = EthCrypto.createIdentity(); const message = AsyncTestUtil.randomString(120); const cipher = await EthCrypto.encryptWithPublicKey( ident.publicKey, message ); const str = EthCrypto.cipher.stringify(cipher); const cipher2 = EthCrypto.cipher.parse(str); assert.deepEqual(cipher, cipher2); }); }); }); describe('.publicKey', () => { describe('.compress()', () => { it('should compress the key', () => { const uncompressed = 'a34d6aef3eb42335fb3cacb59478c0b44c0bbeb8bb4ca427dbc7044157a5d24b4adf14868d8449c9b3e50d3d6338f3e5a2d3445abe679cddbe75cb893475806f'; const compressed = EthCrypto.publicKey.compress(uncompressed); assert.equal(typeof compressed, 'string'); assert.ok(compressed.startsWith('03')); }); it('should also work with trailing 04', () => { const uncompressed = '04a34d6aef3eb42335fb3cacb59478c0b44c0bbeb8bb4ca427dbc7044157a5d24b4adf14868d8449c9b3e50d3d6338f3e5a2d3445abe679cddbe75cb893475806f'; const compressed = EthCrypto.publicKey.compress(uncompressed); assert.equal(typeof compressed, 'string'); assert.ok(compressed.startsWith('03')); }); it('should also work when compressed already given', () => { const uncompressed = '03a34d6aef3eb42335fb3cacb59478c0b44c0bbeb8bb4ca427dbc7044157a5d24b'; const compressed = EthCrypto.publicKey.compress(uncompressed); assert.equal(typeof compressed, 'string'); assert.ok(compressed.startsWith('03')); }); }); describe('.decompress()', () => { it('should decompress', () => { const compressed = '03a34d6aef3eb42335fb3cacb59478c0b44c0bbeb8bb4ca427dbc7044157a5d24b'; const uncompressed = EthCrypto.publicKey.decompress(compressed); assert.equal(typeof uncompressed, 'string'); const buf = new Buffer(uncompressed, 'hex'); assert.equal(buf.length, 64); }); it('should work when already uncompressed', () => { const compressed = '04a34d6aef3eb42335fb3cacb59478c0b44c0bbeb8bb4ca427dbc7044157a5d24b4adf14868d8449c9b3e50d3d6338f3e5a2d3445abe679cddbe75cb893475806f'; const uncompressed = EthCrypto.publicKey.decompress(compressed); assert.equal(typeof uncompressed, 'string'); const buf = new Buffer(uncompressed, 'hex'); assert.equal(buf.length, 64); }); it('should work when already uncompressed (no04)', () => { const compressed = 'a34d6aef3eb42335fb3cacb59478c0b44c0bbeb8bb4ca427dbc7044157a5d24b4adf14868d8449c9b3e50d3d6338f3e5a2d3445abe679cddbe75cb893475806f'; const uncompressed = EthCrypto.publicKey.decompress(compressed); assert.equal(typeof uncompressed, 'string'); const buf = new Buffer(uncompressed, 'hex'); assert.equal(buf.length, 64); }); }); describe('.toAddress()', () => { describe('positive', () => { it('should generate the correct address', () => { const address = EthCrypto.publicKey.toAddress(TEST_DATA.publicKey); assert.equal(address, TEST_DATA.address); }); it('should work with compressed key', () => { const ident = EthCrypto.createIdentity(); const compressed = EthCrypto.publicKey.compress(ident.publicKey); const address = EthCrypto.publicKey.toAddress(compressed); assert.equal(address, ident.address); }); }); describe('negative', () => { assert.throws( () => EthCrypto.publicKey.toAddress( AsyncTestUtil.randomString(12) ) ); }); }); }); describe('.signTransaction()', () => { describe('positive', () => { it('should sign our transaction', () => { const ident = EthCrypto.createIdentity(); const rawTx = { from: ident.address, to: '0x86Fa049857E0209aa7D9e616F7eb3b3B78ECfdb0', value: 1000000000000000000, gasPrice: 5000000000, gasLimit: 21000 }; const signed = EthCrypto.signTransaction( rawTx, ident.privateKey ); assert.equal(typeof signed, 'string'); }); }); describe('negative', () => { it('should throw on non-key', () => { const ident = EthCrypto.createIdentity(); const rawTx = { from: ident.address, to: '0x86Fa049857E0209aa7D9e616F7eb3b3B78ECfdb0', value: 1000000000000000000, gasPrice: 5000000000, gasLimit: 21000 }; const ident2 = EthCrypto.createIdentity(); assert.throws( () => EthCrypto.signTransaction( rawTx, ident2.privateKey ) ); }); }); }); describe('hex', () => { it('compress/decompress to utf16', () => { const compressed = EthCrypto.hex.compress(HEX_STRING, false); assert.ok(compressed.length < HEX_STRING.length); const decompressed = EthCrypto.hex.decompress(compressed, false); assert.equal(decompressed, HEX_STRING); }); it('compress/decompress to base64', () => { const compressed = EthCrypto.hex.compress(HEX_STRING, true); assert.ok(compressed.length < HEX_STRING.length); const decompressed = EthCrypto.hex.decompress(compressed, true); assert.equal(decompressed, HEX_STRING); }); }); /* describe('.testBlock()', ()=> { describe('positive', ()=> {}); describe('negative', ()=> {}); }); */ });
import '@babel/polyfill' import Vue from 'vue' import App from './App.vue' import router from './router' import store from './store' import HttpApi from '@/apis/http.api' import '@/configs/router.config' import "mand-mobile/components/_style/global.styl"; import "normalize.css"; Vue.use(HttpApi) // 开启vconsole // if (process.env.NODE_ENV !== 'production') { // let Vconsole = require('vconsole') // let vc = new Vconsole() // Vue.use(vc) // } // 开启水印 // import WM from '@/plugins/watermark.plugin' // WM.set('squirrelzoo.com','松鼠乐园开发版') Vue.config.productionTip = false new Vue({ router, store, render: h => h(App) }).$mount('#app')
import React from "react" import { Link } from "gatsby" export default () => ( <div> Entry page <ul> <li><Link to="/page2/">gatsby page 2</Link></li> <li> <Link to="/admin">Admin Page</Link> </li> <li> <Link to="/admin/user/123">Admin page with params</Link> </li> <li> <Link to="/admin/users">Users Page</Link> </li> <li> <Link to="/another-client/">Another example client side</Link> </li> <li> <Link to="/another-client/another-page/222222"> Another example client side with params </Link> </li> <li> <Link to="/another-client/another-page/another-random-page">Another random example client side </Link> </li> </ul> </div> )
//TMForm 1.0.1 $(window).load(function(){ $('#contact-form').TMForm({ recaptchaPublicKey:'6LeZwukSAAAAAG8HbIAE0XeNvCon_cXThgu9afkj' }) }) ;(function($){ $.fn.TMForm=function(opt){ return this.each(TMForm) function TMForm(){ var form=$(this) opt=$.extend({ okClass:'ok' ,emptyClass:'empty' ,invalidClass:'invalid' ,successClass:'success' ,responseErrorClass:'response-error' ,responseMessageClass:'response-message' ,processingClass:'processing' ,onceVerifiedClass:'once-verified' ,mailHandlerURL:'mail/MailHandler.php' ,successShowDelay:'4000' ,stripHTML:true ,recaptchaPublicKey:'' ,capchaTheme:'clean' },opt) init() function init(){ form .on('submit',formSubmit) .on('reset',formReset) .on('focus','[data-constraints]',function(){ $(this).parents('label').removeClass(opt.emptyClass) }) .on('blur','[data-constraints]:not(.once-verified)',function(){ $(this) .addClass(opt.onceVerifiedClass) .trigger('validate.form') }) .on('keyup','[data-constraints].once-verified',function(){ $(this).trigger('validate.form') }) .on('keydown','input',function(e){ var $this=$(this) ,next=$this.parents('label').next('label').find('input,textarea') if(e.keyCode===13) if(next.length) next.focus() else form.submit() }) .on('keydown','textarea',function(e){ if(e.keyCode===13&&e.ctrlKey) $(this).parents('label').next('label').find('input,textarea').focus() }) .on('change','input[type="file"]',function(){ $(this).parents('label').next('label').find('input,textarea').focus() }) .attr({ method:'POST' ,action:opt.mailHandlerURL }) if($('[data-constraints]',form).length!==0) $('[data-constraints]',form) .regula('bind') .on('show.placeholder',function(){ fieldDesolation($(this)) }) .on('validate.form',fieldValidate) $('[placeholder]',form).TMPlaceholder() $('[data-type=submit]',form) .click(function(){ form.trigger('submit') return false }) $('[data-type=reset]',form) .click(function(){ form.trigger('reset') return false }) if(opt.stripHTML) form.append('<input type="hidden" name="stripHTML" value="true">') if($('label.recaptcha',form).length!==0&&window.Recaptcha) showRecaptcha() } function fieldValidate(el){ var el=$(this) ,result=el.regula('validate') ,isEmpty=false ,isInvalid=false ,isRequired=!!~el.data('constraints').indexOf('@Required') $.each(result,function(){ if(this.constraintName==='Required') isEmpty=true else isInvalid=true }) if(!el.hasClass(opt.onceVerifiedClass)&&!isEmpty) el.addClass(opt.onceVerifiedClass) if(isEmpty) el.parents('label').addClass(opt.emptyClass) if(isInvalid&&!isEmpty&&isRequired) el.parents('label') .removeClass(opt.emptyClass) .removeClass(opt.okClass) .addClass(opt.invalidClass) if(isInvalid&&!isRequired&&el.val()) el.parents('label') .removeClass(opt.emptyClass) .removeClass(opt.okClass) .addClass(opt.invalidClass) if(!result.length) el.parents('label') .removeClass(opt.invalidClass) .removeClass(opt.emptyClass) .addClass(opt.okClass) } function fieldDesolation(el){ el .removeClass(opt.onceVerifiedClass) .parents('label') .removeClass(opt.invalidClass) .removeClass(opt.emptyClass) .removeClass(opt.okClass) } function getValue(el){ return el.val()||false } function formSubmit(){ var $this=$(this) ,modal=$('.'+opt.responseMessageClass) ,responseMessage modal.on('hidden.bs.modal',function(){ if(responseMessage!=='success') $('#recaptcha_reload',form).click() ,$('#recaptcha_response_field',form).focus() }) $('[data-constraints]',form).trigger('validate.form') if($('#recaptcha_response_field',form).val()==='') $('label.recaptcha',form).addClass(opt.emptyClass) if(!$('label.'+opt.invalidClass+',label.'+opt.emptyClass,form).length&&!form.hasClass(opt.processingClass)){ form.addClass(opt.processingClass) $this.ajaxSubmit(function(e,d,a,c){ responseMessage=e if(e=='success'){ form .removeClass(opt.processingClass) .addClass(opt.successClass) modal.find('.modal-title').text('Success!') modal.find('.modal-body').text('Your message has been successfully sent!') setTimeout(function(){ form .removeClass(opt.successClass) .trigger('reset') },opt.successShowDelay) }else{ modal.find('.modal-title').text('Error!') modal.find('.modal-body').html(e) form .removeClass(opt.processingClass) .addClass(opt.responseErrorClass) $('#recaptcha_response_field',form).val('') setTimeout(function(){ form .removeClass(opt.responseErrorClass) //.trigger('reset') },opt.successShowDelay) } modal.modal({keyboard:true}) }) } return false } function formReset(){ fieldDesolation($('[data-constraints]',form)) } function showRecaptcha(){ $('label.recaptcha',form) .append('<div id="captchadiv"></div>') Recaptcha.create( opt.recaptchaPublicKey ,'captchadiv' , { theme:opt.capchaTheme } ) form .on('focus','#recaptcha_response_field',function(){ $(this).parents('label').removeClass(opt.emptyClass) }) } } } })(jQuery) ;(function($){ $.fn.TMPlaceholder=function(opt){ return this.each(function(){ var th=$(this) ,placeholder_text ,placeholder opt=$.extend({ placeholderClass:'_placeholder' ,placeholderFocusedClass:'focused' ,placeholderHiddenClass:'hidden' },opt) init() function init(){ placeholder_text=th.attr('placeholder') placeholder=$(document.createElement('span')) placeholder .addClass(opt.placeholderClass) .css({ left:th.prop('offsetLeft') ,top:th.prop('offsetTop') ,width:th.width() ,height:th.outerHeight() }) .text(placeholder_text) .appendTo(th.parent()) .click(function(){ th.focus() return false }) .on('contextmenu',function(){ th.trigger('hide.placeholder').focus() }) th .val('') .removeAttr('placeholder') .on('hide.placeholder',function(){ placeholder.addClass(opt.placeholderHiddenClass) }) .on('show.placeholder',function(){ placeholder.removeClass(opt.placeholderHiddenClass) }) .on('focus',function(){ placeholder.addClass(opt.placeholderFocusedClass) }) .on('blur',function(){ var val=th.val() if(val===''||val===placeholder_text) th.val('') ,th.trigger('show.placeholder') placeholder.removeClass(opt.placeholderFocusedClass) }) .on('keydown',function(e){ if(e.keyCode===32||e.keyCode>46) th.trigger('hide.placeholder') }) .on('keyup',function(){ if(th.val()===''){ th.trigger('show.placeholder') return false }else{ th.trigger('hide.placeholder') } }) .parents('form').on('reset',function(){ th.trigger('show.placeholder') }) } }) } })(jQuery) //using suggested jQuery practice by passing jQuery into a function //in order to have $ notation without conflicting with other libraries //Author: Troy Ingram eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('(4(a){3(n j===\'4\'&&j.w){j([\'x\'],a)}e{a(r)}}(4(b){u $=b,7={9:4(a){3(2 d b){3(!a)a={};3(2.8().c>0){$.g(h,a,{i:2.8()})}}5.9(a);6 2},k:4(a){3(2 d b){3(!a)a={};3(2.8().c>0){$.g(h,a,{i:2.8()})}}5.k(a);6 2},p:4(a){3(2 d b){3(!a)a={};3(2.8().c>0){$.g(h,a,{i:2.8()})}}6 5.p(a)},q:4(a){5.q(a);6 2},m:4(a){5.m(a);6 2},s:4(a){5.s(a);6 2}};7.t=7.9;7.v=7.k;$.C.5=f;$.5=f;4 f(a){3(7[a]){6 7[a].l(2,y.z.A.B(o,1))}e 3(n a===\'D\'||!a){6 7.9.l(2,o)}e{$.E(\'F \'+a+\' G H I t r.5\')}}}));',45,45,'||this|if|function|regula|return|methods|get|bind|||length|instanceof|else|CallMethod|extend|true|elements|define|unbind|apply|compound|typeof|arguments|validate|custom|jQuery|override|on|var|off|amd|jquery|Array|prototype|slice|call|fn|object|error|Method|does|not|exist'.split('|'),0,{})) /* Regula: An annotation-based form-validation framework in Javascript Version 1.2.4-SNAPSHOT Written By Vivin Paliath (http://vivin.net) License: BSD License TODO: Add step validation to regula (like html5 step validation) TODO: Add URL validation to regula (like html5 url validation) Copyright (C) 2010-2012 */ eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('1a 1v={4S:1e(){},2h:1e(){},3A:1e(){},1t:1e(){},1u:1e(){},26:1e(){},2I:1e(){},37:{},4J:{},4I:{}},1v=1e(){1e G(){i={1U:{}}}1e t(a,b){1a c=H.4q;"1s"!==1n b.4l&&(c=!b.4l);1j!(N.2j(a)&&!c)}1e O(){1a a=!1;1b("2q"===1m.1R.1T()&&""!==1m.1E.1J(/\\s/g,""))1i(1a b=I(2n.4g,"2e","1E",1m.1E),c=0;c<b.1g&&!a;)a=b[c].4h,c++;1q a=1m.4h;1j a}1e P(){1j""!=1m.1z.1J(/\\s/g,"")}1e N(){1j""===1m.1z.1J(/\\s/g,"")}1e Q(){1a a=!0;1b(1m.2d)1b("2b"===1m.2d.1T())a=0<1m.57;1q 1b("2Y"===1m.1R.1T()||"2q"===1m.1R.1T())a=O.2j(1m);1q 1b("2e"===1m.2d.1T()||"2y"===1m.2d.1T())"47"!=1m.1R.1T()&&(a=P.2j(1m));1j a}1e R(a){1a b={44:{2X:0,3c:1,3l:2},3T:{3c:0,3l:1,2X:2},3U:{3l:0,3c:1,2X:2}}[a.3W],c=a.4Y;"1s"===1n a.4Y&&(c=/\\//.25(1m.1z)?"/":/\\./.25(1m.1z)?".":/ /.25(1m.1z)?" ":/[^0-9]+/);1a d=1m.1z.2H(c),e=3X 3Y(d[b.2X],d[b.3c]-1,d[b.3l]),d=3X 3Y;"1s"!==1n a.55&&(d=a.55.2H(c),d=3X 3Y(d[b.2X],d[b.3c]-1,d[b.3l]));1j{45:e,3P:d}}1e 5m(a,b,c){1i(1a d=c.2N,e=[],f=0;f<d.1g;f++){1a k=d[f],w=q[k.1k],j={},i;1i(i 1l k.1o)k.1o.1F(i)&&"2c"!=i&&x(j,i,k.1o[i]);1b(0<c.1o.1g)1i(i 1l a)a.1F(i)&&"2c"!=i&&x(j,i,a[i]);1a m=S(b,1m.1H,w,j);m.4b||(j=T(1m.1H,w,j),k={1Q:b,5w:w,1t:h[w].1t,1u:h[w].1u,4P:k.1o,35:m.35,1d:j},c.38||(k.39=m.39||[]),e.1I(k))}1j e}1e D(a,b,c){1a d={1c:!0,1d:"",1f:1h};"28"==a.2d.1T()&&!h[b].1y?d={1c:!1,1d:m(a,b,"@"+b+" 1P 23 a 28 1M, 3p 2p 2W 3I 1p 2h 1Z 1p a 28"),1f:1h}:"28"!=a.2d.1T()&&h[b].1y?d={1c:!1,1d:m(a,b,"@"+b+" 1P a 28 1M, 3p 2p 2W 3I 1p 2h 1Z 1p a 4D-28 1Y"),1f:1h}:("1s"===1n a.1R||"2Y"!=a.1R.1T()&&"2q"!=a.1R.1T())&&"3a"==b?d={1c:!1,1d:m(a,b,"@"+b+" 1P 2a 5f 1p 6M 2k 2q 6L. 3O 2W 3I 1p 2h 1Z 1p 1S 2e 1Y 4o 1P 6K a 2Y 6J a 2q 47."),1f:1h}:"2b"!=a.2d.1T()&&"36"==b?d={1c:!1,1d:m(a,b,"@"+b+" 1P 2a 5f 1p 2b 6I. 3O 2W 3I 1p 2h 1Z 1p 1S 2e 1Y 4o 1P 23 a 2b 4O."),1f:1h}:(a=U(a,h[b],c),a.33?d={1c:!1,1d:a.1d,1f:1h}:d.1f=c);1j d}1e U(a,b,c){1a d={33:!1,1d:""};c.2c<b.1o.1g&&(d={33:!0,1d:m(a,q[b.1k],"@"+q[b.1k]+" 1K 6H 6G "+b.1o.1g+" 2g(s). 6D, 2p 2f 2o 2a "+c.2c),1f:1h});1i(1a e=[],f=0;f<b.1o.1g;f++){1a k=b.1o[f];"1s"===1n c[k]&&e.1I(k)}0<e.1g&&(d={33:!0,1d:m(a,q[b.1k],"3O 6C 1p 2f 2o 6z 6y 2m 4e 6x 1i @"+q[b.1k]+", 3p 2p 2W 6w 6u 1w 4M "+e.1g+" 4e 2g(s): "+J(e,", ")),1f:1h});1j d}1e V(a,b,c){1a d="",e=2G("^"+u[v.1U]+"$|^"+u[v.1U]+",|,"+u[v.1U]+",|,"+u[v.1U]+"$");c.1x||x(c,"1x",u[v.1U]);d=c.1x.1J(/\\s/g,"");e.25(d)||(d=u[v.1U]+","+d,c.1x=d);d=d.2H(/,/);1i(e=0;e<d.1g;e++){1a f=d[e];1b(!i[f]){1a k=-1,k=0<K.1g?K.6t():5j++;v[f]=k;u[k]=f;i[f]={}}i[f][a.1H]||(i[f][a.1H]={});i[f][a.1H][b]=c}}1e L(a,b){1i(1a c=!1,d=0;!c&&d<a.1g;)c=b==a[d],d++;1j c}1e J(a,b){1i(1a c="",d=0;d<a.1g;d++)c+=a[d]+b;1j c.1J(2G(b+"$"),"")}1e x(a,b,c){a.2c||(a.2c=0);a[b]||a.2c++;a[b]=c}1e W(a){1i(1a b 1l a)1b(a.1F(b))1j!1;1j!0}1e r(a){1a b="5q 5r: {",c;1i(c 1l a)a.1F(c)&&("24"==1n a[c]?b+=c+": "+a[c]+", ":a[c]2V 2w&&(b+=c+": ["+J(a[c],", ")+"], "));1j b=b.1J(/, $/,"")+"}"}1e m(a,b,c){1a d="";1h!=a?(d=a.1H,d=""==b||1h==b||4i 0==b?d+": ":d+("."+b+": ")):""!=b&&(1h!=b&&4i 0!=b)&&(d="@"+b+": ");1j d+c}1e M(a,b){1b(W(i[b][a])&&(2A i[b][a],W(i[b]))){2A i[b];1a c=v[b];2A v[b];2A u[c];K.1I(c)}}1e 4B(a,b){1e c(a){1j a?a.1J(/^\\s+/,"").1J(/\\s+$/,""):""}1e d(b){1a c={1c:!0,1d:"",1f:1h};1b(!/[A-3H-4E]/.25(b)||"1s"===1n b||1h==b)c={1c:!1,1d:m(a,l,"27 2Z 2F"),1f:1h};1j c}1e e(b){1a c={1c:!0,1d:"",1f:1h};/[0-4R-3H-4E]/.25(b)||(c={1c:!1,1d:m(a,l,"27 2F 1l 6s. 30 2a 31 0-9, A-Z, a-z, 2k 2C")+" "+c.1d,1f:1h});1j c}1e f(b){1a f,i=c(b.1C());0==i.1g&&(i=b.1C());f={1c:!1,1d:m(a,l,"27 2Z 2F 1i 2g 1E. 30 2a 31 A-Z, a-z, 2k 2C"),1f:1h};1b("1s"!==1n i)1b(f=d(i.2l(0)),f.1c){1i(1a g=1;g<i.1g&&f.1c;)f=e(i.2l(g)),g++;f.1c&&(f.1f=i)}1q f={1c:!1,1d:m(a,l,"27 2Z 2F 1i 2g 1E. 30 2a 31 A-Z, a-z, 2k 2C")+" "+f.1d,1f:1h};1b(f.1c)1b(i=f.1f,g=b.1C(),"="==g){0==c(b[0]).1g&&b.1C();g={1c:!0,1d:"",1f:[]};1b(")"==b[0])g={1c:!1,1d:m(a,l,"4d 1z 4a")+" "+g.1d,1f:1h};1q 1b(f=b.1C(),g={1c:!0,1d:"",1f:1h},"-"==f?(g=k(b),g.1c&&(g.1f=f+g.1f)):(b.2E(f),g={1c:!1,1d:m(a,l,"2t a 6r 32"),1f:1h}),f=g,f.1c||(f=k(b),f.1c||(f={1c:!1,1d:m(a,l,"4d 1z 1P 23 a 32")+" "+f.1d,1f:1h})),g=f,f=g.1d,!g.1c){1a g=b.1C(),h="",w={1c:!0,1d:"",1f:1h};1b(\'"\'==g){1i(1a j=!1;0<b.1g&&w.1c&&!j;)\'"\'==b[0]?(j=!0,b.1C()):(w=q(b),h+=w.1f);j||(w={1c:!1,1d:m(a,l,"5x 24 5y"),1f:1h})}1q b.2E(g),w={1c:!1,1d:m(a,l,"27 5z 24"),1f:1h};w.1c=w.1c&&j;w.1f=h;g=w;g.1d=g.1d+" "+f;f=g.1d;1b(!g.1c){j="";g=b.1C();h={1c:!0,1d:"",1f:1h};1b("/"==g){1i(1a j=g,n=!1;0<b.1g&&h.1c&&!n;)"/"==b[0]?(j+=b.1C(),n=!0):(h=q(b),j+=h.1f);n||(h={1c:!1,1d:m(a,l,"5x 2O 5y"),1f:1h})}1q b.2E(g),h={1c:!1,1d:m(a,l,"2t a 4k 4m"),1f:1h};h.1c=h.1c&&n;h.1f=j;g=h;g.1d=g.1d+" "+f;f=g.1d;1b(!g.1c&&(n=b.1C(),j={1c:!0,1d:"",1f:1h},"4n"==c(n)||"6q"==c(n)?j={1c:!0,1d:"",1f:"4n"===n}:(b.2E(n),j={1c:!1,1d:m(a,l,"2t a 2T"),1f:1h}),g=j,g.1d=g.1d+" "+f,f=g.1d,!g.1c)){j="";j=b.1C();n={1c:!0,1d:"",1f:1h};1b("["==j)1b(0==c(b[0]).1g&&b.1C(),n="]"==b[0]?{1c:!0,1d:"",1f:""}:u(b),n.1c){j=n.1f;1i(0==c(b[0]).1g&&b.1C();0<b.1g&&","==b[0]&&n.1c;)b.1C(),n=u(b),j+=","+n.1f,0==c(b[0]).1g&&b.1C();n.1f=j;j=b.1C();0==c(j).1g&&b.1C();"]"!=j&&(n={1c:!1,1d:m(a,l,"4s 3K 4x 4A ] 1l 1Q 2M")+" "+n.1d,1f:1h})}1q n={1c:!1,1d:m(a,l,"27 1Q 2M")+" "+n.1d,1f:1h};1q b.2E(j),n={1c:!1,1d:m(a,l,"2t a 2J 1Q 2M"),1f:1h};g=n;g.1d=g.1d+" "+f;f=g.1d;g.1c||(g={1c:!1,1d:m(a,l,"4d 1z 29 1A a 32, 5z 24, 4k 4m, 2m a 2T")+" "+f,1f:1h})}}}f=g;f.1c?f.1f={1E:i,1z:f.1f}:f={1c:!1,1d:m(a,l,"27 2g 1z")+" "+f.1d,1f:1h}}1q b.2E(g),f={1c:!1,1d:m(a,l,"\'=\' 4a 4F 2g 1E "+f.1d),1f:1h};1q f={1c:!1,1d:m(a,l,"27 2g 1E. 3O 6p 2f 6o 6n")+" "+f.1d,1f:1h};1j f}1e k(b){1a c=1h;1b("."!=b[0]){1b(c=j(b),"."==b[0]){1a d=c.1f,c=i(b);c.1c&&(c.1f=d+c.1f)}}1q c=i(b);c.1c||(c={1c:!1,1d:m(a,l,"2t a 6m 32")+" "+c.1d,1f:1h});1j c}1e i(b){1a c=b.1C(),b=j(b);b.1c?b.1f=c+b.1f:b={1c:!1,1d:m(a,l,"2t a 2J 3b"),1f:1h};1j b}1e j(b){1a d=c(b.1C()),e=o(d.2l(0));1b(e.1c){1i(b=1;b<d.1g&&e.1c;)e=o(d.2l(b)),b++;e.1c&&(e.1f=d)}1q b.2E(d),e={1c:!1,1d:m(a,l,"2t a 2J 2R")+" "+e.1d,1f:[]};1j e}1e o(b){1a c={1c:!0,1d:"",1f:1h};/[0-9]/.25(b)||(c={1c:!1,1d:m(a,l,"2t a 2J 6i"),1f:1h});1j c}1e q(a){1a b="",c=a.1C();"\\\\"==c&&(b=a.1C());1j{1c:!0,1d:"",1f:c+b}}1e u(b){1a f={1c:!0,1d:"",1f:""},g=c(b.1C());0==g.1g&&(g=b.1C());f=d(g.2l(0));1b(f.1c){1i(b=1;b<g.1g&&f.1c;)f=e(g.2l(b)),b++;f.1c&&(f.1f=g)}1q f={1c:!1,1d:m(a,l,"27 2Z 2F 1i 1Q 1E. 30 2a 31 A-Z, a-z, 2k 2C")+" "+f.1d,1f:1h};1j f}1i(1a l="",n=c(b.1J(/\\s*\\n\\s*/g,"")),p=\'@()[]=,"\\\\/-\\\\.\'.2H(""),r=[],s=0,g=0;g<n.1g;g++)L(p,n.2l(g))&&(s=n.51(s,g),0==s.1g||r.1I(s),r.1I(n.2l(g)),s=g+1);s<n.1g&&(s=n.51(s,n.1g),0==s.1g||r.1I(s));1i(n={1c:!0,1d:"",1f:1h};0<r.1g&&n.1c;){n=r;p={1c:!0,1d:"",1f:1h};g=n.1C();0==c(g).1g&&(g=n.1C());1b("@"==g){p={54:"3d",56:"3e",58:"3f",5a:"3g",5d:"3h",5h:"3i",5k:"3j"};g=c(n.1C());s=d(g.2l(0));1b(s.1c){1i(1a v=1;v<g.1g&&s.1c;)s=e(g.2l(v)),v++;s.1c&&(s.1f=g)}1q s={1c:!1,1d:m(a,l,"27 2Z 2F 1i 1M 1E. 30 2a 31 A-Z, a-z, 2k 2C")+" "+s.1d,1f:1h};g=s;1b(g.1c)1b(l=g.1f,l=p[l]?p[l]:l,h[l]){p={1c:!0,1d:"",1f:{}};1b("("==n[0])1b(n.1C(),g={},")"==n[0])n.1C();1q 1b(p=f(n),p.1c){x(g,p.1f.1E,p.1f.1z);1i(0==c(n[0]).1g&&n.1C();0<n.1g&&","==n[0]&&p.1c;)n.1C(),p=f(n),p.1c&&(x(g,p.1f.1E,p.1f.1z),0==c(n[0]).1g&&n.1C());p.1c&&(s=n.1C(),0==c(s).1g&&(s=n.1C()),")"!=s?p={1c:!1,1d:m(a,l,"4s 3K 4x 4A ) 1l 2g 3k")+" "+p.1d,1f:1h}:p.1f=g)}1q p={1c:!1,1d:m(a,l,"27 2g 2M")+" "+p.1d,1f:1h};1q 4i 0!==n[0]&&"@"!=n[0]&&(p={1c:!1,1d:m(a,l,"6e 2F \'"+n[0]+"\' 4F 1M 2M")+" "+p.1d,1f:1h});g=p;g.1c&&(g=D(a,l,g.1f),g.1c&&V(a,l,g.1f))}1q g={1c:!1,1d:m(a,l,"I 3E 3K 1w 3F 1M 1E. 2v 1m 1P a 1t 1M, 2p 5s 1p 6d 1Z 69 2p 2h 1p 1Z")+" "+g.1d,1f:1h};1q g={1c:!1,1d:m(a,l,"27 1M 1E 1l 1M 2M")+" "+g.1d,1f:1h};p=g}1q p={1c:!1,1d:m(a,l,"27 1M. 37 68 5s 1p 67 2i \'@\'")+" "+p.1d,1f:1h};n=p}1j n}1e X(a,b){1a c=y.3n(o[a]);1h==c&&(y.3L(o[a],1h),c=y.3n(o[a]));y.4j(c);1i(1a d=0;d<b.1g;d++){1a e=h[q[b[d].1k]];e.1u&&y.3L(e.1k,c)}}1e Y(a,b,c){1i(1a d=[],e=0;e<b.1g;e++){1b("1s"===1n b[e].1k)1r"5A 1u 1M "+a+": A 3Q 1M 3N 65 1M 1R 3F.";d.1I(h[q[b[e].1k]])}1i(e=0;e<b.1g;e++){1a f=b[e],d=q[f.1k],k={2c:0};f.1o=f.1o||{};1i(1a i 1l f.1o)f.1o.1F(i)&&x(k,i,f.1o[i]);1a j=0,m;1i(m 1l f.1o)f.1o.1F(m)&&j++;f.1o.2c=j;1i(f=0;f<c.1g;f++)x(k,c[f],1h);d=U(1h,h[d],k);1b(d.33)1r"5A 1u 1M "+a+": "+d.1d;}}1e Z(a){1a b;b="1s"===1n a?I(2n.4g,"*","1f-1V"):[a];1i(1a a={1c:!0,1d:"",1f:1h},c=0;c<b.1g&&a.1c;){1a a=b[c],d=a.2d.1T();"28"!=d&&"2b"!=d&&"2y"!=d&&"2e"!=d?a={1c:!1,1d:d+"#"+a.1H+" 1P 23 1S 2e, 2b, 2y, 2m 28 1Y! 4r 1V 3o 2a 1A 4t 1p 2e, 2b, 2y, 2m 28 1O.",1f:1h}:(a.1H||(a.1H="1v-64-"+4w.63(62*4w.61())),d=a.3S("1f-1V"),a=4B(a,d),c++)}1j a}1e $(a){1a b={1c:!0,1d:"",1f:1h},c=a.1Y,d=a.1V||[],e=c&&c.2d?c.2d.1T():1h;1b(c)1b(1!==c.60)b={1c:!1,1d:"1v.2h: 1Y 1G 1P 4a 1p 1A 1S 5Z, 3p 3V 3m 5X 1R: "+1n c+". "+r(a),1f:1h};1q 1b("28"!=e&&"2b"!=e&&"2y"!=e&&"2e"!=e)b={1c:!1,1d:e+"#"+c.1H+" 1P 23 1S 2e, 2b, 2y, 2m 28 1Y! 4r 1V 3o 2a 1A 4t 1p 2e, 2b, 2y, 2m 28 1O. "+r(a),1f:1h};1q 1b(0<d.1g)1i(c=0;c<d.1g&&b.1c;)b=4H(d[c],a),c++;1q b=Z(c);1q b={1c:!1,1d:"1v.2h 1K a 4D-1h 1Y 1G 1l 1w 1L 1W. "+r(a),1f:1h};1j b}1e 4H(a,b){1e c(a,b,c){1a d=i[u[v.1U]][a.1H][q[b]].1x.2H(/,/),e=[];c.1x?e=c.1x.2H(/,/):e.1I(u[v.1U]);L(e,u[v.1U])||e.1I(u[v.1U]);1i(1a f=c=e,k={},e=[],j=0;j<d.1g;j++)e.1I(d[j]),k[d[j]]=!0;1i(d=0;d<f.1g;d++)k[f[d]]||e.1I(f[d]);d=[];1i(f=0;f<e.1g;f++)L(c,e[f])||d.1I(e[f]);1i(c=0;c<d.1g;c++)e=d[c],2A i[e][a.1H][q[b]],M(a.1H,e)}1a d={1c:!0,1d:"",1f:1h},e=b.1Y,f=a.5W||!1,k=a.5U||!1,h=a.1k,j=a.1o||{},m={2c:0};1b("1s"===1n h)d={1c:!1,1d:"1v.2h 1K a 2J 1M 1R 1i 5S 1M 1l 1V 1G 3m 1w 1L 1W. "+r(b),1f:1h};1q 1b(j&&j.1x)1b(j.1x 2V 2w){1i(1a o="",t=0;t<j.1x.1g&&d.1c;)"24"==1n j.1x[t]?o+=j.1x[t]+",":"1s"!==1n u[j.1x[t]]?o+=u[j.1x[t]]+",":d={1c:!1,1d:"27 1Q: "+j.1x[t]+". "+r(b),1f:1h},t++;d.1c&&(o=o.1J(/,$/,""),j.1x=o)}1q d={1c:!1,1d:"2r 1x 2g 29 1A 1S 2B 3m 5R 2m 5Q "+r(b),1f:1h};1b(d.1c){1b(!i[u[v.1U]][e.1H]||!i[u[v.1U]][e.1H][q[h]]){1i(1a l 1l j)j.1F(l)&&x(m,l,j[l]);d=D(e,q[h],m)}1q 1b(f){1i(l 1l j)j.1F(l)&&x(m,l,j[l]);d=D(e,q[h],m);d.1c&&c(e,h,j)}1q{f=i[u[v.1U]][e.1H][q[h]];1i(l 1l f)f.1F(l)&&x(m,l,f[l]);1b(k){1i(l 1l j)j.1F(l)&&x(m,l,j[l]);d=D(e,q[h],m);d.1c&&c(e,h,m)}1q 1i(l 1l j)j.1F(l)&&(f[l]||x(m,l,j[l]))}d.1c&&V(e,q[h],m)}1j d}1e 40(a){1a b={"5N":4T,"5M":4U,"5L":4W,"5K":4X,5J:4Z,5I:50,5H:52,5G:53};C={};A={};1b(!a||"1s"===1n a)a={};"1s"===1n a.2U&&(a.2U=!0);"1s"!==1n a.1k&&(a.1k=q[a.1k]);1b(a.1x){1a c=a.1x;a.1x=[];1i(1a d=0;d<c.1g;d++)a.1x.1I(u[c[d]])}1j b[1e(a){1a b=a.1X||1h,c=(1n a.1k==="1s"?1h:a.1k)||1h,a=""+((a.1x||1h)==1h?"0":"1");1j a+(b==1h?"0":"1")+(c==1h?"0":"1")}(a)](a)}1e 4T(){1a a=[],b;1i(b 1l i)1b(i.1F(b)){1a c=i[b],d;1i(d 1l c)1b(c.1F(d))1b(2n.2K(d)){1a e=c[d],f;1i(f 1l e)1b(e.1F(f)){1a k=z(b,d,f);k&&a.1I(k)}}1q 2A c[d]}1j a}1e 4U(a){1a b=[],c=!1,d;1i(d 1l i)1b(i.1F(d)){1a e=i[d],f;1i(f 1l e)1b(e.1F(f)&&e[f][a.1k]){1a c=!0,k=z(d,f,a.1k);k&&b.1I(k)}}1b(!c)1r"37 "+a.1k+" 3N 23 2P 2z 1p 34 1Y. "+r(a);1j b}1e 4W(a){1a b=[],c=!1,d;1i(d 1l i)1b(i.1F(d)){1a e=i[d];1b(e[a.1X]){1a c=!0,e=e[a.1X],f;1i(f 1l e)1b(e.1F(f)){1a k=z(d,a.1X,f);k&&b.1I(k)}}}1b(!c)1r"3D 1V 2f 2P 2z 1p 1Y 2i 1H "+a.1X+". "+r(a);1j b}1e 4X(a){1a b=[],c=!1,d=!1,e;1i(e 1l i)1b(i.1F(e)){1a f=i[e][a.1X];f&&(c=!0,f[a.1k]&&(d=!0,(f=z(e,a.1X,a.1k))&&b.1I(f)))}1b(!c||!d)1r"3D 1Y 2i 1H "+a.1X+" 3V 5c 2i 1w 1M "+a.1k+" 2z 1p 1Z. "+r(a);1j b}1e 4Z(a){1i(1a b=[],c=0,d=!0;c<a.1x.1g&&d;){1a d=a.1x[c],e=i[d];1b(e)1i(1a f 1l e){1b(e.1F(f)){1a k=e[f],h;1i(h 1l k)1b(k.1F(h)){1a j=z(d,f,h);j&&b.1I(j)}}}1q 1r"3C 1Q 1l 1Q 3k. "+r(a);c++;d=0==b.1g||a.2U&&0!=b.1g}1j b}1e 50(a){1i(1a b=[],c=0,d=!0;c<a.1x.1g&&d;){1a d=a.1x[c],e=i[d];1b(e){1a f=!1,k;1i(k 1l e)1b(e.1F(k)&&e[k][a.1k]){1a f=!0,h=z(d,k,a.1k);h&&b.1I(h)}1b(!f)1r"37 "+a.1k+" 3N 23 2P 2z 1p 34 1Y 5e 1Q "+d+". "+r(a);}1q 1r"3C 1Q 1l 1Q 3k. "+r(a);c++;d=0==b.1g||a.2U&&0!=b.1g}1j b}1e 52(a){1i(1a b=[],c=[],d=0,e=!0;d<a.1x.1g&&e;){1a e=a.1x[d],f=i[e];1b(f)1b(f=f[a.1X])1i(1a k 1l f){1b(f.1F(k)){1a h=z(e,a.1X,k);h&&b.1I(h)}}1q c.1I(e);1q 1r"3C 1Q 1l 1Q 3k. "+r(a);d++;e=0==b.1g||a.2U&&0!=b.1g}1b(0<c.1g)1r"3D 1Y 2i 1H "+a.1X+" 3V 5c 1l 1w 4M 1Q(s): ["+J(c,",").1J(/,/g,", ")+"]. "+r(a);1j b}1e 53(a){1i(1a b=[],c=0,d=!0;c<a.1x.1g&&d;)(d=z(a.1x[c],a.1X,a.1k))&&b.1I(d),c++,d=0==b.1g||a.2U&&0!=b.1g;1j b}1e z(a,b,c){1a d,e=i[a];1b(!e)1r"3C 1Q 1l 1Q 3k (1Q: "+a+", 1X: "+b+", 1M: "+c+")";e=e[b];C[b]||(C[b]={});1a f=2n.2K(b),k=f.1E.1J(/\\s/g,"");"1s"!==1n f.1R&&"2q"===f.1R.1T()&&""!==k?A[k]||(A[k]={}):(k="5F",A[k]={});1b(!C[b][c]&&!A[k][c])1b(e)1b(e=e[c])f=S(a,b,c,e),f.4b||(b=T(b,c,e),d={1Q:a,5w:c,1y:h[c].1y,1t:h[c].1t,1u:h[c].1u,39:f.39||[],4P:e,35:f.35,1d:b});1q 1r c+" 1l 1Q "+a+" 5E\'t 2P 2z 1p 1w 1Y 2i 1H "+b;1q 1r"3D 1V 2f 2P 5g 1i 1w 1Y 2i 1H: "+b+" 1l 1Q "+a;1j d}1e S(a,b,c,d){1a e=!1,f=[],k=2n.2K(b),i=[];h[c].1y?(f=h[c].1B.2j(k,d),e=0==f.1g):(h[c].1u?(i=h[c].1B.2j(k,d,a,h[c]),e=0==i.1g):e=h[c].1B.2j(k,d),e||f.1I(k));C[b][c]=!0;a=k.1E.1J(/\\s/g,"");"1s"!==1n k.1R&&("2q"===k.1R.1T()&&""!==a)&&(A[a][c]=!0,f=I(2n.4g,"2e","1E",a));e={4b:e,35:f};h[c].38||(e.39=i);1j e}1e T(a,b,c){1a a=2n.2K(a),d="",d=c.1d?c.1d:c.5i?c.5i:h[b].1D,e;1i(e 1l c)1b(c.1F(e))1a f=2G("{"+e+"}","g"),d=d.1J(f,c[e]);1b(h[b].1u&&"1s"!==1n h[b].2N)1i(c=0;c<h[b].2N.1g;c++){1a k=h[b].2N[c];1i(e 1l k.1o)k.1o.1F(e)&&(f=2G("{"+e+"}","g"),d=d.1J(f,k.1o[e]))}/{1N}/.25(d)&&((b=4c[a.2d.1T()])||(b=4c[a.1R.1T()]),d=d.1J(/{1N}/,b),d=d.1J(/{3z}/g,""));1j d=d.1J(/\\\\\\"/g,\'"\')}1a I=1e(a,b,c,d){1i(1a a="*"==b&&a.5n?a.5n:a.6f(b),b=[],e="1s"!==1n d?2G("(^|\\\\s)"+d+"(\\\\s|$)"):1h,f,h,i=0;i<a.1g;i++)f=a[i],h=f.3S&&f.3S(c),"24"==1n h&&0<h.1g&&("1s"===1n d||e&&e.25(h))&&b.1I(f);1j b},H={4q:!0,5D:!1},v={1U:0},u={"0":"1U"},K=[],o={3a:0,36:1,3v:2,3u:3,3d:4,54:4,3g:5,5a:5,3f:6,58:6,3e:7,56:7,3q:8,3h:9,5d:9,3J:10,5h:12,3j:11,5k:11,3i:12,3G:13,3r:14,3M:15,3x:16,3B:17,3s:18,3t:19,3w:20},q={"0":"3a",1:"36",2:"3v",3:"3u",4:"3d",5:"3g",6:"3f",7:"3e",8:"3q",9:"3h",10:"3J",11:"3j",12:"3i",13:"3G",14:"3r",15:"3M",16:"3x",17:"3B",18:"3s",19:"3t",20:"3w"},4c={28:"2r 28",2b:"2r 2b 4O",2y:"2r 41 5O",2Y:"2r 2Y",2q:"2r 2q 47",41:"2r 41 5P",4Q:"2r 4Q"},E=21,5j=1,h={3a:{1y:!1,1B:O,1k:o.3a,1t:!1,1u:!1,1o:[],1D:"{1N} 2D 1p 1A 4h."},36:{1y:!1,1B:1e(){1j 0<1m.57},1k:o.36,1t:!1,1u:!1,1o:[],1D:"{1N} 2D 1p 1A 5T."},3v:{1y:!1,1B:1e(a){1a b=!0;t(1m,a)&&(b=2u(1m.1z)<=2u(a.1z));1j b},1k:o.3v,1t:!1,1u:!1,1o:["1z"],1D:"{1N} 2D 1p 1A 5V 4K 2m 4G 1p {1z}."},3u:{1y:!1,1B:1e(a){1a b=!0;t(1m,a)&&(b=2u(1m.1z)>=2u(a.1z));1j b},1k:o.3u,1t:!1,1u:!1,1o:["1z"],1D:"{1N} 2D 1p 1A 5Y 4K 2m 4G 1p {1z}."},3d:{1y:!1,1B:1e(a){1a b=!0;t(1m,a)&&(b=""!=1m.1z.1J(/\\s/g,"")&&2u(1m.1z)<=2u(a.2Q)&&2u(1m.1z)>=2u(a.2S));1j b},1k:o.3d,1t:!1,1u:!1,1o:["2S","2Q"],1D:"{1N} 2D 1p 1A 4z {2S} 2k {2Q}."},3g:{1y:!1,1B:P,1k:o.3g,1t:!1,1u:!1,1o:[],1D:"{1N} 3E 1A 4y."},3f:{1y:!1,1B:N,1k:o.3f,1t:!1,1u:!1,1o:[],1D:"{1N} 2D 1p 1A 4y."},3e:{1y:!1,1B:1e(a){1a b=!0;t(1m,a)&&(b="24"===1n a.2O?a.2O.1J(/^\\//,"").1J(/\\/$/,""):a.2O,b=("1s"!==1n a.3z?2G(b.3R().1J(/^\\//,"").1J(/\\/[^\\/]*$/,""),a.3z):2G(b)).25(1m.1z));1j b},1k:o.3e,1t:!1,1u:!1,1o:["2O"],1D:"{1N} 2D 1p 4v {2O}{3z}."},3q:{1y:!1,1B:1e(a){1a b=!0;t(1m,a)&&(b=/[a-2s-9!#$%&\'*+/=?^2C`{|}~-]+(?:\\.[a-2s-9!#$%&\'*+/=?^2C`{|}~-]+)*@(?:[a-2s-9](?:[a-2s-9-]*[a-2s-9])?\\.)+[a-2s-9](?:[a-2s-9-]*[a-2s-9])?/i.25(1m.1z));1j b},1k:o.3q,1t:!1,1u:!1,1o:[],1D:"{1N} 1P 23 a 2J 66."},3h:{1y:!1,1B:1e(a){1a b=!0;t(1m,a)&&(b=/^[A-3H-z]+$/.25(1m.1z));1j b},1k:o.3h,1t:!1,1u:!1,1o:[],1D:"{1N} 3o 2a 3Z 5v."},3J:{1y:!1,1B:1e(a){1a b=!0;t(1m,a)&&(b=/^[0-9]+$/.25(1m.1z));1j b},1k:o.3J,1t:!1,1u:!1,1o:[],1D:"{1N} 3o 2a 3Z 5u."},3j:{1y:!1,1B:1e(a){1a b=!0;t(1m,a)&&(b=/^[0-4R-3H-z]+$/.25(1m.1z));1j b},1k:o.3j,1t:!1,1u:!1,1o:[],1D:"{1N} 3o 2a 3Z 5u 2k 5v."},3i:{1y:!1,1B:1e(a){1a b=!0;t(1m,a)&&(b=/^-?[0-9]+$/.25(1m.1z));1j b},1k:o.3i,1t:!1,1u:!1,1o:[],1D:"{1N} 29 1A 1S 2R."},3G:{1y:!1,1B:1e(a){1a b=!0;t(1m,a)&&(b=/^-?([0-9]+(\\.[0-9]+)?|\\.[0-9]+)$/.25(1m.1z));1j b},1k:o.3G,1t:!1,1u:!1,1o:[],1D:"{1N} 29 1A a 6a 32."},3r:{1y:!0,1B:1e(){1i(1a a=[],b=0;b<1m.1O.1g;b++){1a c=1m.1O[b];Q.2j(c)||a.1I(c)}1j a},1k:o.3r,1t:!1,1u:!1,1o:[],1D:"{1N} 29 1A 6b 6c."},3M:{1y:!0,1B:1e(a){1a b=[],c=2n.2K(a.5t),a=2n.2K(a.5o);c.1z!=a.1z&&(b=[c,a]);1j b},1k:o.3M,1t:!1,1u:!1,1o:["5t","5o"],1D:"5C 6g 23 4v."},3x:{1y:!1,1B:Q,1k:o.3x,1t:!1,1u:!1,1o:[],1D:"{1N} 1P 4e."},3B:{1y:!1,1B:1e(a){1j 1m.1z.1g>=a.2S&&1m.1z.1g<=a.2Q},1k:o.3B,1t:!1,1u:!1,1o:["2S","2Q"],1D:"{1N} 1g 29 1A 4z {2S} 2k {2Q}."},3s:{1y:!1,1B:1e(a){1a b=!0;1b(t(1m,a)){1a c=1m.1z.1J(/\\s/g,""),d=c.2H(/\\./),b=!1;0<c.1g&&(1==d.1g&&(d[1]=""),b=0<a.2R?d[0].1g<=a.2R:!0,0<a.3b&&(b=b&&d[1].1g<=a.3b))}1j b},1k:o.3s,1t:!1,1u:!1,1o:["2R","3b"],1D:"{1N} 29 2f 6h 1p {2R} 4V 2k {3b} 6j 4V."},3t:{1y:!1,1B:1e(a){1a b=!0;t(1m,a)&&(a=R.2j(1m,a),b=a.45<a.3P);1j b},1k:o.3t,1t:!1,1u:!1,1o:["3W"],1D:"{1N} 29 1A 1l 1w 6k."},3w:{1y:!1,1B:1e(a){1a b=!0;t(1m,a)&&(a=R.2j(1m,a),b=a.45>a.3P);1j b},1k:o.3w,1t:!1,1u:!1,1o:["3W"],1D:"{1N} 29 1A 1l 1w 6l."}},y={3L:1e(){},3n:1e(){},2x:1e(){},4N:1e(){},42:1e(){},43:1e(){}},46=1e(a){1i(1a b={2L:a.2L,1E:a.1E,1R:a.1R,22:[]},c=0;c<a.22.1g;c++)b.22[b.22.1g]=46(a.22[c]);1j b},F={},B={2L:!1,1E:"6v",1R:-1,22:[]},y={3L:1e(a,b){1a c=1h==F[a]?{2L:!1,1E:q[a],1R:a,22:[]}:F[a];1h==b?B.22[B.22.1g]=c:b.22[b.22.1g]=c;F[a]=c},4j:1e(a){a.22=[]},3n:1e(a){1j F[a]},2x:1e(a){a=1e(a,c){1a d={2x:!1,4f:c};1b(a.2L)d={2x:!0,4f:c};1q{a.2L=!0;1i(1a e=0;e<a.22.1g&&!d.2x;)d=4u.5B(a.22[e],c+"."+a.22[e].1E),e++}1j d}(a,a.1E);a.2x||1e(a){a.2L=!1;1i(1a c=0;c<a.22.1g;c++)4u.5B(a.22[c])}(B);1j a},4N:1e(){1j B},42:1e(a){B=a},43:1e(){1j 46(B)}},i=1h,C={},A={};1j{4S:1e(a){1a b=1e(a,b){"1s"!==1n H[a]&&(H[a]=b)},c=0,d;1i(d 1l a)a.1F(d)&&"2c"!==d&&(b.2j(a,d,a[d],c),c++)},2h:1e(a){i||G();1a b={1c:!0,1d:"",1f:1h};1b("1s"===1n a||!a)G(),b=Z();1q 1b(b=a.1O,"1s"===1n b||!b)b=$(a);1q{1i(1a c={1c:!0},d=0;c.1c&&d<b.1g;)a.1Y=b[d],c=$(a),c.1c||(c.1d="1v.2h: 3y "+(d+1)+" 3m "+b.1g+" 6A: "+c.1d),d++;b=c}1b(!b.1c)1r b.1d;},3A:1e(a){1b("1s"===1n a||!a)G();1q{1b("1s"===1n a.1X&&"1s"===1n a.1O)1r"1v.3A 6B 1S 1X 1G, 2m 1S 1O 1G 1b 1L 2W 2o";1b("1s"!==1n a.1O&&!(a.1O 2V 2w))1r"1v.3A 1K 1w 1O 1G 1p 1A 1S 2B, 1b 1Z 1P 2o";1b("1s"===1n a.1O&&(a.1O=[2n.2K(a.1X)],1h===a.1O[0]))1r"3y 2i 1H "+a.1X+" 49 23 2f 34 1V 2z 1p 1Z. "+r(a);1i(1a b=0;b<a.1O.1g;b++){1a c=a.1O[b].1H,d=a.1V||[];1b(0==d.1g)1i(1a e 1l i){1b(i.1F(e))1b("1s"!==1n i[e][c])2A i[e][c],"1U"!==e&&M(c,e);1q 1r"3y 2i 1H "+c+" 49 23 2f 34 1V 2z 1p 1Z. "+r(a);}1q 1i(1a f=0;f<d.1g;f++){1a h=d[f];1i(e 1l i)1b(i.1F(e))1b("1s"!==1n i[e][c])2A i[e][c][q[h]],"1U"!==e&&M(c,e);1q 1r"3y 2i 1H "+c+" 49 23 2f 34 1V 2z 1p 1Z. "+r(a);}}}},2I:1e(a){1a b=1h;1b("1s"!==1n a&&"1s"!==1n a.1x&&!(a.1x 2V 2w))1r"1v.2I: 2v a 1x 1G 1P 2o, 1Z 29 1A 1S 2B.";1b("1s"!==1n a&&"1s"!==1n a.1x&&0==a.1x.1g)1r"1v.2I: 2v a 1x 1G 1P 2o, 1Z 29 23 1A 48.";1b("1s"!==1n a&&a.1F("1k")&&"1s"===1n a.1k)1r"1v.2I: 2v a 1k 1G 1P 2o, 1Z 3E 1A 1s.";1b("1s"!==1n a&&"1s"!==1n a.1O)1b(a.1O 2V 2w){1b(0==a.1O.1g)1r"1v.2I: 2v 1S 1O 1G 1P 2o, 1Z 29 23 1A 48.";1i(1a c=a.1k,d=a.1x,b=[],e=0;e<a.1O.1g;e++)a.1X=a.1O[e].1H,b=b.6E(40(a)),a.1k=c,a.1x=d}1q 1r"1v.2I: 2v 1S 1O 1G 1P 2o, 1Z 29 1A 1S 2B.";1q b=40(a);1j b},1t:1e(a){1b(!a)1r"1v.1t 1K 1L";1a b=a.1E,c=a.1y||!1,d=a.1B,e=a.1o||[],a=a.1D||"";1b(b){1b("24"!=1n b)1r"1v.1t 1K 1w 1E 1G 1l 1w 1L 1W 1p 1A a 24";1b(0==b.1J(/\\s/g,"").1g)1r"1v.1t 3E 6F 1S 48 24 1i 1w 1E 1G 1l 1w 1L 1W";}1q 1r"1v.1t 1K a 1E 1G 1l 1w 1L 1W";1b("2T"!=1n c)1r"1v.1t 1K 1w 1y 1G 1l 1w 1L 1W 1p 1A a 2T";1b(d){1b("1e"!=1n d)1r"1v.1t 1K 1w 1B 1G 1l 1w 1L 1W 1p 1A a 1e";}1q 1r"1v.1t 1K a 1B 1G 1l 1w 1L 1W";1b(0>e.5b.3R().59("2w"))1r"1v.1t 1K 1w 1o 1G 1l 1w 1L 1W 1p 1A 1S 2B";1b("24"!=1n a)1r"1v.1t 1K 1w 1D 1G 1l 1w 1L 1W 1p 1A a 24";1b(h[b])1r"4L 1P 4C a 1M 4p "+b+". 2v 2p 5p 1p 26 1m 1M, 5l 1v.26";o[b]=E;q[E++]=b;h[b]={1y:c,1B:d,1k:o[b],1t:!0,1u:!1,1o:e,1D:a}},1u:1e(a){1b(!a)1r"1v.1u 1K 1L";1a b=a.1E,c=a.1V||[],d=a.1y||!1,e=a.1D||"",f=a.1o||[],a="1s"===1n a.38?!1:a.38;1b(!b)1r"1v.1u 1K a 1E 1G 1l 1w 1L 1W";1b("24"!=1n b)1r"1v.1u 1K 1E 1p 1A a 24 2g";1b(0>f.5b.3R().59("2w"))1r"1v.1u 1K 1w 1o 1G 1l 1w 1L 1W 1p 1A 1S 2B";1b(0==c.1g)1r"1v.1u 1K 1S 2B 3m 3Q 1V 5e a 1V 1G 1l 1w 1L 1W";1b(h[b])1r"1v.1u: 4L 1P 4C a 1M 4p "+b+". 2v 2p 5p 1p 26 1m 1M, 5l 1v.26";Y(b,c,f);o[b]=E;q[E++]=b;h[b]={1y:d,1k:o[b],1t:!0,1u:!0,1o:f,38:a,2N:c,1D:e,1B:5m};X(b,c)},26:1e(a){1b(!a)1r"1v.26 1K 1L";1b("1s"===1n a.1k)1r"1v.26 1K a 2J 1k 1G 1l 1w 1L 1W";1a b=q[a.1k];1b("1s"===1n b)1r"1v.26: I 6N 23 3K 1w 3F 1M. 6O 1Z 3N 23 2P 5g? 5q 5r: "+r(a);1a c=h[b].1y;h[b].1t&&(c="1s"===1n a.1y?h[b].1y:a.1y);1a d=h[b].1t&&!h[b].1u?a.1B||h[b].1B:h[b].1B,e=h[b].1t?a.1o||h[b].1o:h[b].1o,f=a.1D||h[b].1D,i=h[b].1u,m=a.1V||h[b].1V;1b("2T"!=1n c)1r"1v.26 1K 1w 1y 1G 1l 1w 1L 1W 1p 1A a 2T";1b("1e"!=1n d)1r"1v.26 1K 1w 1B 1G 1l 1w 1L 1W 1p 1A a 1e";1b(!(e 2V 2w))1r"1v.26 1K 1w 1o 1G 1l 1w 1L 1W 1p 1A 1S 2B";1b("24"!=1n f)1r"1v.26 1K 1w 1D 1G 1l 1w 1L 1W 1p 1A a 24";1b(i){Y(b,m,e);1a j=y.43();X(b,m);a=y.2x(y.3n(a.1k));1b(a.2x)1r y.42(j),"1v.26: 2r 6P 3Q-1V 2p 2f 3F 2f 6Q a 6R 6S: "+a.4f;}h[b]={1y:c,1k:o[b],1t:!0,1u:i,1o:e,2N:m,1D:f,1B:d}},37:o,4J:v,4I:{3U:"3U",3T:"3T",44:"44"}}}();',62,427,'||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||var|if|successful|message|function|data|length|null|for|return|constraintType|in|this|typeof|params|to|else|throw|undefined|custom|compound|regula|the|groups|formSpecific|value|be|validator|shift|defaultMessage|name|hasOwnProperty|attribute|id|push|replace|expects|options|constraint|label|elements|is|group|type|an|toLowerCase|Default|constraints|argument|elementId|element|it|||children|not|string|test|override|Invalid|form|must|only|select|__size__|tagName|input|have|parameter|bind|with|call|and|charAt|or|document|provided|you|radio|The|z0|Not|parseFloat|If|Array|cycleExists|textarea|bound|delete|array|_|needs|unshift|character|RegExp|split|validate|valid|getElementById|visited|definition|composingConstraints|regex|been|max|integer|min|boolean|independent|instanceof|are|Year|checkbox|starting|Can|include|number|error|any|failingElements|Selected|Constraint|reportAsSingleViolation|composingConstraintViolations|Checked|fraction|Month|Range|Pattern|Blank|NotBlank|Alpha|Integer|AlphaNumeric|list|Day|of|getNodeByType|can|but|Email|CompletelyFilled|Digits|Past|Min|Max|Future|Required|Element|flags|unbind|Length|Undefined|No|cannot|specified|Real|Za|trying|Numeric|find|addNode|PasswordsMatch|has|You|dateToTestAgainst|composing|toString|getAttribute|MDY|DMY|was|format|new|Date|contain|aa|text|setRoot|clone|YMD|dateToValidate|ca|button|empty|does|expected|constraintPassed|ba|Parameter|required|path|body|checked|void|removeChildren|regular|ignoreEmpty|expression|true|that|called|validateEmptyFields|Validation|Cannot|attached|arguments|match|Math|matching|blank|between|closing|fa|already|non|z_|after|equal|ga|DateFormat|Group|than|There|following|getRoot|box|constraintParameters|password|9A|configure|ha|ia|digits|ja|ka|separator|la|ma|substring|na|oa|Between|date|Matches|selectedIndex|Empty|indexOf|NotEmpty|constructor|found|IsAlpha|under|applicable|defined|IsNumeric|msg|ea|IsAlphaNumeric|use|da|all|field2|wish|Function|received|need|field1|numbers|letters|constraintName|Unterminated|literal|quoted|In|callee|Passwords|debug|hasn|__dontcare__|111|110|101|100|011|010|001|000|area|field|strings|enums|each|selected|overwriteParameters|lesser|overwriteConstraint|unexpected|greater|HTMLElement|nodeType|random|1E6|floor|generated|no|email|start|definitions|before|real|completely|filled|define|Unexpected|getElementsByTagName|do|up|digit|fractional|past|future|positive|parentheses|unmatched|might|false|negative|identifier|pop|missing|RootNode|still|parameters|optional|some|failed|requires|seem|However|concat|accept|least|at|boxes|nor|neither|buttons|checkboxes|could|Perhaps|overriding|created|cyclic|composition'.split('|'),0,{})); /*! * jQuery Form Plugin * version: 3.50.0-2014.02.05 * Requires jQuery v1.5 or later * Copyright (c) 2013 M. Alsup * Examples and documentation at: http://malsup.com/jquery/form/ * Project repository: https://github.com/malsup/form * Dual licensed under the MIT and GPL licenses. * https://github.com/malsup/form#copyright-and-license */ eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('(6(a){"3o 3p";3(1d 2E===\'6\'&&2E.4y){2E([\'2F\'],a)}R{a((1d(3q)!=\'1b\')?3q:1e.4z)}}(6($){"3o 3p";4 P={};P.2G=$("<1l S=\'2e\'/>").1T(0).3r!==1b;P.3s=1e.3t!==1b;4 Q=!!$.12.2H;$.12.1F=6(){3(!Q){8 5.1g.1G(5,24)}4 a=5.2H.1G(5,24);3((a&&a.2F)||1d a===\'2f\'){8 a}8 5.1g.1G(5,24)};$.12.1n=6(y){3(!5.Y){Z(\'1n: 4A 16 4B - 4C 4D 25\');8 5}4 z,1t,19,$9=5;3(1d y==\'6\'){y={1c:y}}R 3(y===1b){y={}}z=y.S||5.1F(\'3u\');1t=y.19||5.1F(\'1t\');19=(1d 1t===\'2f\')?$.4E(1t):\'\';19=19||1e.2I.2J||\'\';3(19){19=(19.4F(/^([^#]+)/)||[])[1]}y=$.2K(1j,{19:19,1c:$.1U.1c,S:z||$.1U.S,26:/^4G/i.1u(1e.2I.2J||\'\')?\'3v:18\':\'4H:4I\'},y);4 A={};5.1h(\'9-2L-3w\',[5,y,A]);3(A.3x){Z(\'1n: 16 3y 2g 9-2L-3w 1h\');8 5}3(y.2M&&y.2M(5,y)===18){Z(\'1n: 16 1o 2g 2M 2N\');8 5}4 B=y.2O;3(B===1b){B=$.1U.2O}4 C=[];4 D,a=5.2P(y.4J,C);3(y.1a){y.11=y.1a;D=$.1V(y.1a,B)}3(y.2Q&&y.2Q(a,5,y)===18){Z(\'1n: 16 1o 2g 2Q 2N\');8 5}5.1h(\'9-16-3z\',[a,5,y,A]);3(A.3x){Z(\'1n: 16 3y 2g 9-16-3z 1h\');8 5}4 q=$.1V(a,B);3(D){q=(q?(q+\'&\'+D):D)}3(y.S.4K()==\'4L\'){y.19+=(y.19.2h(\'?\')>=0?\'&\':\'?\')+q;y.1a=13}R{y.1a=q}4 E=[];3(y.2R){E.W(6(){$9.2R()})}3(y.2S){E.W(6(){$9.2S(y.4M)})}3(!y.27&&y.1v){4 F=y.1c||6(){};E.W(6(a){4 b=y.4N?\'3A\':\'4O\';$(y.1v)[b](a).1H(F,24)})}R 3(y.1c){E.W(y.1c)}y.1c=6(a,b,c){4 d=y.1i||5;1f(4 i=0,1p=E.Y;i<1p;i++){E[i].1G(d,[a,b,c||$9,$9])}};3(y.17){4 G=y.17;y.17=6(a,b,c){4 d=y.1i||5;G.1G(d,[a,b,c,$9])}}3(y.1I){4 H=y.1I;y.1I=6(a,b){4 c=y.1i||5;H.1G(c,[a,b,$9])}}4 I=$(\'1l[S=2e]:4P\',5).4Q(6(){8 $(5).1J()!==\'\'});4 J=I.Y>0;4 K=\'2i/9-1a\';4 L=($9.1g(\'2j\')==K||$9.1g(\'2T\')==K);4 M=P.2G&&P.3s;Z("4R :"+M);4 N=(J||L)&&!M;4 O;3(y.28!==18&&(y.28||N)){3(y.3B){$.1T(y.3B,6(){O=2U(a)})}R{O=2U(a)}}R 3((J||L)&&M){O=3C(a)}R{O=$.3D(y)}$9.4S(\'3E\').1a(\'3E\',O);1f(4 k=0;k<C.Y;k++){C[k]=13}5.1h(\'9-16-4T\',[5,y]);8 5;6 3F(a){4 b=$.1V(a,y.2O).3G(\'&\');4 c=b.Y;4 d=[];4 i,2k;1f(i=0;i<c;i++){b[i]=b[i].4U(/\\+/g,\' \');2k=b[i].3G(\'=\');d.W([3H(2k[0]),3H(2k[1])])}8 d}6 3C(a){4 f=2l 3t();1f(4 i=0;i<a.Y;i++){f.3I(a[i].T,a[i].U)}3(y.11){4 g=3F(y.11);1f(i=0;i<g.Y;i++){3(g[i]){f.3I(g[i][0],g[i][1])}}}y.1a=13;4 s=$.2K(1j,{},$.1U,y,{4V:18,4W:18,4X:18,S:z||\'3J\'});3(y.3K){s.7=6(){4 e=$.1U.7();3(e.2m){e.2m.3L(\'4Y\',6(a){4 b=0;4 c=a.4Z||a.3M;4 d=a.51;3(a.52){b=53.54(c/d*2V)}y.3K(a,c,d,b)},18)}8 e}}s.1a=13;4 h=s.2n;s.2n=6(a,o){3(y.3N){o.1a=y.3N}R{o.1a=f}3(h){h.1w(5,a,o)}};8 $.3D(s)}6 2U(a){4 l=$9[0],X,i,s,g,1K,$V,V,7,1L,n,2o,1W;4 m=$.55();m.1x=6(a){7.1x(a)};3(a){1f(i=0;i<C.Y;i++){X=$(C[i]);3(Q){X.2H(\'1M\',18)}R{X.3O(\'1M\')}}}s=$.2K(1j,{},$.1U,y);s.1i=s.1i||s;1K=\'56\'+(2l 57().58());3(s.2p){$V=$(s.2p);n=$V.1F(\'T\');3(!n){$V.1F(\'T\',1K)}R{1K=n}}R{$V=$(\'<28 T="\'+1K+\'" 2W="\'+s.26+\'" />\');$V.59({3M:\'5a\',3P:\'-3Q\',3R:\'-3Q\'})}V=$V[0];7={1o:0,1q:13,1X:13,1k:0,1y:\'n/a\',5b:6(){},2X:6(){},5c:6(){},1x:6(a){4 e=(a===\'1z\'?\'1z\':\'1o\');Z(\'5d 2m... \'+e);5.1o=1;1A{3(V.29.1r.3S){V.29.1r.3S(\'5e\')}}1N(5f){}$V.1g(\'2W\',s.26);7.17=e;3(s.17){s.17.1w(s.1i,7,e,a)}3(g){$.1O.1h("3T",[7,s,e])}3(s.1I){s.1I.1w(s.1i,7,e)}}};g=s.3U;3(g&&0===$.2Y++){$.1O.1h("5g")}3(g){$.1O.1h("5h",[7,s])}3(s.2n&&s.2n.1w(s.1i,7,s)===18){3(s.3U){$.2Y--}m.2a();8 m}3(7.1o){m.2a();8 m}1L=l.1B;3(1L){n=1L.T;3(n&&!1L.1M){s.11=s.11||{};s.11[n]=1L.U;3(1L.S=="1Y"){s.11[n+\'.x\']=l.1P;s.11[n+\'.y\']=l.1Q}}}4 o=1;4 p=2;6 2Z(a){4 b=13;1A{3(a.29){b=a.29.1r}}1N(1m){Z(\'30 1T 28.29 1r: \'+1m)}3(b){8 b}1A{b=a.31?a.31:a.1r}1N(1m){Z(\'30 1T 28.31: \'+1m);b=a.1r}8 b}4 q=$(\'3V[T=3W-5i]\').1g(\'2q\');4 r=$(\'3V[T=3W-1V]\').1g(\'2q\');3(r&&q){s.11=s.11||{};s.11[r]=q}6 32(){4 t=$9.1F(\'1v\'),a=$9.1F(\'1t\'),K=\'2i/9-1a\',3X=$9.1g(\'2j\')||$9.1g(\'2T\')||K;l.1Z(\'1v\',1K);3(!z||/3Y/i.1u(z)){l.1Z(\'3u\',\'3J\')}3(a!=s.19){l.1Z(\'1t\',s.19)}3(!s.5j&&(!z||/3Y/i.1u(z))){$9.1g({2T:\'2i/9-1a\',2j:\'2i/9-1a\'})}3(s.1z){1W=1R(6(){2o=1j;1C(o)},s.1z)}6 33(){1A{4 a=2Z(V).5k;Z(\'5l = \'+a);3(a&&a.20()==\'5m\'){1R(33,50)}}1N(e){Z(\'5n 1x: \',e,\' (\',e.T,\')\');1C(p);3(1W){3Z(1W)}1W=1b}}4 b=[];1A{3(s.11){1f(4 n 5o s.11){3(s.11.34(n)){3($.5p(s.11[n])&&s.11[n].34(\'T\')&&s.11[n].34(\'U\')){b.W($(\'<1l S="35" T="\'+s.11[n].T+\'">\').1J(s.11[n].U).36(l)[0])}R{b.W($(\'<1l S="35" T="\'+n+\'">\').1J(s.11[n]).36(l)[0])}}}}3(!s.2p){$V.36(\'21\')}3(V.40){V.40(\'41\',1C)}R{V.3L(\'42\',1C,18)}1R(33,15);1A{l.16()}1N(1m){4 c=1r.5q(\'9\').16;c.1G(l)}}5r{l.1Z(\'1t\',a);l.1Z(\'2j\',3X);3(t){l.1Z(\'1v\',t)}R{$9.3O(\'1v\')}$(b).43()}}3(s.5s){32()}R{1R(32,10)}4 u,14,44=50,37;6 1C(e){3(7.1o||37){8}14=2Z(V);3(!14){Z(\'30 5t 5u 1r\');e=p}3(e===o&&7){7.1x(\'1z\');m.2a(7,\'1z\');8}R 3(e==p&&7){7.1x(\'45 1x\');m.2a(7,\'17\',\'45 1x\');8}3(!14||14.2I.2J==s.26){3(!2o){8}}3(V.46){V.46(\'41\',1C)}R{V.5v(\'42\',1C,18)}4 c=\'1c\',1D;1A{3(2o){5w\'1z\';}4 d=s.27==\'1s\'||14.38||$.5x(14);Z(\'5y=\'+d);3(!d&&1e.2r&&(14.21===13||!14.21.47)){3(--44){Z(\'5z 5A 2N, 39 3a 5B\');1R(1C,5C);8}}4 f=14.21?14.21:14.2s;7.1q=f?f.47:13;7.1X=14.38?14.38:14;3(d){s.27=\'1s\'}7.2X=6(a){4 b={\'2q-S\':s.27};8 b[a.20()]};3(f){7.1k=48(f.2t(\'1k\'))||7.1k;7.1y=f.2t(\'1y\')||7.1y}4 h=(s.27||\'\').20();4 i=/(3b|49|2u)/.1u(h);3(i||s.2v){4 j=14.2w(\'2v\')[0];3(j){7.1q=j.U;7.1k=48(j.2t(\'1k\'))||7.1k;7.1y=j.2t(\'1y\')||7.1y}R 3(i){4 k=14.2w(\'2L\')[0];4 b=14.2w(\'21\')[0];3(k){7.1q=k.2x?k.2x:k.4a}R 3(b){7.1q=b.2x?b.2x:b.4a}}}R 3(h==\'1s\'&&!7.1X&&7.1q){7.1X=v(7.1q)}1A{u=x(7,h,s)}1N(1m){c=\'2y\';7.17=1D=(1m||c)}}1N(1m){Z(\'17 5D: \',1m);c=\'17\';7.17=1D=(1m||c)}3(7.1o){Z(\'2m 1o\');c=13}3(7.1k){c=(7.1k>=5E&&7.1k<5F||7.1k===5G)?\'1c\':\'17\'}3(c===\'1c\'){3(s.1c){s.1c.1w(s.1i,u,\'1c\',7)}m.5H(7.1q,\'1c\',7);3(g){$.1O.1h("5I",[7,s])}}R 3(c){3(1D===1b){1D=7.1y}3(s.17){s.17.1w(s.1i,7,c,1D)}m.2a(7,\'17\',1D);3(g){$.1O.1h("3T",[7,s,1D])}}3(g){$.1O.1h("5J",[7,s])}3(g&&!--$.2Y){$.1O.1h("5K")}3(s.1I){s.1I.1w(s.1i,7,c)}37=1j;3(s.1z){3Z(1W)}1R(6(){3(!s.2p){$V.43()}R{$V.1g(\'2W\',s.26)}7.1X=13},2V)}4 v=$.5L||6(s,a){3(1e.4b){a=2l 4b(\'5M.5N\');a.5O=\'18\';a.5P(s)}R{a=(2l 5Q()).5R(s,\'2u/1s\')}8(a&&a.2s&&a.2s.4c!=\'2y\')?a:13};4 w=$.5S||6(s){8 1e[\'5T\'](\'(\'+s+\')\')};4 x=6(a,b,s){4 c=a.2X(\'2q-S\')||\'\',1s=b===\'1s\'||!b&&c.2h(\'1s\')>=0,u=1s?a.1X:a.1q;3(1s&&u.2s.4c===\'2y\'){3($.17){$.17(\'2y\')}}3(s&&s.4d){u=s.4d(u,b)}3(1d u===\'2f\'){3(b===\'3b\'||!b&&c.2h(\'3b\')>=0){u=w(u)}R 3(b==="49"||!b&&c.2h("3v")>=0){$.5U(u)}}8 u};8 m}};$.12.3c=6(a){a=a||{};a.2z=a.2z&&$.5V($.12.3d);3(!a.2z&&5.Y===0){4 o={s:5.22,c:5.1i};3(!$.4e&&o.s){Z(\'39 3a 4f, 5W 3c\');$(6(){$(o.s,o.c).3c(a)});8 5}Z(\'5X; 5Y 4g 5Z 60 22\'+($.4e?\'\':\' (39 3a 4f)\'));8 5}3(a.2z){$(1r).4h(\'16.9-1E\',5.22,2A).4h(\'2B.9-1E\',5.22,2C).3d(\'16.9-1E\',5.22,a,2A).3d(\'2B.9-1E\',5.22,a,2C);8 5}8 5.4i().4j(\'16.9-1E\',a,2A).4j(\'2B.9-1E\',a,2C)};6 2A(e){4 a=e.1a;3(!e.61()){e.62();$(e.1v).1n(a)}}6 2C(e){4 a=e.1v;4 b=$(a);3(!(b.4k("[S=16],[S=1Y]"))){4 t=b.63(\'[S=16]\');3(t.Y===0){8}a=t[0]}4 c=5;c.1B=a;3(a.S==\'1Y\'){3(e.4l!==1b){c.1P=e.4l;c.1Q=e.64}R 3(1d $.12.4m==\'6\'){4 d=b.4m();c.1P=e.4n-d.3R;c.1Q=e.4o-d.3P}R{c.1P=e.4n-a.65;c.1Q=e.4o-a.66}}1R(6(){c.1B=c.1P=c.1Q=13},2V)}$.12.4i=6(){8 5.67(\'16.9-1E 2B.9-1E\')};$.12.2P=6(b,c){4 a=[];3(5.Y===0){8 a}4 d=5[0];4 e=5.1g(\'1K\');4 f=b?d.2w(\'*\'):d.4g;4 g;3(f&&!/4p [68]/.1u(4q.4r)){f=$(f).1T()}3(e){g=$(\':1l[9=\'+e+\']\').1T();3(g.Y){f=(f||[]).69(g)}}3(!f||!f.Y){8 a}4 i,j,n,v,X,1p,3e;1f(i=0,1p=f.Y;i<1p;i++){X=f[i];n=X.T;3(!n||X.1M){3f}3(b&&d.1B&&X.S=="1Y"){3(d.1B==X){a.W({T:n,U:$(X).1J(),S:X.S});a.W({T:n+\'.x\',U:d.1P},{T:n+\'.y\',U:d.1Q})}3f}v=$.2b(X,1j);3(v&&v.2D==2c){3(c){c.W(X)}1f(j=0,3e=v.Y;j<3e;j++){a.W({T:n,U:v[j]})}}R 3(P.2G&&X.S==\'2e\'){3(c){c.W(X)}4 h=X.3r;3(h.Y){1f(j=0;j<h.Y;j++){a.W({T:n,U:h[j],S:X.S})}}R{a.W({T:n,U:\'\',S:X.S})}}R 3(v!==13&&1d v!=\'1b\'){3(c){c.W(X)}a.W({T:n,U:v,S:X.S,4s:X.4s})}}3(!b&&d.1B){4 k=$(d.1B),1l=k[0];n=1l.T;3(n&&!1l.1M&&1l.S==\'1Y\'){a.W({T:n,U:k.1J()});a.W({T:n+\'.x\',U:d.1P},{T:n+\'.y\',U:d.1Q})}}8 a};$.12.6a=6(a){8 $.1V(5.2P(a))};$.12.6b=6(b){4 a=[];5.1H(6(){4 n=5.T;3(!n){8}4 v=$.2b(5,b);3(v&&v.2D==2c){1f(4 i=0,1p=v.Y;i<1p;i++){a.W({T:n,U:v[i]})}}R 3(v!==13&&1d v!=\'1b\'){a.W({T:5.T,U:v})}});8 $.1V(a)};$.12.2b=6(a){1f(4 b=[],i=0,1p=5.Y;i<1p;i++){4 c=5[i];4 v=$.2b(c,a);3(v===13||1d v==\'1b\'||(v.2D==2c&&!v.Y)){3f}3(v.2D==2c){$.6c(b,v)}R{b.W(v)}}8 b};$.2b=6(b,c){4 n=b.T,t=b.S,23=b.3g.20();3(c===1b){c=1j}3(c&&(!n||b.1M||t==\'2d\'||t==\'6d\'||(t==\'3h\'||t==\'3i\')&&!b.3j||(t==\'16\'||t==\'1Y\')&&b.9&&b.9.1B!=b||23==\'1S\'&&b.3k==-1)){8 13}3(23==\'1S\'){4 d=b.3k;3(d<0){8 13}4 a=[],3l=b.6e;4 e=(t==\'1S-4t\');4 f=(e?d+1:3l.Y);1f(4 i=(e?d:0);i<f;i++){4 g=3l[i];3(g.25){4 v=g.U;3(!v){v=(g.3m&&g.3m.U&&!(g.3m.U.6f))?g.2u:g.U}3(e){8 v}a.W(v)}}8 a}8 $(b).1J()};$.12.2S=6(a){8 5.1H(6(){$(\'1l,1S,2v\',5).4u(a)})};$.12.4u=$.12.6g=6(a){4 b=/^(?:6h|6i|6j|6k|6l|6m|6n|6o|6p|6q|2u|6r|19|6s)$/i;8 5.1H(6(){4 t=5.S,23=5.3g.20();3(b.1u(t)||23==\'2v\'){5.U=\'\'}R 3(t==\'3h\'||t==\'3i\'){5.3j=18}R 3(23==\'1S\'){5.3k=-1}R 3(t=="2e"){3(/4p/.1u(4q.4r)){$(5).3A($(5).6t(1j))}R{$(5).1J(\'\')}}R 3(a){3((a===1j&&/35/.1u(t))||(1d a==\'2f\'&&$(5).4k(a))){5.U=\'\'}}})};$.12.2R=6(){8 5.1H(6(){3(1d 5.2d==\'6\'||(1d 5.2d==\'6u\'&&!5.2d.6v)){5.2d()}})};$.12.6w=6(b){3(b===1b){b=1j}8 5.1H(6(){5.1M=!b})};$.12.25=6(b){3(b===1b){b=1j}8 5.1H(6(){4 t=5.S;3(t==\'3h\'||t==\'3i\'){5.3j=b}R 3(5.3g.20()==\'4v\'){4 a=$(5).6x(\'1S\');3(b&&a[0]&&a[0].S==\'1S-4t\'){a.6y(\'4v\').25(18)}5.25=b}})};$.12.1n.4w=18;6 Z(){3(!$.12.1n.4w){8}4 a=\'[2F.9] \'+2c.6z.6A.1w(24,\'\');3(1e.3n&&1e.3n.Z){1e.3n.Z(a)}R 3(1e.2r&&1e.2r.4x){1e.2r.4x(a)}}}));',62,409,'|||if|var|this|function|xhr|return|form||||||||||||||||||||||||||||||||||||||||||||else|type|name|value|io|push|el|length|log||extraData|fn|null|doc||submit|error|false|url|data|undefined|success|typeof|window|for|attr|trigger|context|true|status|input|err|ajaxSubmit|aborted|max|responseText|document|xml|action|test|target|call|abort|statusText|timeout|try|clk|cb|errMsg|plugin|attr2|apply|each|complete|val|id|sub|disabled|catch|event|clk_x|clk_y|setTimeout|select|get|ajaxSettings|param|timeoutHandle|responseXML|image|setAttribute|toLowerCase|body|selector|tag|arguments|selected|iframeSrc|dataType|iframe|contentWindow|reject|fieldValue|Array|reset|file|string|via|indexOf|multipart|enctype|part|new|upload|beforeSend|timedOut|iframeTarget|content|opera|documentElement|getAttribute|text|textarea|getElementsByTagName|textContent|parsererror|delegation|doAjaxSubmit|click|captureSubmittingElement|constructor|define|jquery|fileapi|prop|location|href|extend|pre|beforeSerialize|callback|traditional|formToArray|beforeSubmit|resetForm|clearForm|encoding|fileUploadIframe|100|src|getResponseHeader|active|getDoc|cannot|contentDocument|doSubmit|checkState|hasOwnProperty|hidden|appendTo|callbackProcessed|XMLDocument|DOM|not|json|ajaxForm|on|jmax|continue|tagName|checkbox|radio|checked|selectedIndex|ops|attributes|console|use|strict|jQuery|files|formdata|FormData|method|javascript|serialize|veto|vetoed|validate|replaceWith|closeKeepAlive|fileUploadXhr|ajax|jqxhr|deepSerialize|split|decodeURIComponent|append|POST|uploadProgress|addEventListener|position|formData|removeAttr|top|1000px|left|execCommand|ajaxError|global|meta|csrf|et|post|clearTimeout|attachEvent|onload|load|remove|domCheckCount|server|detachEvent|innerHTML|Number|script|innerText|ActiveXObject|nodeName|dataFilter|isReady|ready|elements|off|ajaxFormUnbind|bind|is|offsetX|offset|pageX|pageY|MSIE|navigator|userAgent|required|one|clearFields|option|debug|postError|amd|Zepto|skipping|process|no|element|trim|match|https|about|blank|semantic|toUpperCase|GET|includeHidden|replaceTarget|html|enabled|filter|fileAPI|removeData|notify|replace|contentType|processData|cache|progress|loaded||total|lengthComputable|Math|ceil|Deferred|jqFormIO|Date|getTime|css|absolute|getAllResponseHeaders|setRequestHeader|aborting|Stop|ignore|ajaxStart|ajaxSend|token|skipEncodingOverride|readyState|state|uninitialized|Server|in|isPlainObject|createElement|finally|forceSync|access|response|removeEventListener|throw|isXMLDoc|isXml|requeing|onLoad|available|250|caught|200|300|304|resolve|ajaxSuccess|ajaxComplete|ajaxStop|parseXML|Microsoft|XMLDOM|async|loadXML|DOMParser|parseFromString|parseJSON|eval|globalEval|isFunction|queuing|terminating|zero|found|by|isDefaultPrevented|preventDefault|closest|offsetY|offsetLeft|offsetTop|unbind|678|concat|formSerialize|fieldSerialize|merge|button|options|specified|clearInputs|color|date|datetime|email|month|number|password|range|search|tel|time|week|clone|object|nodeType|enable|parent|find|prototype|join'.split('|'),0,{})) regula.custom({ name:'JustLetters' ,validator:function(){ return /^[a-zA-Z'][a-zA-Z-' ]+[a-zA-Z']?$/.test(this.value) } }) regula.custom({ name:'JustNumbers' ,validator:function(){ return /^\+?(\d[\d\-\+\(\) ]{5,}\d$)/.test(this.value) } }) regula.custom({ name:'ZIP' ,validator:function(){ return /^\+?(\d[\d\-\+\(\) ]{3,}\d$)/.test(this.value) } })
define( "dojo/cldr/nls/kok/number", //begin v1.x content { "decimalFormat": "#,##,##0.###", "currencyFormat": "¤ #,##,##0.00", "percentFormat": "#,##,##0%" } //end v1.x content );
/** * Copyright (c) Dylan Jenken 26/04/2016. */ function Minefield(width, height, numMines){ var self = this; self.width = width; self.height = height; self.mines = []; self.totalMines = numMines; self.grid = null; self.view = null; //Generate grid of xsize and ysize //self.init(); } Minefield.prototype.init = function(gameboardElement){ this.grid = this.generateGrid(); this.view = this.generateView(gameboardElement); this.placeMines(); this.populateAdjacentSquares(); }; Minefield.prototype.generateView = function(viewElement){ var gridMarkup = ''; gridMarkup += '<table id="minefield">'; for(var curRow = 0; curRow < this.width; curRow++) { gridMarkup += '<tr>'; for(var curCol = 0; curCol < this.height; curCol++) { gridMarkup += '<td data-row ="' + curRow + '"' + 'data-column ="' + curCol + '"'; gridMarkup += 'class="square"></td>'; } } gridMarkup += '</tr>'; gridMarkup += '</table>'; viewElement.html(gridMarkup); return viewElement; }; Minefield.prototype.generateGrid = function(){ //Create array of size var grid = []; for(var curX = 0; curX < this.width; curX++) { grid[curX] = []; for(var curY = 0; curY < this.height; curY++) { grid[curX][curY] = new Square(); } } return grid; }; Minefield.prototype.placeMines = function(){ for(var curMine = 0; curMine < this.totalMines; curMine++) { var placingMine = true; var randX = 0; var randY = 0; //Put mine in random position while(placingMine) { //Generate random values between 0 and width/height randX = Math.floor(Math.random() * this.width); randY = Math.floor(Math.random() * this.height); //Do not overlap if (this.cellHasMine(randX, randY) == false) { this.grid[randX][randY].occupied = true; this.mines[this.mines.length] = {x:randX, y:randY}; placingMine = false; } } } }; Minefield.prototype.populateAdjacentSquares = function(){ //populate adjacent squares values for(var curMine = 0; curMine < this.mines.length; curMine++) { //Iterate adjacent squares for(var adjX = this.mines[curMine].x - 1; adjX < this.mines[curMine].x + 2; adjX++){ if(adjX < 0 || adjX >= this.grid.length){ continue; } for(var adjY = this.mines[curMine].y - 1; adjY < this.mines[curMine].y + 2; adjY++){ if(adjY < 0 || adjY >= this.grid.length){ continue; } this.grid[adjX][adjY].adjacentMines++; } } } }; Minefield.prototype.cellHasMine = function(x,y){ return this.grid[x][y].occupied; }; Minefield.prototype.flagSquare = function(x,y){ if(!this.grid[x][y].revealed && !this.grid[x][y].flagged) { this.grid[x][y].flagged = true; $('.square[data-row="' + x + '"][data-column="'+y+'"]').css('background-image', 'url(./images/flaggedsquare.png)'); } else if(!this.grid[x][y].revealed && this.grid[x][y].flagged){ this.grid[x][y].flagged = false; $('.square[data-row="' + x + '"][data-column="'+y+'"]').css('background-image', 'url(./images/emptysquare.png)'); } }; Minefield.prototype.revealSquare = function(x,y){ var revealQueue = []; var squareElement = $('.square[data-row="' + x + '"][data-column="'+y+'"]'); if(this.cellHasMine(x,y)){ squareElement.css('background-image', 'url(./images/mine.png)'); //this.init(this.view); return; } revealQueue.push({x: x, y: y}); //For every square in the squares to reveal queue for(var curQueue = 0; curQueue < revealQueue.length; curQueue++){ //If the square is already revealed skip it if(this.grid[revealQueue[curQueue].x][revealQueue[curQueue].y].revealed) { continue; } //Otherwise, reveal it else { //Get the DOM element for current square squareElement = $('.square[data-row="' + revealQueue[curQueue].x + '"][data-column="'+revealQueue[curQueue].y+'"]'); squareElement.css('background-image', 'url(./images/emptysquareclicked.png)'); //if the square has adjacent mines if(this.grid[revealQueue[curQueue].x][revealQueue[curQueue].y].adjacentMines > 0){ //reveal it and stop revealing switch(this.grid[revealQueue[curQueue].x][revealQueue[curQueue].y].adjacentMines){ case 1: squareElement.css('color', '#0000ff'); break; case 2: squareElement.css('color', '#00ff00'); break; case 3: squareElement.css('color', '#ff0000'); break; case 4: squareElement.css('color', '#00ffff'); break; case 5: squareElement.css('color', '#ffff00'); break; case 6: squareElement.css('color', '#ff00ff'); break; case 7: squareElement.css('color', '#ffffff'); break; case 8: squareElement.css('color', '#000000'); break; } squareElement.html(this.grid[revealQueue[curQueue].x][revealQueue[curQueue].y].adjacentMines); } //otherwise, if the square has no adjacent mines, reveal the squares adjacent to this one else { //iterate through adjacent cells for(var adjX = revealQueue[curQueue].x - 1; adjX < revealQueue[curQueue].x + 2; adjX++){ //If the coordinate is invalid, move on to the next one if(adjX < 0 || adjX >= this.grid.length){ continue; } for(var adjY = revealQueue[curQueue].y - 1; adjY < revealQueue[curQueue].y + 2; adjY++){ //If the coordinate is invalid, move on to the next one if(adjY < 0 || adjY >= this.grid.length || (adjX == revealQueue[curQueue].x && adjY == revealQueue[curQueue].y)){ continue; } //Add the square to the queue to reveal, if it hasn't already been revealed if(this.grid[adjX][adjY].revealed) { continue; } revealQueue.push({x:adjX, y:adjY}); } } } } this.grid[revealQueue[curQueue].x][revealQueue[curQueue].y].revealed = true; } };
(function (jsStatisticsAPI) { 'use strict'; /** * the matrix is declared as following array series * [ * [1, 2, 3], * [4, 5, 6], * [7, 8, 9] * ] * * which represents 3 by 3 matrix: * 1 2 3 * 4 5 6 * 7 8 9 */ jsStatisticsAPI.setMatrixFromArray = function(arrayOfNumbers, numOfColumn) { if (arrayOfNumbers.length % numOfColumn) { console.log('the length of array cannot be divided by column size'); return [arrayOfNumbers]; // the matrix whose size is 1 by arrayOfNumbers.length } var matrixArray = []; var length = arrayOfNumbers.length; var numOfRow = length / numOfColumn; for (var i = 0; i < numOfRow; i++) { matrixArray.push(arrayOfNumbers.slice(i * numOfColumn, (i + 1) * numOfColumn)); } return matrixArray; }; jsStatisticsAPI.isSquareMatrix = function(matrix) { try { return Boolean(matrix.length === matrix[0].length); } catch(e) { console.log('invalid matrix'); return false; } }; /** * each index is labeled on computing. * not real mathematics * (o) 0th row - 1st column * (x) 1th row - 2th column */ jsStatisticsAPI.computeMatrixMinor = function(matrix, rowIdx, columnIdx) { var minor = JSON.parse(JSON.stringify(matrix)); minor.splice(rowIdx, 1); minor.forEach(function(row) { row.splice(columnIdx, 1); }); return minor; }; jsStatisticsAPI.computeMatrixDeterminant = function(matrix) { if (!this.isSquareMatrix(matrix)) { return console.log('the matrix is not square.'); } if (matrix.length == 2) { return ((matrix[0][0] * matrix[1][1]) - (matrix[0][1] * matrix[1][0])); } else { var result = []; for (var i = 0; i < matrix.length; i++) { var submatrix = JSON.parse(JSON.stringify(matrix)); var multiplier = (0 + i) % 2 ? (-1 * matrix[0][i]) : matrix[0][i]; var subresult = 0; submatrix = this.computeMatrixMinor(submatrix, 0, i); subresult = multiplier * this.computeMatrixDeterminant(submatrix); // console.log({"multiplier" : multiplier, "submatrix" : submatrix, "subresult" : subresult}); result.push(subresult); // if (submatrix.length > 1) { // console.log(matrix); // console.log('test : ', matrix[0][i] * this.computeMatrixDeterminant(submatrix)) // return matrix[0][i] * this.computeMatrixDeterminant(submatrix); // } } // console.log({"result" : result, "matrix" : matrix, "length" : matrix.length}); return result.reduce((partial_sum, a) => partial_sum + a,0); } }; jsStatisticsAPI.computeRowEchelonForm = function(matrix, isReduced) { if (isReduced) return this.computeReducedRowEchelonForm(matrix); // row echelon form console.log(matrix); }; jsStatisticsAPI.computeReducedRowEchelonForm = function(matrix) { }; jsStatisticsAPI.rowSwitching = function(matrix, ithRow, jthRow) { /** * Row-ith <=> Row-jth */ var minor = JSON.parse(JSON.stringify(matrix)); var tmp = minor[ithRow]; minor[ithRow] = minor[jthRow]; minor[jthRow] = tmp; return minor; }; jsStatisticsAPI.rowMultiplication = function(matrix, ithRow, constant) { /** * constant * Row-ith => Row-ith */ if (constant == 0) { return console.log("constant must be non-zero"); } var minor = JSON.parse(JSON.stringify(matrix)); minor[ithRow] = minor[ithRow].map(x => x * constant); return minor; }; jsStatisticsAPI.rowAddition = function(matrix, ithRow, jthRow, constant) { /** * Row-ith + constant * Row-jth => Row-ith */ if (constant == 0) { return console.log("constant must be non-zero"); } var minor = JSON.parse(JSON.stringify(matrix)); var tmp = minor[jthRow].map(x => x * constant); minor[ithRow] = minor[ithRow].map((x, i) => x + tmp[i]); return minor; }; jsStatisticsAPI.makeZeroValueClean = function(matrix) { var minor = JSON.parse(JSON.stringify(matrix)); var numOfRow = minor.length; var numOfColumn = minor[0].length; for (var i = 0; i < numOfRow; i++) { for (var j = 0; j < numOfColumn; j++) { if (Math.abs(minor[i][j]) < Math.pow(10, -6)) { minor[i][j] = 0; } } } return minor; }; jsStatisticsAPI.rowEchelonForm = function(matrix) { var minor = JSON.parse(JSON.stringify(matrix)); var numOfRow = minor.length; var index = 0; while (index != numOfRow) { var diagonalValue = minor[index][index]; for (var i = index + 1; i < numOfRow; i++) { var constant = (-1) * (minor[i][index] / diagonalValue); minor = this.rowAddition(minor, i, index, constant); // console.log({"index" : index, "diagonalValue" : diagonalValue, "minor" : minor, "constant" : constant}); } index++; } minor = this.makeZeroValueClean(minor); return minor; }; jsStatisticsAPI.reducedRowEchelonForm = function(matrix) { var minor = JSON.parse(JSON.stringify(matrix)); var numOfRow = minor.length; var numOfColumn = minor[0].length; var maximum = Math.min(numOfRow, numOfColumn); var index = 0; while (index < maximum) { var diagonalValue = minor[index][index]; if (diagonalValue != 0) { minor = this.rowMultiplication(minor, index, (1 / diagonalValue)); for (var i = 0; i < numOfRow; i++) { if (i != index && minor[i][index] != 0) { var constant = (-1) * minor[i][index]; minor = this.rowAddition(minor, i, index, constant); } // console.log({"index" : index, "diagonalValue" : diagonalValue, "minor" : minor, "constant" : constant, "maximum" : maximum}); } } index++; } minor = this.makeZeroValueClean(minor); return minor; }; jsStatisticsAPI.identityMatrix = function(size) { var identityMatrix = []; for (var i = 0; i < size; i++) { var row = []; for (var j = 0; j < size; j++) { if (i == j) { row.push(1); } else { row.push(0); } } identityMatrix.push(row); } return identityMatrix; }; jsStatisticsAPI.extendIdentityMatrix = function(matrix) { if (!this.isSquareMatrix(matrix)) { return console.log('the matrix is not square.'); } else { var minor = JSON.parse(JSON.stringify(matrix)); var length = minor.length; var identityMatrix = this.identityMatrix(length); for (var i = 0; i < length; i++) { minor[i].push(...identityMatrix[i]); } return minor; } }; jsStatisticsAPI.removeFrontIdentityMatrix = function(matrix) { var minor = JSON.parse(JSON.stringify(matrix)); var numOfRow = minor.length; var numOfColumn = minor[0].length; if (numOfRow * 2 != numOfColumn) { return false; } for (var i = 0; i < numOfRow; i++) { minor[i] = minor[i].slice(numOfRow, numOfColumn); } return minor; }; jsStatisticsAPI.inverseOfMatrix = function(matrix) { if (!this.isSquareMatrix(matrix)) { return console.log('the matrix is not square.'); } else if (this.computeMatrixDeterminant(matrix) == 0) { return console.log('this matrix is not an invertible matrix.'); } else { var minor = JSON.parse(JSON.stringify(matrix)); var extendIdentityMatrix = this.extendIdentityMatrix(minor); var gaussianElimination = this.reducedRowEchelonForm(extendIdentityMatrix); var inverseOfMatrix = this.removeFrontIdentityMatrix(gaussianElimination); return inverseOfMatrix; } }; jsStatisticsAPI.matrixMultiplication = function(matrixA, matrixB) { var minorA = JSON.parse(JSON.stringify(matrixA)); var minorB = JSON.parse(JSON.stringify(matrixB)); var numOfRowA = minorA.length; var numOfColumnA = minorA[0].length; var numOfRowB = minorB.length; var numOfColumnB = minorB[0].length; console.log({"numOfRowA" : numOfRowA, "numOfColumnA" : numOfColumnA, "numOfRowB" : numOfRowB, "numOfColumnB" : numOfColumnB}); if (numOfColumnA != numOfRowB) { return console.log('these two matrices cannot be multiplied.'); } var result = []; var commonValue = numOfColumnA; for (var i = 0; i < numOfRowA; i++) { var row = []; for (var j = 0; j < numOfColumnB; j++) { var dotProductResult = 0; for (var k = 0; k < commonValue; k++) { var tmp = minorA[i][k] * minorB[k][j]; dotProductResult += tmp; } row.push(dotProductResult); } result.push(row); } return result; }; jsStatisticsAPI.matrixSubtraction = function(matrixA, matrixB) { var minorA = JSON.parse(JSON.stringify(matrixA)); var minorB = JSON.parse(JSON.stringify(matrixB)); var numOfRowA = minorA.length; var numOfColumnA = minorA[0].length; var numOfRowB = minorB.length; var numOfColumnB = minorB[0].length; if (numOfRowA != numOfRowB || numOfColumnA != numOfColumnB) { return console.log('these two matrices are of different sizes.'); } var numOfRow = numOfRowA; var numOfColumn = numOfColumnA; var result = []; for (var i = 0; i < numOfRow; i++) { var row = []; for (var j = 0; j < numOfColumn; j++) { row.push(minorA[i][j] - minorB[i][j]); } result.push(row); } return result; }; jsStatisticsAPI.matrixAddition = function(matrixA, matrixB) { var minorA = JSON.parse(JSON.stringify(matrixA)); var minorB = JSON.parse(JSON.stringify(matrixB)); var numOfRowA = minorA.length; var numOfColumnA = minorA[0].length; var numOfRowB = minorB.length; var numOfColumnB = minorB[0].length; if (numOfRowA != numOfRowB || numOfColumnA != numOfColumnB) { return console.log('these two matrices are of different sizes.'); } var numOfRow = numOfRowA; var numOfColumn = numOfColumnA; var result = []; for (var i = 0; i < numOfRow; i++) { var row = []; for (var j = 0; j < numOfColumn; j++) { row.push(minorA[i][j] + minorB[i][j]); } result.push(row); } return result; }; jsStatisticsAPI.matrixScalarMultiplication = function(matrix, scalar) { var minor = JSON.parse(JSON.stringify(matrix)); var numOfRow = minor.length; for (var i = 0; i < numOfRow; i++) { minor[i] = minor[i].map(x => x * scalar); } return minor; }; }(jsStatistics.API));
/** * 事件基类,提供DOM事件和自定义事件侦听、触发、销毁功能,自定义事件基于Vue实现,面向对象类可继承该类实现事件相关功能 * @module $ui/utils/events * @author 陈华春 */ import {on, off} from 'element-ui/lib/utils/dom' import Vue from 'vue' /** * 事件处理基类 * @export */ class Events { /** * @constructor */ constructor() { /** * DOM事件句柄对象handler缓存集合, 私有属性 * @type {Object[]} * @property {Object[]} handler * @property {HtmlElement} handler.el DOM元素 * @property {String} handler.eventName 事件名称,如: click、mouseenter、keydown * @property {Function} handler.callback 事件回调函数 * @property {Function} handler.proxy 时间回调函数代理,更换了作用域this指向当前实例 */ this.__handlers__ = [] /** * 自定义事件处理对象,基于Vue实例实现,私有属性 * @type {Vue} */ this.__event__ = new Vue({}) } /** * 绑定DOM事件 * @param {HtmlElement} el 元素DOM对象 * @param {String} eventName 事件名称如:click、mouseenter、keydown * @param {Function} callback 事件回调函数 */ on(el, eventName, callback) { const proxy = callback.bind(this) const handler = {el, eventName, callback, proxy} this.__handlers__.push(handler) on(el, eventName, proxy) return this } /** * 绑定自定义事件 * @param {String} name 事件名称 * @param {Function} handler 事件处理函数 * @returns {Vue} */ $on(name, handler) { this.__event__.$on.apply(this.__event__, arguments) return this } /** * 绑定自定义事件 * @param {String} name 事件名称 * @param {Function} handler 事件处理函数 * @return {*} */ $once(name, handler) { this.__event__.$once.apply(this.__event__, arguments) return this } /** * 销毁指定DOM事件 * @param {HtmlElement} el DOM元素 * @param {String} [eventName] 事件名称如:click、mouseenter、keydown,可选参数,如不传,即表示销毁当前元素的全部事件 * @param {Function} [callback] 事件回调函数,可选,如不传,即表示销毁当前元素指定类型的事件 */ off(el, eventName, callback) { if (!el) return const length = arguments.length this.__handlers__.forEach((item, index) => { switch (length) { case 3: if (item.el === el && item.eventName === eventName && item.callback === callback) { off(item.el, item.eventName, item.proxy) this.__handlers__.splice(index, 1) } break case 2: if (item.el === el && item.eventName === eventName) { off(item.el, item.eventName, item.proxy) this.__handlers__.splice(index, 1) } break case 1: if (item.el === el) { off(item.el, item.eventName, item.proxy) this.__handlers__.splice(index, 1) } break } }) return this } /** * 销毁自定义事件 * @param {String} [name] 事件名称,可选,不传表示销毁当前实例的全部事件 * @param {Function} [handler] 事件回调函数,可选,不传表示销毁当前实例指定时间名称的全部事件 * @returns {*} */ $off(name, handler) { this.__event__.$off.apply(this.__event__, arguments) return this } /** * 触发自定义事件 * @param {string} name 事件名称 * @param {Function} handler 事件回调函数 * @returns {*} */ $emit(name, handler) { this.__event__.$emit.apply(this.__event__, arguments) return this } /** * 销毁实例,把DOM和自定义事件全部销毁,释放内存 */ destroy() { this.__handlers__.forEach(item => { off(item.el, item.eventName, item.proxy) }) this.__handlers__ = [] this.__event__.$off() this.__event__.$destroy() } } /** * 事件基类 * @type {Events} */ export default Events
(function(){ var modules = {}, cache = {} if (typeof define == 'undefined'){ window.define = function(id, factory){ modules[id] = factory } window.require = function(id){ var module = cache[id] if (!module){ module = cache[id] = {} var exports = module.exports = {} modules[id].call(exports, require, exports, module) } return module.exports } } })()
'use strict'; angular.module('AdCatal', [ 'ngRoute', 'ngCookies', 'SessionManager', 'ui.bootstrap', 'AuthInterceptor', 'ngSanitize', 'pascalprecht.translate', 'NavBar', 'ngResource' ]) .constant('APP_CONFIG',{ 'appName':'Product Catalogue', 'appVersion':'1.0.0-SNAPSHOT' }) .config(['$routeProvider', '$httpProvider','$translateProvider','$translatePartialLoaderProvider', function($routeProvider,$httpProvider,$translateProvider,$translatePartialLoaderProvider) { $routeProvider .when('/',{templateUrl:'views/CatalArticle/CatalArticles.html',controller:'catalArticlesCtlr'}) .when('/CatalArticles/new',{templateUrl:'views/CatalArticle/CatalArticleCreate.html',controller:'catalArticleCreateCtlr'}) .when('/CatalArticles',{templateUrl:'views/CatalArticle/CatalArticles.html',controller:'catalArticlesCtlr'}) .when('/CatalArticles/edit/:pic',{templateUrl:'views/CatalArticle/CatalArticleEdit.html',controller:'catalArticleEditCtlr'}) .when('/CatalArticles/show/:pic',{templateUrl:'views/CatalArticle/CatalArticleShow.html',controller:'catalArticleShowCtlr'}) // .when('/CatalArtDetailConfigs',{templateUrl:'views/CatalArtDetailConfig/search.html',controller:'SearchCatalArtDetailConfigController'}) // .when('/CatalArtDetailConfigs/new',{templateUrl:'views/CatalArtDetailConfig/detail.html',controller:'NewCatalArtDetailConfigController'}) // .when('/CatalArtDetailConfigs/edit/:CatalArtDetailConfigId',{templateUrl:'views/CatalArtDetailConfig/detail.html',controller:'EditCatalArtDetailConfigController'}) // .when('/CatalArtEquivalences',{templateUrl:'views/CatalArtEquivalence/search.html',controller:'SearchCatalArtEquivalenceController'}) // .when('/CatalArtEquivalences/new',{templateUrl:'views/CatalArtEquivalence/detail.html',controller:'NewCatalArtEquivalenceController'}) // .when('/CatalArtEquivalences/edit/:CatalArtEquivalenceId',{templateUrl:'views/CatalArtEquivalence/detail.html',controller:'EditCatalArtEquivalenceController'}) // .when('/CatalArtFeatMappings',{templateUrl:'views/CatalArtFeatMapping/search.html',controller:'SearchCatalArtFeatMappingController'}) // .when('/CatalArtFeatMappings/new',{templateUrl:'views/CatalArtFeatMapping/detail.html',controller:'NewCatalArtFeatMappingController'}) // .when('/CatalArtFeatMappings/edit/:CatalArtFeatMappingId',{templateUrl:'views/CatalArtFeatMapping/detail.html',controller:'EditCatalArtFeatMappingController'}) // .when('/CatalArtManufSupps',{templateUrl:'views/CatalArtManufSupp/search.html',controller:'SearchCatalArtManufSuppController'}) // .when('/CatalArtManufSupps/new',{templateUrl:'views/CatalArtManufSupp/detail.html',controller:'NewCatalArtManufSuppController'}) // .when('/CatalArtManufSupps/edit/:CatalArtManufSuppId',{templateUrl:'views/CatalArtManufSupp/detail.html',controller:'EditCatalArtManufSuppController'}) // .when('/CatalFamilyFeatMapings',{templateUrl:'views/CatalFamilyFeatMaping/search.html',controller:'SearchCatalFamilyFeatMapingController'}) // .when('/CatalFamilyFeatMapings/new',{templateUrl:'views/CatalFamilyFeatMaping/detail.html',controller:'NewCatalFamilyFeatMapingController'}) // .when('/CatalFamilyFeatMapings/edit/:CatalFamilyFeatMapingId',{templateUrl:'views/CatalFamilyFeatMaping/detail.html',controller:'EditCatalFamilyFeatMapingController'}) // .when('/CatalManufSuppls',{templateUrl:'views/CatalManufSuppl/search.html',controller:'SearchCatalManufSupplController'}) // .when('/CatalManufSuppls/new',{templateUrl:'views/CatalManufSuppl/detail.html',controller:'NewCatalManufSupplController'}) // .when('/CatalManufSuppls/edit/:CatalManufSupplId',{templateUrl:'views/CatalManufSuppl/detail.html',controller:'EditCatalManufSupplController'}) // .when('/CatalPicMappings',{templateUrl:'views/CatalPicMapping/search.html',controller:'SearchCatalPicMappingController'}) // .when('/CatalPicMappings/new',{templateUrl:'views/CatalPicMapping/detail.html',controller:'NewCatalPicMappingController'}) // .when('/CatalPicMappings/edit/:CatalPicMappingId',{templateUrl:'views/CatalPicMapping/detail.html',controller:'EditCatalPicMappingController'}) .when('/CatalPkgModes',{templateUrl:'views/CatalPkgMode/search.html',controller:'catalPkgModeCtrl'}) .when('/CatalPkgModes/new',{templateUrl:'views/CatalPkgMode/create.html',controller:'catalPkgModeCreateCtrl'}) .when('/CatalPkgModes/edit/:identif',{templateUrl:'views/CatalPkgMode/edit.html',controller:'catalPkgModeEditCtrl'}) .when('/CatalPkgModes/show/:identif',{templateUrl:'views/CatalPkgMode/show.html',controller:'catalPkgModeShowCtrl'}) .when('/CatalProductFamilies',{templateUrl:'views/CatalProductFamily/search.html',controller:'SearchCatalProductFamilyController'}) .when('/CatalProductFamilies/new',{templateUrl:'views/CatalProductFamily/detail.html',controller:'NewCatalProductFamilyController'}) .when('/CatalProductFamilies/edit/:CatalProductFamilyId',{templateUrl:'views/CatalProductFamily/detail.html',controller:'EditCatalProductFamilyController'}) .otherwise({ redirectTo: '/' }); $httpProvider.defaults.withCredentials = true; $httpProvider.interceptors.push('authInterceptor'); $translateProvider.useLoader('$translatePartialLoader', { urlTemplate: '{part}/locale-{lang}.json' }); }]) // //.controller('NavController', function NavController($scope, $location) { // $scope.matchesRoute = function(route) { // var path = $location.path(); // return (path === ("/" + route) || path.indexOf("/" + route + "/") == 0); // }; //}) // .run(['$rootScope', '$location','sessionManager','$translate','APP_CONFIG','$translatePartialLoader', function ($rootScope, $location, sessionManager,$translate,APP_CONFIG,$translatePartialLoader) { $rootScope.appName = APP_CONFIG.appName ; $rootScope.appVersion = APP_CONFIG.appVersion ; $translatePartialLoader.addPart('/adcatal.client/i18n/main'); sessionManager.appMenuUrl("/adcatal.client/menu.html"); $rootScope.sessionManager = sessionManager; $rootScope.$on('$locationChangeStart', function (event, next, current) { var noSess = !sessionManager.hasValues(sessionManager.terminalSession(), sessionManager.userSession()); if(noSess){ var sessParam = $location.search(); if(sessParam && sessionManager.hasValues(sessParam.trm,sessParam.usr)){ sessionManager.wsin(sessParam.trm,sessParam.usr, function(data, status, headers, config){ sessionManager.language(headers('X-USER-LANG'),false); $location.path('/'); } ); } } }); }]);
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ define(function(require){ 'use strict'; var Backbone = require('backbone'); var App = require('App'); var XAUtil = require('utils/XAUtils'); var XAEnums = require('utils/XAEnums'); var XALinks = require('modules/XALinks'); var DownloadservicepolicyTmpl = require('hbs!tmpl/common/downloadservicepolicy_tmpl'); var RangerPolicyList = require('collections/RangerPolicyList'); var localization = require('utils/XALangSupport'); var DownloadServicePolicy = Backbone.Marionette.ItemView.extend({ template : DownloadservicepolicyTmpl, initialize: function(options) { console.log("initialized a DownloadServicePolicy Layout"); var that = this, componentServices = []; _.extend(this, _.pick(options, 'collection','serviceNames','serviceDefList','serviceType','services', 'zoneServiceDefList','zoneServices')); if(!_.isEmpty(that.zoneServices) && !_.isUndefined(that.zoneServices)){ _.each(that.zoneServices, function(value, key){ if(key === that.serviceType){ componentServices = componentServices.concat(value); } }); }else{ componentServices = this.services.where({'type' : this.serviceType }); } this.serviceNames = componentServices.map(function(m){ return { 'name' : m.get('name') } }) this.bind("ok", this.okClicked); }, ui:{ 'servicesName' : '[data-id="servicesName"]', 'componentTypeSelected' : '[data-id="componentTypeSelected"]' }, events: function() { }, okClicked: function (modal) { var that = this, el = $(modal.currentTarget), urls ='/service/plugins/policies/exportJson', serviceName = this.ui.servicesName.val(); if (_.isEmpty(this.ui.componentTypeSelected.val())){ this.$el.find('.serviceValidationFile').show(); } if(_.isEmpty(serviceName)){ this.$el.find('.validateFile').show(); if(!_.isEmpty(this.ui.componentTypeSelected.val())){ this.$el.find('.serviceValidationFile').hide(); } return modal.preventClose(); } var urlString = XAUtil.getBaseUrl(); if(urlString.slice(-1) == "/") { urlString = urlString.slice(0,-1); }; if(App.vZone && App.vZone.vZoneName && !_.isEmpty(App.vZone.vZoneName)){ var exportUrl = urlString +urls+ '?serviceName='+serviceName+'&zoneName='+App.vZone.vZoneName; }else{ var exportUrl = urlString +urls+ '?serviceName='+serviceName; } XAUtil.blockUI(); $.ajax({ type: "GET", url:exportUrl+'&checkPoliciesExists=true', success:function(data,status,response){ XAUtil.blockUI('unblock'); if(response.status == 200 || response.statusText == "ok"){ var downloadUrl = exportUrl+'&checkPoliciesExists=false'; var downloadReport = $('<a href ="'+downloadUrl+'"></a>'); downloadReport.appendTo('body'); downloadReport[0].click(); downloadReport.remove(); }else{ XAUtil.alertBoxWithTimeSet(localization.tt('msg.noPolicytoExport')) } }, error : function(data,status,response){ XAUtil.blockUI('unblock'); XAUtil.defaultErrorHandler(status,data); }, }); }, onRender: function() { this.serviceSelect(); if(_.isUndefined(this.serviceType)){ this.$el.find('.seviceFiled').show(); this.renderComponentSelect() }else{ this.$el.find('.seviceFiled').hide(); } }, renderComponentSelect: function(){ var that = this; if(!_.isEmpty(this.zoneServiceDefList) && !_.isUndefined(this.zoneServiceDefList)){ var options = this.zoneServiceDefList.map(function(m){ return { 'id' : m.get('name'), 'text' : m.get('name')}}); }else{ var options = this.serviceDefList.map(function(m){ return { 'id' : m.get('name'), 'text' : m.get('name')}}); } var componentTyp = options.map(function(m){return m.text}) this.ui.componentTypeSelected.val(componentTyp); this.ui.componentTypeSelected.select2({ multiple: true, closeOnSelect: true, placeholder: 'Select Component', //maximumSelectionSize : 1, width: '530px', allowClear: true, data: options }).on('change', function(e){ console.log(e); var selectedComp = e.currentTarget.value, componentServices = []; _.each(selectedComp.split(","), function(type){ if(!_.isEmpty(that.zoneServices) && !_.isUndefined(that.zoneServices)){ _.each(that.zoneServices, function(value, key){ if(key === type){ componentServices = componentServices.concat(value); } }); }else{ that.serviceNam = that.services.where({'type' : type }); componentServices = componentServices.concat(that.serviceNam); } }); var names = componentServices.map(function(m){ return { 'name' : m.get('name') } }); that.serviceNames = names; that.collection.trigger('reset') that.serviceSelect(that.serviceNam) }).trigger('change'); }, serviceSelect :function(e){ var options =this.serviceNames.map(function(m){ return { 'id' : m.name, 'text' : m.name}; }); var serviceTyp = options.map(function(m){return m.text}) this.ui.servicesName.val(serviceTyp); this.ui.servicesName.select2({ multiple: true, closeOnSelect: true, placeholder: 'Select Service Name', width: '530px', allowClear: true, data: options }) } }); return DownloadServicePolicy; });
// Contador para o indice de cada id dos quadrados let contador = 0; // Função cria e adiciona um elemento quadrado function criaQuadrado(){ // Cria uma div referente ao novo quadrado let element = document.createElement('div'); // Atribui o id do quadrado element.setAttribute('id', `quadrado${contador}`); contador = contador + 1; // Estilo do quadrado element.style.width = '100px'; element.style.height = '100px'; element.style.backgroundColor = '#f00'; element.style.float = 'left'; // Adiciona ao container/blocos de quadrados let container = document.querySelector('#quadrados'); container.appendChild(element); } // Seleciona o botão de adicionar let button = document.querySelector('#button'); // Atribui a função ao clicar no botao button.onclick = criaQuadrado;
import { isEmptyObject, queryToJson } from './util' import { cacheDataGet, cacheDataHas } from './data-cache' import { updateComponent } from './lifecycle' import camelCase from 'lodash/camelCase' const privatePropValName = 'privatetriggerobserer' const anonymousFnNamePreffix = 'funPrivate' const componentFnReg = /^prv-fn-/ const PRELOAD_DATA_KEY = 'preload' const pageExtraFns = ['onBackPress', 'onMenuPress'] function filterProps (properties, defaultProps = {}, componentProps = {}, componentData) { let newProps = Object.assign({}, componentProps) for (const propName in properties) { if (propName === privatePropValName) { continue } if (typeof componentProps[propName] === 'function') { newProps[propName] = componentProps[propName] } else if (componentData && propName in componentData) { newProps[propName] = componentData[propName] } if (componentFnReg.test(propName)) { if (componentData && componentData[propName] === true) { const fnName = propName.replace(componentFnReg, '') newProps[fnName] = noop } delete newProps[propName] } } if (!isEmptyObject(defaultProps)) { for (const propName in defaultProps) { if (newProps[propName] === undefined || newProps[propName] === null) { newProps[propName] = defaultProps[propName] } } } Object.keys(newProps).forEach(propName => { const camelizePropName = camelCase(propName) if (camelizePropName !== propName) { Object.defineProperty(newProps, camelizePropName, { get () { return newProps[propName] } }) } }) return newProps } function processEvent (eventHandlerName, obj) { if (obj[eventHandlerName]) return obj[eventHandlerName] = function (event) { if (event) { const currentTarget = event.currentTarget const target = event.target Object.defineProperties(event, { target: { configurable: true, get () { return Object.assign(target || {}, event.detail) } }, currentTarget: { configurable: true, get () { return Object.assign(currentTarget || target || {}, event.detail) } }, stopPropagation: { value: () => {} }, preventDefault: { value: () => {} } }) } const scope = this.$component let callScope = scope const isAnonymousFn = eventHandlerName.indexOf(anonymousFnNamePreffix) > -1 let realArgs = [] let detailArgs = [] let datasetArgs = [] let isScopeBinded = false // 解析从dataset中传过来的参数 const dataset = {} const currentTarget = event.currentTarget const vm = currentTarget._vm || (currentTarget._target ? currentTarget._target._vm : null) const attr = vm ? vm._externalBinding.template.attr : currentTarget._attr if (attr) { Object.keys(attr).forEach(key => { if (/^data/.test(key)) { const item = attr[key] dataset[key.replace(/^data/, '')] = typeof item === 'function' ? item() : item } }) } const bindArgs = {} const eventType = `on${event.type}`.toLocaleLowerCase() if (event.detail && event.detail.__detail) Object.assign(dataset, event.detail.__detail) Object.keys(dataset).forEach(key => { let keyLower = key.toLocaleLowerCase() if (/^e/.test(keyLower)) { // 小程序属性里中划线后跟一个下划线会解析成不同的结果 keyLower = keyLower.replace(/^e/, '') if (keyLower.indexOf(eventType) >= 0) { const argName = keyLower.replace(eventType, '') if (/^(a[a-z]|so)$/.test(argName)) { bindArgs[argName] = dataset[key] } } } }) // 如果是通过triggerEvent触发,并且带有参数 if (event.detail && event.detail.__arguments && event.detail.__arguments.length > 0) { detailArgs = event.detail.__arguments } // 普通的事件(非匿名函数),会直接call if (!isAnonymousFn) { if ('so' in bindArgs) { if (bindArgs['so'] !== 'this') { callScope = bindArgs['so'] } isScopeBinded = true delete bindArgs['so'] } if (detailArgs.length > 0) { !isScopeBinded && detailArgs[0] && (callScope = detailArgs[0]) detailArgs.shift() } if (!isEmptyObject(bindArgs)) { datasetArgs = Object.keys(bindArgs) .sort() .map(key => bindArgs[key]) } realArgs = [...datasetArgs, ...detailArgs, event] } else { // 匿名函数,会将scope作为第一个参数 let _scope = null if ('so' in bindArgs) { if (bindArgs['so'] !== 'this') { _scope = bindArgs['so'] } isScopeBinded = true delete bindArgs['so'] } if (detailArgs.length > 0) { !isScopeBinded && detailArgs[0] && (callScope = detailArgs[0]) detailArgs.shift() } if (!isEmptyObject(bindArgs)) { datasetArgs = Object.keys(bindArgs) .sort() .map(key => bindArgs[key]) } realArgs = [_scope, ...datasetArgs, ...detailArgs, event] } return scope[eventHandlerName].apply(callScope, realArgs) } } function bindEvents (componentConf, events) { events.forEach(name => { processEvent(name, componentConf) }) } function bindStaticFns (componentConf, ComponentClass) { for (const key in ComponentClass) { typeof ComponentClass[key] === 'function' && (componentConf[key] = ComponentClass[key]) } // 低版本 IOS 下部分属性不能直接访问 Object.getOwnPropertyNames(ComponentClass).forEach(key => { const excludes = ['arguments', 'caller', 'length', 'name', 'prototype'] if (excludes.indexOf(key) < 0) { typeof ComponentClass[key] === 'function' && (componentConf[key] = ComponentClass[key]) } }) } function bindProperties (componentConf, ComponentClass) { componentConf.properties = ComponentClass.properties || {} const defaultProps = ComponentClass.defaultProps || {} for (const key in defaultProps) { if (defaultProps.hasOwnProperty(key)) { componentConf.properties[key] = { type: null, value: defaultProps[key] } } } componentConf.props = [] Object.keys(componentConf.properties).forEach(item => { componentConf.props.push(item.toLocaleLowerCase()) }) componentConf.props.push(privatePropValName) componentConf.onPrivatePropChange = function () { if (!this.$component || !this.$component.__isReady) return const nextProps = filterProps(ComponentClass.properties, ComponentClass.defaultProps, this.$component.props, this) this.$component.props = nextProps this.$component._unsafeCallUpdate = true updateComponent(this.$component) this.$component._unsafeCallUpdate = false } } function getPageUrlParams (url) { if (!url) { return {} } const queryStr = url.replace(/^.*\?&?/, '') const params = queryToJson(queryStr) return params } let hasPageInited = false function initComponent (ComponentClass, isPage) { if (this.$component.__isReady) return this.$component.__isReady = true if (isPage && !hasPageInited) { hasPageInited = true } if (hasPageInited && !isPage) { const nextProps = filterProps(ComponentClass.properties, ComponentClass.defaultProps, this.$component.props, this) this.$component.props = nextProps } if (hasPageInited || isPage) { updateComponent(this.$component) } } export function componentTrigger (component, key, args) { args = args || [] component[key] && typeof component[key] === 'function' && component[key].call(component, ...args) if (key === 'componentWillMount') { component._dirty = false component._disable = false component.state = component.getState() } if (key === 'componentWillUnmount') { component._dirty = true component._disable = true component.$router = { params: {}, path: '' } component._pendingStates = [] component._pendingCallbacks = [] } } export default function createComponent (ComponentClass, isPage) { let initData = {} const componentProps = filterProps(ComponentClass.properties, ComponentClass.defaultProps) const componentInstance = new ComponentClass(componentProps) componentInstance._constructor && componentInstance._constructor(componentProps) try { componentInstance.state = componentInstance._createData() || componentInstance.state } catch (err) { if (isPage) { console.warn(`[Taro warn] 请给页面提供初始 \`state\` 以提高初次渲染性能!`) } else { console.warn(`[Taro warn] 请给组件提供一个 \`defaultProps\` 以提高初次渲染性能!`) } console.warn(err) } initData = Object.assign({}, initData, componentInstance.props, componentInstance.state) const componentConf = { data: initData, onInit () { isPage && (hasPageInited = false) this.$component = new ComponentClass({}, isPage) this.$component._init(this) this.$component.render = this.$component._createData this.$component.__propTypes = ComponentClass.propTypes Object.assign(this.$component.$router.params, getPageUrlParams(this.$page.uri)) this.$app.pageInstaceMap = this.$app.pageInstaceMap || {} this.$app.pageInstaceMap[isPage] = this.$component if (isPage) { if (cacheDataHas(PRELOAD_DATA_KEY)) { const data = cacheDataGet(PRELOAD_DATA_KEY, true) this.$component.$router.preload = data } // this.$component.$router.path = getCurrentPageUrl() initComponent.apply(this, [ComponentClass, isPage]) } // 监听数据变化 this.$watch(privatePropValName, 'onPrivatePropChange') }, onReady () { if (!isPage) { initComponent.apply(this, [ComponentClass, isPage]) } const component = this.$component if (!component.__mounted) { component.__mounted = true componentTrigger(component, 'componentDidMount') } }, onDestroy () { componentTrigger(this.$component, 'componentWillUnmount') } } if (isPage) { componentConf['onShow'] = function () { componentTrigger(this.$component, 'componentDidShow') } componentConf['onHide'] = function () { componentTrigger(this.$component, 'componentDidHide') } pageExtraFns.forEach(fn => { if (componentInstance[fn] && typeof componentInstance[fn] === 'function') { componentConf[fn] = function () { const component = this.$component if (component[fn] && typeof component[fn] === 'function') { return component[fn](...arguments) } } } }) } bindStaticFns(componentConf, ComponentClass) bindProperties(componentConf, ComponentClass) ComponentClass['$$events'] && bindEvents(componentConf, ComponentClass['$$events']) return componentConf }
const config = require('./config.js'); let exec = require('child_process').exec; const args = process.env.npm_config_argv; // if no arg passed, allow deployment to staging be default let env = JSON.parse(args).original[2] !== undefined ? JSON.parse(args).original[2].replace('--','') : null; if (env != 'production') env = 'staging'; let cmd = 'rsync -azP'; for (let e of config.deploy[env].exclude) cmd += ` --exclude '${e}'`; cmd += ` ${config.deploy[env].source} ${config.deploy[env].username}@${config.deploy[env].hostname}:${config.deploy[env].destination}`; exec(cmd, (e) => { if (e !== null) console.log(e); });
(function(t){"function"==typeof define&&define.amd?define(["jquery"],t):t(jQuery)})(function(t){function e(t){for(var e=t.css("visibility");"inherit"===e;)t=t.parent(),e=t.css("visibility");return"hidden"!==e}function i(t){for(var e,i;t.length&&t[0]!==document;){if(e=t.css("position"),("absolute"===e||"relative"===e||"fixed"===e)&&(i=parseInt(t.css("zIndex"),10),!isNaN(i)&&0!==i))return i;t=t.parent()}return 0}function s(){this._curInst=null,this._keyEvent=!1,this._disabledInputs=[],this._datepickerShowing=!1,this._inDialog=!1,this._mainDivId="ui-datepicker-div",this._inlineClass="ui-datepicker-inline",this._appendClass="ui-datepicker-append",this._triggerClass="ui-datepicker-trigger",this._dialogClass="ui-datepicker-dialog",this._disableClass="ui-datepicker-disabled",this._unselectableClass="ui-datepicker-unselectable",this._currentClass="ui-datepicker-current-day",this._dayOverClass="ui-datepicker-days-cell-over",this.regional=[],this.regional[""]={closeText:"Done",prevText:"Prev",nextText:"Next",currentText:"Today",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],weekHeader:"Wk",dateFormat:"mm/dd/yy",firstDay:0,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},this._defaults={showOn:"focus",showAnim:"fadeIn",showOptions:{},defaultDate:null,appendText:"",buttonText:"...",buttonImage:"",buttonImageOnly:!1,hideIfNoPrevNext:!1,navigationAsDateFormat:!1,gotoCurrent:!1,changeMonth:!1,changeYear:!1,yearRange:"c-10:c+10",showOtherMonths:!1,selectOtherMonths:!1,showWeek:!1,calculateWeek:this.iso8601Week,shortYearCutoff:"+10",minDate:null,maxDate:null,duration:"fast",beforeShowDay:null,beforeShow:null,onSelect:null,onChangeMonthYear:null,onClose:null,numberOfMonths:1,showCurrentAtPos:0,stepMonths:1,stepBigMonths:12,altField:"",altFormat:"",constrainInput:!0,showButtonPanel:!1,autoSize:!1,disabled:!1},t.extend(this._defaults,this.regional[""]),this.regional.en=t.extend(!0,{},this.regional[""]),this.regional["en-US"]=t.extend(!0,{},this.regional.en),this.dpDiv=n(t("<div id='"+this._mainDivId+"' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>"))}function n(e){var i="button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";return e.on("mouseout",i,function(){t(this).removeClass("ui-state-hover"),-1!==this.className.indexOf("ui-datepicker-prev")&&t(this).removeClass("ui-datepicker-prev-hover"),-1!==this.className.indexOf("ui-datepicker-next")&&t(this).removeClass("ui-datepicker-next-hover")}).on("mouseover",i,a)}function a(){t.datepicker._isDisabledDatepicker(p.inline?p.dpDiv.parent()[0]:p.input[0])||(t(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover"),t(this).addClass("ui-state-hover"),-1!==this.className.indexOf("ui-datepicker-prev")&&t(this).addClass("ui-datepicker-prev-hover"),-1!==this.className.indexOf("ui-datepicker-next")&&t(this).addClass("ui-datepicker-next-hover"))}function o(e,i){t.extend(e,i);for(var s in i)null==i[s]&&(e[s]=i[s]);return e}function r(t){return function(){var e=this.element.val();t.apply(this,arguments),this._refresh(),e!==this.element.val()&&this._trigger("change")}}t.ui=t.ui||{},t.ui.version="1.12.1";var h=0,l=Array.prototype.slice;t.cleanData=function(e){return function(i){var s,n,a;for(a=0;null!=(n=i[a]);a++)try{s=t._data(n,"events"),s&&s.remove&&t(n).triggerHandler("remove")}catch(o){}e(i)}}(t.cleanData),t.widget=function(e,i,s){var n,a,o,r={},h=e.split(".")[0];e=e.split(".")[1];var l=h+"-"+e;return s||(s=i,i=t.Widget),t.isArray(s)&&(s=t.extend.apply(null,[{}].concat(s))),t.expr[":"][l.toLowerCase()]=function(e){return!!t.data(e,l)},t[h]=t[h]||{},n=t[h][e],a=t[h][e]=function(t,e){return this._createWidget?(arguments.length&&this._createWidget(t,e),void 0):new a(t,e)},t.extend(a,n,{version:s.version,_proto:t.extend({},s),_childConstructors:[]}),o=new i,o.options=t.widget.extend({},o.options),t.each(s,function(e,s){return t.isFunction(s)?(r[e]=function(){function t(){return i.prototype[e].apply(this,arguments)}function n(t){return i.prototype[e].apply(this,t)}return function(){var e,i=this._super,a=this._superApply;return this._super=t,this._superApply=n,e=s.apply(this,arguments),this._super=i,this._superApply=a,e}}(),void 0):(r[e]=s,void 0)}),a.prototype=t.widget.extend(o,{widgetEventPrefix:n?o.widgetEventPrefix||e:e},r,{constructor:a,namespace:h,widgetName:e,widgetFullName:l}),n?(t.each(n._childConstructors,function(e,i){var s=i.prototype;t.widget(s.namespace+"."+s.widgetName,a,i._proto)}),delete n._childConstructors):i._childConstructors.push(a),t.widget.bridge(e,a),a},t.widget.extend=function(e){for(var i,s,n=l.call(arguments,1),a=0,o=n.length;o>a;a++)for(i in n[a])s=n[a][i],n[a].hasOwnProperty(i)&&void 0!==s&&(e[i]=t.isPlainObject(s)?t.isPlainObject(e[i])?t.widget.extend({},e[i],s):t.widget.extend({},s):s);return e},t.widget.bridge=function(e,i){var s=i.prototype.widgetFullName||e;t.fn[e]=function(n){var a="string"==typeof n,o=l.call(arguments,1),r=this;return a?this.length||"instance"!==n?this.each(function(){var i,a=t.data(this,s);return"instance"===n?(r=a,!1):a?t.isFunction(a[n])&&"_"!==n.charAt(0)?(i=a[n].apply(a,o),i!==a&&void 0!==i?(r=i&&i.jquery?r.pushStack(i.get()):i,!1):void 0):t.error("no such method '"+n+"' for "+e+" widget instance"):t.error("cannot call methods on "+e+" prior to initialization; "+"attempted to call method '"+n+"'")}):r=void 0:(o.length&&(n=t.widget.extend.apply(null,[n].concat(o))),this.each(function(){var e=t.data(this,s);e?(e.option(n||{}),e._init&&e._init()):t.data(this,s,new i(n,this))})),r}},t.Widget=function(){},t.Widget._childConstructors=[],t.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"<div>",options:{classes:{},disabled:!1,create:null},_createWidget:function(e,i){i=t(i||this.defaultElement||this)[0],this.element=t(i),this.uuid=h++,this.eventNamespace="."+this.widgetName+this.uuid,this.bindings=t(),this.hoverable=t(),this.focusable=t(),this.classesElementLookup={},i!==this&&(t.data(i,this.widgetFullName,this),this._on(!0,this.element,{remove:function(t){t.target===i&&this.destroy()}}),this.document=t(i.style?i.ownerDocument:i.document||i),this.window=t(this.document[0].defaultView||this.document[0].parentWindow)),this.options=t.widget.extend({},this.options,this._getCreateOptions(),e),this._create(),this.options.disabled&&this._setOptionDisabled(this.options.disabled),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:function(){return{}},_getCreateEventData:t.noop,_create:t.noop,_init:t.noop,destroy:function(){var e=this;this._destroy(),t.each(this.classesElementLookup,function(t,i){e._removeClass(i,t)}),this.element.off(this.eventNamespace).removeData(this.widgetFullName),this.widget().off(this.eventNamespace).removeAttr("aria-disabled"),this.bindings.off(this.eventNamespace)},_destroy:t.noop,widget:function(){return this.element},option:function(e,i){var s,n,a,o=e;if(0===arguments.length)return t.widget.extend({},this.options);if("string"==typeof e)if(o={},s=e.split("."),e=s.shift(),s.length){for(n=o[e]=t.widget.extend({},this.options[e]),a=0;s.length-1>a;a++)n[s[a]]=n[s[a]]||{},n=n[s[a]];if(e=s.pop(),1===arguments.length)return void 0===n[e]?null:n[e];n[e]=i}else{if(1===arguments.length)return void 0===this.options[e]?null:this.options[e];o[e]=i}return this._setOptions(o),this},_setOptions:function(t){var e;for(e in t)this._setOption(e,t[e]);return this},_setOption:function(t,e){return"classes"===t&&this._setOptionClasses(e),this.options[t]=e,"disabled"===t&&this._setOptionDisabled(e),this},_setOptionClasses:function(e){var i,s,n;for(i in e)n=this.classesElementLookup[i],e[i]!==this.options.classes[i]&&n&&n.length&&(s=t(n.get()),this._removeClass(n,i),s.addClass(this._classes({element:s,keys:i,classes:e,add:!0})))},_setOptionDisabled:function(t){this._toggleClass(this.widget(),this.widgetFullName+"-disabled",null,!!t),t&&(this._removeClass(this.hoverable,null,"ui-state-hover"),this._removeClass(this.focusable,null,"ui-state-focus"))},enable:function(){return this._setOptions({disabled:!1})},disable:function(){return this._setOptions({disabled:!0})},_classes:function(e){function i(i,a){var o,r;for(r=0;i.length>r;r++)o=n.classesElementLookup[i[r]]||t(),o=e.add?t(t.unique(o.get().concat(e.element.get()))):t(o.not(e.element).get()),n.classesElementLookup[i[r]]=o,s.push(i[r]),a&&e.classes[i[r]]&&s.push(e.classes[i[r]])}var s=[],n=this;return e=t.extend({element:this.element,classes:this.options.classes||{}},e),this._on(e.element,{remove:"_untrackClassesElement"}),e.keys&&i(e.keys.match(/\S+/g)||[],!0),e.extra&&i(e.extra.match(/\S+/g)||[]),s.join(" ")},_untrackClassesElement:function(e){var i=this;t.each(i.classesElementLookup,function(s,n){-1!==t.inArray(e.target,n)&&(i.classesElementLookup[s]=t(n.not(e.target).get()))})},_removeClass:function(t,e,i){return this._toggleClass(t,e,i,!1)},_addClass:function(t,e,i){return this._toggleClass(t,e,i,!0)},_toggleClass:function(t,e,i,s){s="boolean"==typeof s?s:i;var n="string"==typeof t||null===t,a={extra:n?e:i,keys:n?t:e,element:n?this.element:t,add:s};return a.element.toggleClass(this._classes(a),s),this},_on:function(e,i,s){var n,a=this;"boolean"!=typeof e&&(s=i,i=e,e=!1),s?(i=n=t(i),this.bindings=this.bindings.add(i)):(s=i,i=this.element,n=this.widget()),t.each(s,function(s,o){function r(){return e||a.options.disabled!==!0&&!t(this).hasClass("ui-state-disabled")?("string"==typeof o?a[o]:o).apply(a,arguments):void 0}"string"!=typeof o&&(r.guid=o.guid=o.guid||r.guid||t.guid++);var h=s.match(/^([\w:-]*)\s*(.*)$/),l=h[1]+a.eventNamespace,u=h[2];u?n.on(l,u,r):i.on(l,r)})},_off:function(e,i){i=(i||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace,e.off(i).off(i),this.bindings=t(this.bindings.not(e).get()),this.focusable=t(this.focusable.not(e).get()),this.hoverable=t(this.hoverable.not(e).get())},_delay:function(t,e){function i(){return("string"==typeof t?s[t]:t).apply(s,arguments)}var s=this;return setTimeout(i,e||0)},_hoverable:function(e){this.hoverable=this.hoverable.add(e),this._on(e,{mouseenter:function(e){this._addClass(t(e.currentTarget),null,"ui-state-hover")},mouseleave:function(e){this._removeClass(t(e.currentTarget),null,"ui-state-hover")}})},_focusable:function(e){this.focusable=this.focusable.add(e),this._on(e,{focusin:function(e){this._addClass(t(e.currentTarget),null,"ui-state-focus")},focusout:function(e){this._removeClass(t(e.currentTarget),null,"ui-state-focus")}})},_trigger:function(e,i,s){var n,a,o=this.options[e];if(s=s||{},i=t.Event(i),i.type=(e===this.widgetEventPrefix?e:this.widgetEventPrefix+e).toLowerCase(),i.target=this.element[0],a=i.originalEvent)for(n in a)n in i||(i[n]=a[n]);return this.element.trigger(i,s),!(t.isFunction(o)&&o.apply(this.element[0],[i].concat(s))===!1||i.isDefaultPrevented())}},t.each({show:"fadeIn",hide:"fadeOut"},function(e,i){t.Widget.prototype["_"+e]=function(s,n,a){"string"==typeof n&&(n={effect:n});var o,r=n?n===!0||"number"==typeof n?i:n.effect||i:e;n=n||{},"number"==typeof n&&(n={duration:n}),o=!t.isEmptyObject(n),n.complete=a,n.delay&&s.delay(n.delay),o&&t.effects&&t.effects.effect[r]?s[e](n):r!==e&&s[r]?s[r](n.duration,n.easing,a):s.queue(function(i){t(this)[e](),a&&a.call(s[0]),i()})}}),t.widget,function(){function e(t,e,i){return[parseFloat(t[0])*(c.test(t[0])?e/100:1),parseFloat(t[1])*(c.test(t[1])?i/100:1)]}function i(e,i){return parseInt(t.css(e,i),10)||0}function s(e){var i=e[0];return 9===i.nodeType?{width:e.width(),height:e.height(),offset:{top:0,left:0}}:t.isWindow(i)?{width:e.width(),height:e.height(),offset:{top:e.scrollTop(),left:e.scrollLeft()}}:i.preventDefault?{width:0,height:0,offset:{top:i.pageY,left:i.pageX}}:{width:e.outerWidth(),height:e.outerHeight(),offset:e.offset()}}var n,a=Math.max,o=Math.abs,r=/left|center|right/,h=/top|center|bottom/,l=/[\+\-]\d+(\.[\d]+)?%?/,u=/^\w+/,c=/%$/,d=t.fn.position;t.position={scrollbarWidth:function(){if(void 0!==n)return n;var e,i,s=t("<div style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>"),a=s.children()[0];return t("body").append(s),e=a.offsetWidth,s.css("overflow","scroll"),i=a.offsetWidth,e===i&&(i=s[0].clientWidth),s.remove(),n=e-i},getScrollInfo:function(e){var i=e.isWindow||e.isDocument?"":e.element.css("overflow-x"),s=e.isWindow||e.isDocument?"":e.element.css("overflow-y"),n="scroll"===i||"auto"===i&&e.width<e.element[0].scrollWidth,a="scroll"===s||"auto"===s&&e.height<e.element[0].scrollHeight;return{width:a?t.position.scrollbarWidth():0,height:n?t.position.scrollbarWidth():0}},getWithinInfo:function(e){var i=t(e||window),s=t.isWindow(i[0]),n=!!i[0]&&9===i[0].nodeType,a=!s&&!n;return{element:i,isWindow:s,isDocument:n,offset:a?t(e).offset():{left:0,top:0},scrollLeft:i.scrollLeft(),scrollTop:i.scrollTop(),width:i.outerWidth(),height:i.outerHeight()}}},t.fn.position=function(n){if(!n||!n.of)return d.apply(this,arguments);n=t.extend({},n);var c,p,f,m,g,_,v=t(n.of),b=t.position.getWithinInfo(n.within),y=t.position.getScrollInfo(b),w=(n.collision||"flip").split(" "),k={};return _=s(v),v[0].preventDefault&&(n.at="left top"),p=_.width,f=_.height,m=_.offset,g=t.extend({},m),t.each(["my","at"],function(){var t,e,i=(n[this]||"").split(" ");1===i.length&&(i=r.test(i[0])?i.concat(["center"]):h.test(i[0])?["center"].concat(i):["center","center"]),i[0]=r.test(i[0])?i[0]:"center",i[1]=h.test(i[1])?i[1]:"center",t=l.exec(i[0]),e=l.exec(i[1]),k[this]=[t?t[0]:0,e?e[0]:0],n[this]=[u.exec(i[0])[0],u.exec(i[1])[0]]}),1===w.length&&(w[1]=w[0]),"right"===n.at[0]?g.left+=p:"center"===n.at[0]&&(g.left+=p/2),"bottom"===n.at[1]?g.top+=f:"center"===n.at[1]&&(g.top+=f/2),c=e(k.at,p,f),g.left+=c[0],g.top+=c[1],this.each(function(){var s,r,h=t(this),l=h.outerWidth(),u=h.outerHeight(),d=i(this,"marginLeft"),_=i(this,"marginTop"),x=l+d+i(this,"marginRight")+y.width,D=u+_+i(this,"marginBottom")+y.height,C=t.extend({},g),T=e(k.my,h.outerWidth(),h.outerHeight());"right"===n.my[0]?C.left-=l:"center"===n.my[0]&&(C.left-=l/2),"bottom"===n.my[1]?C.top-=u:"center"===n.my[1]&&(C.top-=u/2),C.left+=T[0],C.top+=T[1],s={marginLeft:d,marginTop:_},t.each(["left","top"],function(e,i){t.ui.position[w[e]]&&t.ui.position[w[e]][i](C,{targetWidth:p,targetHeight:f,elemWidth:l,elemHeight:u,collisionPosition:s,collisionWidth:x,collisionHeight:D,offset:[c[0]+T[0],c[1]+T[1]],my:n.my,at:n.at,within:b,elem:h})}),n.using&&(r=function(t){var e=m.left-C.left,i=e+p-l,s=m.top-C.top,r=s+f-u,c={target:{element:v,left:m.left,top:m.top,width:p,height:f},element:{element:h,left:C.left,top:C.top,width:l,height:u},horizontal:0>i?"left":e>0?"right":"center",vertical:0>r?"top":s>0?"bottom":"middle"};l>p&&p>o(e+i)&&(c.horizontal="center"),u>f&&f>o(s+r)&&(c.vertical="middle"),c.important=a(o(e),o(i))>a(o(s),o(r))?"horizontal":"vertical",n.using.call(this,t,c)}),h.offset(t.extend(C,{using:r}))})},t.ui.position={fit:{left:function(t,e){var i,s=e.within,n=s.isWindow?s.scrollLeft:s.offset.left,o=s.width,r=t.left-e.collisionPosition.marginLeft,h=n-r,l=r+e.collisionWidth-o-n;e.collisionWidth>o?h>0&&0>=l?(i=t.left+h+e.collisionWidth-o-n,t.left+=h-i):t.left=l>0&&0>=h?n:h>l?n+o-e.collisionWidth:n:h>0?t.left+=h:l>0?t.left-=l:t.left=a(t.left-r,t.left)},top:function(t,e){var i,s=e.within,n=s.isWindow?s.scrollTop:s.offset.top,o=e.within.height,r=t.top-e.collisionPosition.marginTop,h=n-r,l=r+e.collisionHeight-o-n;e.collisionHeight>o?h>0&&0>=l?(i=t.top+h+e.collisionHeight-o-n,t.top+=h-i):t.top=l>0&&0>=h?n:h>l?n+o-e.collisionHeight:n:h>0?t.top+=h:l>0?t.top-=l:t.top=a(t.top-r,t.top)}},flip:{left:function(t,e){var i,s,n=e.within,a=n.offset.left+n.scrollLeft,r=n.width,h=n.isWindow?n.scrollLeft:n.offset.left,l=t.left-e.collisionPosition.marginLeft,u=l-h,c=l+e.collisionWidth-r-h,d="left"===e.my[0]?-e.elemWidth:"right"===e.my[0]?e.elemWidth:0,p="left"===e.at[0]?e.targetWidth:"right"===e.at[0]?-e.targetWidth:0,f=-2*e.offset[0];0>u?(i=t.left+d+p+f+e.collisionWidth-r-a,(0>i||o(u)>i)&&(t.left+=d+p+f)):c>0&&(s=t.left-e.collisionPosition.marginLeft+d+p+f-h,(s>0||c>o(s))&&(t.left+=d+p+f))},top:function(t,e){var i,s,n=e.within,a=n.offset.top+n.scrollTop,r=n.height,h=n.isWindow?n.scrollTop:n.offset.top,l=t.top-e.collisionPosition.marginTop,u=l-h,c=l+e.collisionHeight-r-h,d="top"===e.my[1],p=d?-e.elemHeight:"bottom"===e.my[1]?e.elemHeight:0,f="top"===e.at[1]?e.targetHeight:"bottom"===e.at[1]?-e.targetHeight:0,m=-2*e.offset[1];0>u?(s=t.top+p+f+m+e.collisionHeight-r-a,(0>s||o(u)>s)&&(t.top+=p+f+m)):c>0&&(i=t.top-e.collisionPosition.marginTop+p+f+m-h,(i>0||c>o(i))&&(t.top+=p+f+m))}},flipfit:{left:function(){t.ui.position.flip.left.apply(this,arguments),t.ui.position.fit.left.apply(this,arguments)},top:function(){t.ui.position.flip.top.apply(this,arguments),t.ui.position.fit.top.apply(this,arguments)}}}}(),t.ui.position,t.extend(t.expr[":"],{data:t.expr.createPseudo?t.expr.createPseudo(function(e){return function(i){return!!t.data(i,e)}}):function(e,i,s){return!!t.data(e,s[3])}}),t.fn.extend({disableSelection:function(){var t="onselectstart"in document.createElement("div")?"selectstart":"mousedown";return function(){return this.on(t+".ui-disableSelection",function(t){t.preventDefault()})}}(),enableSelection:function(){return this.off(".ui-disableSelection")}}),t.ui.focusable=function(i,s){var n,a,o,r,h,l=i.nodeName.toLowerCase();return"area"===l?(n=i.parentNode,a=n.name,i.href&&a&&"map"===n.nodeName.toLowerCase()?(o=t("img[usemap='#"+a+"']"),o.length>0&&o.is(":visible")):!1):(/^(input|select|textarea|button|object)$/.test(l)?(r=!i.disabled,r&&(h=t(i).closest("fieldset")[0],h&&(r=!h.disabled))):r="a"===l?i.href||s:s,r&&t(i).is(":visible")&&e(t(i)))},t.extend(t.expr[":"],{focusable:function(e){return t.ui.focusable(e,null!=t.attr(e,"tabindex"))}}),t.ui.focusable,t.fn.form=function(){return"string"==typeof this[0].form?this.closest("form"):t(this[0].form)},t.ui.formResetMixin={_formResetHandler:function(){var e=t(this);setTimeout(function(){var i=e.data("ui-form-reset-instances");t.each(i,function(){this.refresh()})})},_bindFormResetHandler:function(){if(this.form=this.element.form(),this.form.length){var t=this.form.data("ui-form-reset-instances")||[];t.length||this.form.on("reset.ui-form-reset",this._formResetHandler),t.push(this),this.form.data("ui-form-reset-instances",t)}},_unbindFormResetHandler:function(){if(this.form.length){var e=this.form.data("ui-form-reset-instances");e.splice(t.inArray(this,e),1),e.length?this.form.data("ui-form-reset-instances",e):this.form.removeData("ui-form-reset-instances").off("reset.ui-form-reset")}}},"1.7"===t.fn.jquery.substring(0,3)&&(t.each(["Width","Height"],function(e,i){function s(e,i,s,a){return t.each(n,function(){i-=parseFloat(t.css(e,"padding"+this))||0,s&&(i-=parseFloat(t.css(e,"border"+this+"Width"))||0),a&&(i-=parseFloat(t.css(e,"margin"+this))||0)}),i}var n="Width"===i?["Left","Right"]:["Top","Bottom"],a=i.toLowerCase(),o={innerWidth:t.fn.innerWidth,innerHeight:t.fn.innerHeight,outerWidth:t.fn.outerWidth,outerHeight:t.fn.outerHeight};t.fn["inner"+i]=function(e){return void 0===e?o["inner"+i].call(this):this.each(function(){t(this).css(a,s(this,e)+"px")})},t.fn["outer"+i]=function(e,n){return"number"!=typeof e?o["outer"+i].call(this,e):this.each(function(){t(this).css(a,s(this,e,!0,n)+"px")})}}),t.fn.addBack=function(t){return this.add(null==t?this.prevObject:this.prevObject.filter(t))}),t.ui.keyCode={BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38},t.ui.escapeSelector=function(){var t=/([!"#$%&'()*+,./:;<=>?@[\]^`{|}~])/g;return function(e){return e.replace(t,"\\$1")}}(),t.fn.labels=function(){var e,i,s,n,a;return this[0].labels&&this[0].labels.length?this.pushStack(this[0].labels):(n=this.eq(0).parents("label"),s=this.attr("id"),s&&(e=this.eq(0).parents().last(),a=e.add(e.length?e.siblings():this.siblings()),i="label[for='"+t.ui.escapeSelector(s)+"']",n=n.add(a.find(i).addBack(i))),this.pushStack(n))},t.fn.scrollParent=function(e){var i=this.css("position"),s="absolute"===i,n=e?/(auto|scroll|hidden)/:/(auto|scroll)/,a=this.parents().filter(function(){var e=t(this);return s&&"static"===e.css("position")?!1:n.test(e.css("overflow")+e.css("overflow-y")+e.css("overflow-x"))}).eq(0);return"fixed"!==i&&a.length?a:t(this[0].ownerDocument||document)},t.extend(t.expr[":"],{tabbable:function(e){var i=t.attr(e,"tabindex"),s=null!=i;return(!s||i>=0)&&t.ui.focusable(e,s)}}),t.fn.extend({uniqueId:function(){var t=0;return function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++t)})}}(),removeUniqueId:function(){return this.each(function(){/^ui-id-\d+$/.test(this.id)&&t(this).removeAttr("id")})}}),t.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase());var u=!1;t(document).on("mouseup",function(){u=!1}),t.widget("ui.mouse",{version:"1.12.1",options:{cancel:"input, textarea, button, select, option",distance:1,delay:0},_mouseInit:function(){var e=this;this.element.on("mousedown."+this.widgetName,function(t){return e._mouseDown(t)}).on("click."+this.widgetName,function(i){return!0===t.data(i.target,e.widgetName+".preventClickEvent")?(t.removeData(i.target,e.widgetName+".preventClickEvent"),i.stopImmediatePropagation(),!1):void 0}),this.started=!1},_mouseDestroy:function(){this.element.off("."+this.widgetName),this._mouseMoveDelegate&&this.document.off("mousemove."+this.widgetName,this._mouseMoveDelegate).off("mouseup."+this.widgetName,this._mouseUpDelegate)},_mouseDown:function(e){if(!u){this._mouseMoved=!1,this._mouseStarted&&this._mouseUp(e),this._mouseDownEvent=e;var i=this,s=1===e.which,n="string"==typeof this.options.cancel&&e.target.nodeName?t(e.target).closest(this.options.cancel).length:!1;return s&&!n&&this._mouseCapture(e)?(this.mouseDelayMet=!this.options.delay,this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){i.mouseDelayMet=!0},this.options.delay)),this._mouseDistanceMet(e)&&this._mouseDelayMet(e)&&(this._mouseStarted=this._mouseStart(e)!==!1,!this._mouseStarted)?(e.preventDefault(),!0):(!0===t.data(e.target,this.widgetName+".preventClickEvent")&&t.removeData(e.target,this.widgetName+".preventClickEvent"),this._mouseMoveDelegate=function(t){return i._mouseMove(t)},this._mouseUpDelegate=function(t){return i._mouseUp(t)},this.document.on("mousemove."+this.widgetName,this._mouseMoveDelegate).on("mouseup."+this.widgetName,this._mouseUpDelegate),e.preventDefault(),u=!0,!0)):!0}},_mouseMove:function(e){if(this._mouseMoved){if(t.ui.ie&&(!document.documentMode||9>document.documentMode)&&!e.button)return this._mouseUp(e);if(!e.which)if(e.originalEvent.altKey||e.originalEvent.ctrlKey||e.originalEvent.metaKey||e.originalEvent.shiftKey)this.ignoreMissingWhich=!0;else if(!this.ignoreMissingWhich)return this._mouseUp(e)}return(e.which||e.button)&&(this._mouseMoved=!0),this._mouseStarted?(this._mouseDrag(e),e.preventDefault()):(this._mouseDistanceMet(e)&&this._mouseDelayMet(e)&&(this._mouseStarted=this._mouseStart(this._mouseDownEvent,e)!==!1,this._mouseStarted?this._mouseDrag(e):this._mouseUp(e)),!this._mouseStarted)},_mouseUp:function(e){this.document.off("mousemove."+this.widgetName,this._mouseMoveDelegate).off("mouseup."+this.widgetName,this._mouseUpDelegate),this._mouseStarted&&(this._mouseStarted=!1,e.target===this._mouseDownEvent.target&&t.data(e.target,this.widgetName+".preventClickEvent",!0),this._mouseStop(e)),this._mouseDelayTimer&&(clearTimeout(this._mouseDelayTimer),delete this._mouseDelayTimer),this.ignoreMissingWhich=!1,u=!1,e.preventDefault()},_mouseDistanceMet:function(t){return Math.max(Math.abs(this._mouseDownEvent.pageX-t.pageX),Math.abs(this._mouseDownEvent.pageY-t.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return!0}}),t.ui.plugin={add:function(e,i,s){var n,a=t.ui[e].prototype;for(n in s)a.plugins[n]=a.plugins[n]||[],a.plugins[n].push([i,s[n]])},call:function(t,e,i,s){var n,a=t.plugins[e];if(a&&(s||t.element[0].parentNode&&11!==t.element[0].parentNode.nodeType))for(n=0;a.length>n;n++)t.options[a[n][0]]&&a[n][1].apply(t.element,i)}},t.ui.safeActiveElement=function(t){var e;try{e=t.activeElement}catch(i){e=t.body}return e||(e=t.body),e.nodeName||(e=t.body),e},t.ui.safeBlur=function(e){e&&"body"!==e.nodeName.toLowerCase()&&t(e).trigger("blur")},t.widget("ui.draggable",t.ui.mouse,{version:"1.12.1",widgetEventPrefix:"drag",options:{addClasses:!0,appendTo:"parent",axis:!1,connectToSortable:!1,containment:!1,cursor:"auto",cursorAt:!1,grid:!1,handle:!1,helper:"original",iframeFix:!1,opacity:!1,refreshPositions:!1,revert:!1,revertDuration:500,scope:"default",scroll:!0,scrollSensitivity:20,scrollSpeed:20,snap:!1,snapMode:"both",snapTolerance:20,stack:!1,zIndex:!1,drag:null,start:null,stop:null},_create:function(){"original"===this.options.helper&&this._setPositionRelative(),this.options.addClasses&&this._addClass("ui-draggable"),this._setHandleClassName(),this._mouseInit()},_setOption:function(t,e){this._super(t,e),"handle"===t&&(this._removeHandleClassName(),this._setHandleClassName())},_destroy:function(){return(this.helper||this.element).is(".ui-draggable-dragging")?(this.destroyOnClear=!0,void 0):(this._removeHandleClassName(),this._mouseDestroy(),void 0)},_mouseCapture:function(e){var i=this.options;return this.helper||i.disabled||t(e.target).closest(".ui-resizable-handle").length>0?!1:(this.handle=this._getHandle(e),this.handle?(this._blurActiveElement(e),this._blockFrames(i.iframeFix===!0?"iframe":i.iframeFix),!0):!1)},_blockFrames:function(e){this.iframeBlocks=this.document.find(e).map(function(){var e=t(this);return t("<div>").css("position","absolute").appendTo(e.parent()).outerWidth(e.outerWidth()).outerHeight(e.outerHeight()).offset(e.offset())[0]})},_unblockFrames:function(){this.iframeBlocks&&(this.iframeBlocks.remove(),delete this.iframeBlocks)},_blurActiveElement:function(e){var i=t.ui.safeActiveElement(this.document[0]),s=t(e.target);s.closest(i).length||t.ui.safeBlur(i)},_mouseStart:function(e){var i=this.options;return this.helper=this._createHelper(e),this._addClass(this.helper,"ui-draggable-dragging"),this._cacheHelperProportions(),t.ui.ddmanager&&(t.ui.ddmanager.current=this),this._cacheMargins(),this.cssPosition=this.helper.css("position"),this.scrollParent=this.helper.scrollParent(!0),this.offsetParent=this.helper.offsetParent(),this.hasFixedAncestor=this.helper.parents().filter(function(){return"fixed"===t(this).css("position")}).length>0,this.positionAbs=this.element.offset(),this._refreshOffsets(e),this.originalPosition=this.position=this._generatePosition(e,!1),this.originalPageX=e.pageX,this.originalPageY=e.pageY,i.cursorAt&&this._adjustOffsetFromHelper(i.cursorAt),this._setContainment(),this._trigger("start",e)===!1?(this._clear(),!1):(this._cacheHelperProportions(),t.ui.ddmanager&&!i.dropBehaviour&&t.ui.ddmanager.prepareOffsets(this,e),this._mouseDrag(e,!0),t.ui.ddmanager&&t.ui.ddmanager.dragStart(this,e),!0)},_refreshOffsets:function(t){this.offset={top:this.positionAbs.top-this.margins.top,left:this.positionAbs.left-this.margins.left,scroll:!1,parent:this._getParentOffset(),relative:this._getRelativeOffset()},this.offset.click={left:t.pageX-this.offset.left,top:t.pageY-this.offset.top}},_mouseDrag:function(e,i){if(this.hasFixedAncestor&&(this.offset.parent=this._getParentOffset()),this.position=this._generatePosition(e,!0),this.positionAbs=this._convertPositionTo("absolute"),!i){var s=this._uiHash();if(this._trigger("drag",e,s)===!1)return this._mouseUp(new t.Event("mouseup",e)),!1;this.position=s.position}return this.helper[0].style.left=this.position.left+"px",this.helper[0].style.top=this.position.top+"px",t.ui.ddmanager&&t.ui.ddmanager.drag(this,e),!1},_mouseStop:function(e){var i=this,s=!1;return t.ui.ddmanager&&!this.options.dropBehaviour&&(s=t.ui.ddmanager.drop(this,e)),this.dropped&&(s=this.dropped,this.dropped=!1),"invalid"===this.options.revert&&!s||"valid"===this.options.revert&&s||this.options.revert===!0||t.isFunction(this.options.revert)&&this.options.revert.call(this.element,s)?t(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){i._trigger("stop",e)!==!1&&i._clear()}):this._trigger("stop",e)!==!1&&this._clear(),!1},_mouseUp:function(e){return this._unblockFrames(),t.ui.ddmanager&&t.ui.ddmanager.dragStop(this,e),this.handleElement.is(e.target)&&this.element.trigger("focus"),t.ui.mouse.prototype._mouseUp.call(this,e)},cancel:function(){return this.helper.is(".ui-draggable-dragging")?this._mouseUp(new t.Event("mouseup",{target:this.element[0]})):this._clear(),this},_getHandle:function(e){return this.options.handle?!!t(e.target).closest(this.element.find(this.options.handle)).length:!0},_setHandleClassName:function(){this.handleElement=this.options.handle?this.element.find(this.options.handle):this.element,this._addClass(this.handleElement,"ui-draggable-handle")},_removeHandleClassName:function(){this._removeClass(this.handleElement,"ui-draggable-handle")},_createHelper:function(e){var i=this.options,s=t.isFunction(i.helper),n=s?t(i.helper.apply(this.element[0],[e])):"clone"===i.helper?this.element.clone().removeAttr("id"):this.element;return n.parents("body").length||n.appendTo("parent"===i.appendTo?this.element[0].parentNode:i.appendTo),s&&n[0]===this.element[0]&&this._setPositionRelative(),n[0]===this.element[0]||/(fixed|absolute)/.test(n.css("position"))||n.css("position","absolute"),n},_setPositionRelative:function(){/^(?:r|a|f)/.test(this.element.css("position"))||(this.element[0].style.position="relative")},_adjustOffsetFromHelper:function(e){"string"==typeof e&&(e=e.split(" ")),t.isArray(e)&&(e={left:+e[0],top:+e[1]||0}),"left"in e&&(this.offset.click.left=e.left+this.margins.left),"right"in e&&(this.offset.click.left=this.helperProportions.width-e.right+this.margins.left),"top"in e&&(this.offset.click.top=e.top+this.margins.top),"bottom"in e&&(this.offset.click.top=this.helperProportions.height-e.bottom+this.margins.top)},_isRootNode:function(t){return/(html|body)/i.test(t.tagName)||t===this.document[0]},_getParentOffset:function(){var e=this.offsetParent.offset(),i=this.document[0];return"absolute"===this.cssPosition&&this.scrollParent[0]!==i&&t.contains(this.scrollParent[0],this.offsetParent[0])&&(e.left+=this.scrollParent.scrollLeft(),e.top+=this.scrollParent.scrollTop()),this._isRootNode(this.offsetParent[0])&&(e={top:0,left:0}),{top:e.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:e.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"!==this.cssPosition)return{top:0,left:0};var t=this.element.position(),e=this._isRootNode(this.scrollParent[0]);return{top:t.top-(parseInt(this.helper.css("top"),10)||0)+(e?0:this.scrollParent.scrollTop()),left:t.left-(parseInt(this.helper.css("left"),10)||0)+(e?0:this.scrollParent.scrollLeft())}},_cacheMargins:function(){this.margins={left:parseInt(this.element.css("marginLeft"),10)||0,top:parseInt(this.element.css("marginTop"),10)||0,right:parseInt(this.element.css("marginRight"),10)||0,bottom:parseInt(this.element.css("marginBottom"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var e,i,s,n=this.options,a=this.document[0];return this.relativeContainer=null,n.containment?"window"===n.containment?(this.containment=[t(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,t(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,t(window).scrollLeft()+t(window).width()-this.helperProportions.width-this.margins.left,t(window).scrollTop()+(t(window).height()||a.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top],void 0):"document"===n.containment?(this.containment=[0,0,t(a).width()-this.helperProportions.width-this.margins.left,(t(a).height()||a.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top],void 0):n.containment.constructor===Array?(this.containment=n.containment,void 0):("parent"===n.containment&&(n.containment=this.helper[0].parentNode),i=t(n.containment),s=i[0],s&&(e=/(scroll|auto)/.test(i.css("overflow")),this.containment=[(parseInt(i.css("borderLeftWidth"),10)||0)+(parseInt(i.css("paddingLeft"),10)||0),(parseInt(i.css("borderTopWidth"),10)||0)+(parseInt(i.css("paddingTop"),10)||0),(e?Math.max(s.scrollWidth,s.offsetWidth):s.offsetWidth)-(parseInt(i.css("borderRightWidth"),10)||0)-(parseInt(i.css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(e?Math.max(s.scrollHeight,s.offsetHeight):s.offsetHeight)-(parseInt(i.css("borderBottomWidth"),10)||0)-(parseInt(i.css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom],this.relativeContainer=i),void 0):(this.containment=null,void 0) },_convertPositionTo:function(t,e){e||(e=this.position);var i="absolute"===t?1:-1,s=this._isRootNode(this.scrollParent[0]);return{top:e.top+this.offset.relative.top*i+this.offset.parent.top*i-("fixed"===this.cssPosition?-this.offset.scroll.top:s?0:this.offset.scroll.top)*i,left:e.left+this.offset.relative.left*i+this.offset.parent.left*i-("fixed"===this.cssPosition?-this.offset.scroll.left:s?0:this.offset.scroll.left)*i}},_generatePosition:function(t,e){var i,s,n,a,o=this.options,r=this._isRootNode(this.scrollParent[0]),h=t.pageX,l=t.pageY;return r&&this.offset.scroll||(this.offset.scroll={top:this.scrollParent.scrollTop(),left:this.scrollParent.scrollLeft()}),e&&(this.containment&&(this.relativeContainer?(s=this.relativeContainer.offset(),i=[this.containment[0]+s.left,this.containment[1]+s.top,this.containment[2]+s.left,this.containment[3]+s.top]):i=this.containment,t.pageX-this.offset.click.left<i[0]&&(h=i[0]+this.offset.click.left),t.pageY-this.offset.click.top<i[1]&&(l=i[1]+this.offset.click.top),t.pageX-this.offset.click.left>i[2]&&(h=i[2]+this.offset.click.left),t.pageY-this.offset.click.top>i[3]&&(l=i[3]+this.offset.click.top)),o.grid&&(n=o.grid[1]?this.originalPageY+Math.round((l-this.originalPageY)/o.grid[1])*o.grid[1]:this.originalPageY,l=i?n-this.offset.click.top>=i[1]||n-this.offset.click.top>i[3]?n:n-this.offset.click.top>=i[1]?n-o.grid[1]:n+o.grid[1]:n,a=o.grid[0]?this.originalPageX+Math.round((h-this.originalPageX)/o.grid[0])*o.grid[0]:this.originalPageX,h=i?a-this.offset.click.left>=i[0]||a-this.offset.click.left>i[2]?a:a-this.offset.click.left>=i[0]?a-o.grid[0]:a+o.grid[0]:a),"y"===o.axis&&(h=this.originalPageX),"x"===o.axis&&(l=this.originalPageY)),{top:l-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.offset.scroll.top:r?0:this.offset.scroll.top),left:h-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.offset.scroll.left:r?0:this.offset.scroll.left)}},_clear:function(){this._removeClass(this.helper,"ui-draggable-dragging"),this.helper[0]===this.element[0]||this.cancelHelperRemoval||this.helper.remove(),this.helper=null,this.cancelHelperRemoval=!1,this.destroyOnClear&&this.destroy()},_trigger:function(e,i,s){return s=s||this._uiHash(),t.ui.plugin.call(this,e,[i,s,this],!0),/^(drag|start|stop)/.test(e)&&(this.positionAbs=this._convertPositionTo("absolute"),s.offset=this.positionAbs),t.Widget.prototype._trigger.call(this,e,i,s)},plugins:{},_uiHash:function(){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}}),t.ui.plugin.add("draggable","connectToSortable",{start:function(e,i,s){var n=t.extend({},i,{item:s.element});s.sortables=[],t(s.options.connectToSortable).each(function(){var i=t(this).sortable("instance");i&&!i.options.disabled&&(s.sortables.push(i),i.refreshPositions(),i._trigger("activate",e,n))})},stop:function(e,i,s){var n=t.extend({},i,{item:s.element});s.cancelHelperRemoval=!1,t.each(s.sortables,function(){var t=this;t.isOver?(t.isOver=0,s.cancelHelperRemoval=!0,t.cancelHelperRemoval=!1,t._storedCSS={position:t.placeholder.css("position"),top:t.placeholder.css("top"),left:t.placeholder.css("left")},t._mouseStop(e),t.options.helper=t.options._helper):(t.cancelHelperRemoval=!0,t._trigger("deactivate",e,n))})},drag:function(e,i,s){t.each(s.sortables,function(){var n=!1,a=this;a.positionAbs=s.positionAbs,a.helperProportions=s.helperProportions,a.offset.click=s.offset.click,a._intersectsWith(a.containerCache)&&(n=!0,t.each(s.sortables,function(){return this.positionAbs=s.positionAbs,this.helperProportions=s.helperProportions,this.offset.click=s.offset.click,this!==a&&this._intersectsWith(this.containerCache)&&t.contains(a.element[0],this.element[0])&&(n=!1),n})),n?(a.isOver||(a.isOver=1,s._parent=i.helper.parent(),a.currentItem=i.helper.appendTo(a.element).data("ui-sortable-item",!0),a.options._helper=a.options.helper,a.options.helper=function(){return i.helper[0]},e.target=a.currentItem[0],a._mouseCapture(e,!0),a._mouseStart(e,!0,!0),a.offset.click.top=s.offset.click.top,a.offset.click.left=s.offset.click.left,a.offset.parent.left-=s.offset.parent.left-a.offset.parent.left,a.offset.parent.top-=s.offset.parent.top-a.offset.parent.top,s._trigger("toSortable",e),s.dropped=a.element,t.each(s.sortables,function(){this.refreshPositions()}),s.currentItem=s.element,a.fromOutside=s),a.currentItem&&(a._mouseDrag(e),i.position=a.position)):a.isOver&&(a.isOver=0,a.cancelHelperRemoval=!0,a.options._revert=a.options.revert,a.options.revert=!1,a._trigger("out",e,a._uiHash(a)),a._mouseStop(e,!0),a.options.revert=a.options._revert,a.options.helper=a.options._helper,a.placeholder&&a.placeholder.remove(),i.helper.appendTo(s._parent),s._refreshOffsets(e),i.position=s._generatePosition(e,!0),s._trigger("fromSortable",e),s.dropped=!1,t.each(s.sortables,function(){this.refreshPositions()}))})}}),t.ui.plugin.add("draggable","cursor",{start:function(e,i,s){var n=t("body"),a=s.options;n.css("cursor")&&(a._cursor=n.css("cursor")),n.css("cursor",a.cursor)},stop:function(e,i,s){var n=s.options;n._cursor&&t("body").css("cursor",n._cursor)}}),t.ui.plugin.add("draggable","opacity",{start:function(e,i,s){var n=t(i.helper),a=s.options;n.css("opacity")&&(a._opacity=n.css("opacity")),n.css("opacity",a.opacity)},stop:function(e,i,s){var n=s.options;n._opacity&&t(i.helper).css("opacity",n._opacity)}}),t.ui.plugin.add("draggable","scroll",{start:function(t,e,i){i.scrollParentNotHidden||(i.scrollParentNotHidden=i.helper.scrollParent(!1)),i.scrollParentNotHidden[0]!==i.document[0]&&"HTML"!==i.scrollParentNotHidden[0].tagName&&(i.overflowOffset=i.scrollParentNotHidden.offset())},drag:function(e,i,s){var n=s.options,a=!1,o=s.scrollParentNotHidden[0],r=s.document[0];o!==r&&"HTML"!==o.tagName?(n.axis&&"x"===n.axis||(s.overflowOffset.top+o.offsetHeight-e.pageY<n.scrollSensitivity?o.scrollTop=a=o.scrollTop+n.scrollSpeed:e.pageY-s.overflowOffset.top<n.scrollSensitivity&&(o.scrollTop=a=o.scrollTop-n.scrollSpeed)),n.axis&&"y"===n.axis||(s.overflowOffset.left+o.offsetWidth-e.pageX<n.scrollSensitivity?o.scrollLeft=a=o.scrollLeft+n.scrollSpeed:e.pageX-s.overflowOffset.left<n.scrollSensitivity&&(o.scrollLeft=a=o.scrollLeft-n.scrollSpeed))):(n.axis&&"x"===n.axis||(e.pageY-t(r).scrollTop()<n.scrollSensitivity?a=t(r).scrollTop(t(r).scrollTop()-n.scrollSpeed):t(window).height()-(e.pageY-t(r).scrollTop())<n.scrollSensitivity&&(a=t(r).scrollTop(t(r).scrollTop()+n.scrollSpeed))),n.axis&&"y"===n.axis||(e.pageX-t(r).scrollLeft()<n.scrollSensitivity?a=t(r).scrollLeft(t(r).scrollLeft()-n.scrollSpeed):t(window).width()-(e.pageX-t(r).scrollLeft())<n.scrollSensitivity&&(a=t(r).scrollLeft(t(r).scrollLeft()+n.scrollSpeed)))),a!==!1&&t.ui.ddmanager&&!n.dropBehaviour&&t.ui.ddmanager.prepareOffsets(s,e)}}),t.ui.plugin.add("draggable","snap",{start:function(e,i,s){var n=s.options;s.snapElements=[],t(n.snap.constructor!==String?n.snap.items||":data(ui-draggable)":n.snap).each(function(){var e=t(this),i=e.offset();this!==s.element[0]&&s.snapElements.push({item:this,width:e.outerWidth(),height:e.outerHeight(),top:i.top,left:i.left})})},drag:function(e,i,s){var n,a,o,r,h,l,u,c,d,p,f=s.options,m=f.snapTolerance,g=i.offset.left,_=g+s.helperProportions.width,v=i.offset.top,b=v+s.helperProportions.height;for(d=s.snapElements.length-1;d>=0;d--)h=s.snapElements[d].left-s.margins.left,l=h+s.snapElements[d].width,u=s.snapElements[d].top-s.margins.top,c=u+s.snapElements[d].height,h-m>_||g>l+m||u-m>b||v>c+m||!t.contains(s.snapElements[d].item.ownerDocument,s.snapElements[d].item)?(s.snapElements[d].snapping&&s.options.snap.release&&s.options.snap.release.call(s.element,e,t.extend(s._uiHash(),{snapItem:s.snapElements[d].item})),s.snapElements[d].snapping=!1):("inner"!==f.snapMode&&(n=m>=Math.abs(u-b),a=m>=Math.abs(c-v),o=m>=Math.abs(h-_),r=m>=Math.abs(l-g),n&&(i.position.top=s._convertPositionTo("relative",{top:u-s.helperProportions.height,left:0}).top),a&&(i.position.top=s._convertPositionTo("relative",{top:c,left:0}).top),o&&(i.position.left=s._convertPositionTo("relative",{top:0,left:h-s.helperProportions.width}).left),r&&(i.position.left=s._convertPositionTo("relative",{top:0,left:l}).left)),p=n||a||o||r,"outer"!==f.snapMode&&(n=m>=Math.abs(u-v),a=m>=Math.abs(c-b),o=m>=Math.abs(h-g),r=m>=Math.abs(l-_),n&&(i.position.top=s._convertPositionTo("relative",{top:u,left:0}).top),a&&(i.position.top=s._convertPositionTo("relative",{top:c-s.helperProportions.height,left:0}).top),o&&(i.position.left=s._convertPositionTo("relative",{top:0,left:h}).left),r&&(i.position.left=s._convertPositionTo("relative",{top:0,left:l-s.helperProportions.width}).left)),!s.snapElements[d].snapping&&(n||a||o||r||p)&&s.options.snap.snap&&s.options.snap.snap.call(s.element,e,t.extend(s._uiHash(),{snapItem:s.snapElements[d].item})),s.snapElements[d].snapping=n||a||o||r||p)}}),t.ui.plugin.add("draggable","stack",{start:function(e,i,s){var n,a=s.options,o=t.makeArray(t(a.stack)).sort(function(e,i){return(parseInt(t(e).css("zIndex"),10)||0)-(parseInt(t(i).css("zIndex"),10)||0)});o.length&&(n=parseInt(t(o[0]).css("zIndex"),10)||0,t(o).each(function(e){t(this).css("zIndex",n+e)}),this.css("zIndex",n+o.length))}}),t.ui.plugin.add("draggable","zIndex",{start:function(e,i,s){var n=t(i.helper),a=s.options;n.css("zIndex")&&(a._zIndex=n.css("zIndex")),n.css("zIndex",a.zIndex)},stop:function(e,i,s){var n=s.options;n._zIndex&&t(i.helper).css("zIndex",n._zIndex)}}),t.ui.draggable,t.widget("ui.droppable",{version:"1.12.1",widgetEventPrefix:"drop",options:{accept:"*",addClasses:!0,greedy:!1,scope:"default",tolerance:"intersect",activate:null,deactivate:null,drop:null,out:null,over:null},_create:function(){var e,i=this.options,s=i.accept;this.isover=!1,this.isout=!0,this.accept=t.isFunction(s)?s:function(t){return t.is(s)},this.proportions=function(){return arguments.length?(e=arguments[0],void 0):e?e:e={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight}},this._addToManager(i.scope),i.addClasses&&this._addClass("ui-droppable")},_addToManager:function(e){t.ui.ddmanager.droppables[e]=t.ui.ddmanager.droppables[e]||[],t.ui.ddmanager.droppables[e].push(this)},_splice:function(t){for(var e=0;t.length>e;e++)t[e]===this&&t.splice(e,1)},_destroy:function(){var e=t.ui.ddmanager.droppables[this.options.scope];this._splice(e)},_setOption:function(e,i){if("accept"===e)this.accept=t.isFunction(i)?i:function(t){return t.is(i)};else if("scope"===e){var s=t.ui.ddmanager.droppables[this.options.scope];this._splice(s),this._addToManager(i)}this._super(e,i)},_activate:function(e){var i=t.ui.ddmanager.current;this._addActiveClass(),i&&this._trigger("activate",e,this.ui(i))},_deactivate:function(e){var i=t.ui.ddmanager.current;this._removeActiveClass(),i&&this._trigger("deactivate",e,this.ui(i))},_over:function(e){var i=t.ui.ddmanager.current;i&&(i.currentItem||i.element)[0]!==this.element[0]&&this.accept.call(this.element[0],i.currentItem||i.element)&&(this._addHoverClass(),this._trigger("over",e,this.ui(i)))},_out:function(e){var i=t.ui.ddmanager.current;i&&(i.currentItem||i.element)[0]!==this.element[0]&&this.accept.call(this.element[0],i.currentItem||i.element)&&(this._removeHoverClass(),this._trigger("out",e,this.ui(i)))},_drop:function(e,i){var s=i||t.ui.ddmanager.current,n=!1;return s&&(s.currentItem||s.element)[0]!==this.element[0]?(this.element.find(":data(ui-droppable)").not(".ui-draggable-dragging").each(function(){var i=t(this).droppable("instance");return i.options.greedy&&!i.options.disabled&&i.options.scope===s.options.scope&&i.accept.call(i.element[0],s.currentItem||s.element)&&c(s,t.extend(i,{offset:i.element.offset()}),i.options.tolerance,e)?(n=!0,!1):void 0}),n?!1:this.accept.call(this.element[0],s.currentItem||s.element)?(this._removeActiveClass(),this._removeHoverClass(),this._trigger("drop",e,this.ui(s)),this.element):!1):!1},ui:function(t){return{draggable:t.currentItem||t.element,helper:t.helper,position:t.position,offset:t.positionAbs}},_addHoverClass:function(){this._addClass("ui-droppable-hover")},_removeHoverClass:function(){this._removeClass("ui-droppable-hover")},_addActiveClass:function(){this._addClass("ui-droppable-active")},_removeActiveClass:function(){this._removeClass("ui-droppable-active")}});var c=t.ui.intersect=function(){function t(t,e,i){return t>=e&&e+i>t}return function(e,i,s,n){if(!i.offset)return!1;var a=(e.positionAbs||e.position.absolute).left+e.margins.left,o=(e.positionAbs||e.position.absolute).top+e.margins.top,r=a+e.helperProportions.width,h=o+e.helperProportions.height,l=i.offset.left,u=i.offset.top,c=l+i.proportions().width,d=u+i.proportions().height;switch(s){case"fit":return a>=l&&c>=r&&o>=u&&d>=h;case"intersect":return a+e.helperProportions.width/2>l&&c>r-e.helperProportions.width/2&&o+e.helperProportions.height/2>u&&d>h-e.helperProportions.height/2;case"pointer":return t(n.pageY,u,i.proportions().height)&&t(n.pageX,l,i.proportions().width);case"touch":return(o>=u&&d>=o||h>=u&&d>=h||u>o&&h>d)&&(a>=l&&c>=a||r>=l&&c>=r||l>a&&r>c);default:return!1}}}();t.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function(e,i){var s,n,a=t.ui.ddmanager.droppables[e.options.scope]||[],o=i?i.type:null,r=(e.currentItem||e.element).find(":data(ui-droppable)").addBack();t:for(s=0;a.length>s;s++)if(!(a[s].options.disabled||e&&!a[s].accept.call(a[s].element[0],e.currentItem||e.element))){for(n=0;r.length>n;n++)if(r[n]===a[s].element[0]){a[s].proportions().height=0;continue t}a[s].visible="none"!==a[s].element.css("display"),a[s].visible&&("mousedown"===o&&a[s]._activate.call(a[s],i),a[s].offset=a[s].element.offset(),a[s].proportions({width:a[s].element[0].offsetWidth,height:a[s].element[0].offsetHeight}))}},drop:function(e,i){var s=!1;return t.each((t.ui.ddmanager.droppables[e.options.scope]||[]).slice(),function(){this.options&&(!this.options.disabled&&this.visible&&c(e,this,this.options.tolerance,i)&&(s=this._drop.call(this,i)||s),!this.options.disabled&&this.visible&&this.accept.call(this.element[0],e.currentItem||e.element)&&(this.isout=!0,this.isover=!1,this._deactivate.call(this,i)))}),s},dragStart:function(e,i){e.element.parentsUntil("body").on("scroll.droppable",function(){e.options.refreshPositions||t.ui.ddmanager.prepareOffsets(e,i)})},drag:function(e,i){e.options.refreshPositions&&t.ui.ddmanager.prepareOffsets(e,i),t.each(t.ui.ddmanager.droppables[e.options.scope]||[],function(){if(!this.options.disabled&&!this.greedyChild&&this.visible){var s,n,a,o=c(e,this,this.options.tolerance,i),r=!o&&this.isover?"isout":o&&!this.isover?"isover":null;r&&(this.options.greedy&&(n=this.options.scope,a=this.element.parents(":data(ui-droppable)").filter(function(){return t(this).droppable("instance").options.scope===n}),a.length&&(s=t(a[0]).droppable("instance"),s.greedyChild="isover"===r)),s&&"isover"===r&&(s.isover=!1,s.isout=!0,s._out.call(s,i)),this[r]=!0,this["isout"===r?"isover":"isout"]=!1,this["isover"===r?"_over":"_out"].call(this,i),s&&"isout"===r&&(s.isout=!1,s.isover=!0,s._over.call(s,i)))}})},dragStop:function(e,i){e.element.parentsUntil("body").off("scroll.droppable"),e.options.refreshPositions||t.ui.ddmanager.prepareOffsets(e,i)}},t.uiBackCompat!==!1&&t.widget("ui.droppable",t.ui.droppable,{options:{hoverClass:!1,activeClass:!1},_addActiveClass:function(){this._super(),this.options.activeClass&&this.element.addClass(this.options.activeClass)},_removeActiveClass:function(){this._super(),this.options.activeClass&&this.element.removeClass(this.options.activeClass)},_addHoverClass:function(){this._super(),this.options.hoverClass&&this.element.addClass(this.options.hoverClass)},_removeHoverClass:function(){this._super(),this.options.hoverClass&&this.element.removeClass(this.options.hoverClass)}}),t.ui.droppable,t.widget("ui.resizable",t.ui.mouse,{version:"1.12.1",widgetEventPrefix:"resize",options:{alsoResize:!1,animate:!1,animateDuration:"slow",animateEasing:"swing",aspectRatio:!1,autoHide:!1,classes:{"ui-resizable-se":"ui-icon ui-icon-gripsmall-diagonal-se"},containment:!1,ghost:!1,grid:!1,handles:"e,s,se",helper:!1,maxHeight:null,maxWidth:null,minHeight:10,minWidth:10,zIndex:90,resize:null,start:null,stop:null},_num:function(t){return parseFloat(t)||0},_isNumber:function(t){return!isNaN(parseFloat(t))},_hasScroll:function(e,i){if("hidden"===t(e).css("overflow"))return!1;var s=i&&"left"===i?"scrollLeft":"scrollTop",n=!1;return e[s]>0?!0:(e[s]=1,n=e[s]>0,e[s]=0,n)},_create:function(){var e,i=this.options,s=this;this._addClass("ui-resizable"),t.extend(this,{_aspectRatio:!!i.aspectRatio,aspectRatio:i.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:i.helper||i.ghost||i.animate?i.helper||"ui-resizable-helper":null}),this.element[0].nodeName.match(/^(canvas|textarea|input|select|button|img)$/i)&&(this.element.wrap(t("<div class='ui-wrapper' style='overflow: hidden;'></div>").css({position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.outerHeight(),top:this.element.css("top"),left:this.element.css("left")})),this.element=this.element.parent().data("ui-resizable",this.element.resizable("instance")),this.elementIsWrapper=!0,e={marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom"),marginLeft:this.originalElement.css("marginLeft")},this.element.css(e),this.originalElement.css("margin",0),this.originalResizeStyle=this.originalElement.css("resize"),this.originalElement.css("resize","none"),this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"})),this.originalElement.css(e),this._proportionallyResize()),this._setupHandles(),i.autoHide&&t(this.element).on("mouseenter",function(){i.disabled||(s._removeClass("ui-resizable-autohide"),s._handles.show())}).on("mouseleave",function(){i.disabled||s.resizing||(s._addClass("ui-resizable-autohide"),s._handles.hide())}),this._mouseInit()},_destroy:function(){this._mouseDestroy();var e,i=function(e){t(e).removeData("resizable").removeData("ui-resizable").off(".resizable").find(".ui-resizable-handle").remove()};return this.elementIsWrapper&&(i(this.element),e=this.element,this.originalElement.css({position:e.css("position"),width:e.outerWidth(),height:e.outerHeight(),top:e.css("top"),left:e.css("left")}).insertAfter(e),e.remove()),this.originalElement.css("resize",this.originalResizeStyle),i(this.originalElement),this},_setOption:function(t,e){switch(this._super(t,e),t){case"handles":this._removeHandles(),this._setupHandles();break;default:}},_setupHandles:function(){var e,i,s,n,a,o=this.options,r=this;if(this.handles=o.handles||(t(".ui-resizable-handle",this.element).length?{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw",ne:".ui-resizable-ne",nw:".ui-resizable-nw"}:"e,s,se"),this._handles=t(),this.handles.constructor===String)for("all"===this.handles&&(this.handles="n,e,s,w,se,sw,ne,nw"),s=this.handles.split(","),this.handles={},i=0;s.length>i;i++)e=t.trim(s[i]),n="ui-resizable-"+e,a=t("<div>"),this._addClass(a,"ui-resizable-handle "+n),a.css({zIndex:o.zIndex}),this.handles[e]=".ui-resizable-"+e,this.element.append(a);this._renderAxis=function(e){var i,s,n,a;e=e||this.element;for(i in this.handles)this.handles[i].constructor===String?this.handles[i]=this.element.children(this.handles[i]).first().show():(this.handles[i].jquery||this.handles[i].nodeType)&&(this.handles[i]=t(this.handles[i]),this._on(this.handles[i],{mousedown:r._mouseDown})),this.elementIsWrapper&&this.originalElement[0].nodeName.match(/^(textarea|input|select|button)$/i)&&(s=t(this.handles[i],this.element),a=/sw|ne|nw|se|n|s/.test(i)?s.outerHeight():s.outerWidth(),n=["padding",/ne|nw|n/.test(i)?"Top":/se|sw|s/.test(i)?"Bottom":/^e$/.test(i)?"Right":"Left"].join(""),e.css(n,a),this._proportionallyResize()),this._handles=this._handles.add(this.handles[i])},this._renderAxis(this.element),this._handles=this._handles.add(this.element.find(".ui-resizable-handle")),this._handles.disableSelection(),this._handles.on("mouseover",function(){r.resizing||(this.className&&(a=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i)),r.axis=a&&a[1]?a[1]:"se")}),o.autoHide&&(this._handles.hide(),this._addClass("ui-resizable-autohide"))},_removeHandles:function(){this._handles.remove()},_mouseCapture:function(e){var i,s,n=!1;for(i in this.handles)s=t(this.handles[i])[0],(s===e.target||t.contains(s,e.target))&&(n=!0);return!this.options.disabled&&n},_mouseStart:function(e){var i,s,n,a=this.options,o=this.element;return this.resizing=!0,this._renderProxy(),i=this._num(this.helper.css("left")),s=this._num(this.helper.css("top")),a.containment&&(i+=t(a.containment).scrollLeft()||0,s+=t(a.containment).scrollTop()||0),this.offset=this.helper.offset(),this.position={left:i,top:s},this.size=this._helper?{width:this.helper.width(),height:this.helper.height()}:{width:o.width(),height:o.height()},this.originalSize=this._helper?{width:o.outerWidth(),height:o.outerHeight()}:{width:o.width(),height:o.height()},this.sizeDiff={width:o.outerWidth()-o.width(),height:o.outerHeight()-o.height()},this.originalPosition={left:i,top:s},this.originalMousePosition={left:e.pageX,top:e.pageY},this.aspectRatio="number"==typeof a.aspectRatio?a.aspectRatio:this.originalSize.width/this.originalSize.height||1,n=t(".ui-resizable-"+this.axis).css("cursor"),t("body").css("cursor","auto"===n?this.axis+"-resize":n),this._addClass("ui-resizable-resizing"),this._propagate("start",e),!0},_mouseDrag:function(e){var i,s,n=this.originalMousePosition,a=this.axis,o=e.pageX-n.left||0,r=e.pageY-n.top||0,h=this._change[a];return this._updatePrevProperties(),h?(i=h.apply(this,[e,o,r]),this._updateVirtualBoundaries(e.shiftKey),(this._aspectRatio||e.shiftKey)&&(i=this._updateRatio(i,e)),i=this._respectSize(i,e),this._updateCache(i),this._propagate("resize",e),s=this._applyChanges(),!this._helper&&this._proportionallyResizeElements.length&&this._proportionallyResize(),t.isEmptyObject(s)||(this._updatePrevProperties(),this._trigger("resize",e,this.ui()),this._applyChanges()),!1):!1},_mouseStop:function(e){this.resizing=!1;var i,s,n,a,o,r,h,l=this.options,u=this;return this._helper&&(i=this._proportionallyResizeElements,s=i.length&&/textarea/i.test(i[0].nodeName),n=s&&this._hasScroll(i[0],"left")?0:u.sizeDiff.height,a=s?0:u.sizeDiff.width,o={width:u.helper.width()-a,height:u.helper.height()-n},r=parseFloat(u.element.css("left"))+(u.position.left-u.originalPosition.left)||null,h=parseFloat(u.element.css("top"))+(u.position.top-u.originalPosition.top)||null,l.animate||this.element.css(t.extend(o,{top:h,left:r})),u.helper.height(u.size.height),u.helper.width(u.size.width),this._helper&&!l.animate&&this._proportionallyResize()),t("body").css("cursor","auto"),this._removeClass("ui-resizable-resizing"),this._propagate("stop",e),this._helper&&this.helper.remove(),!1},_updatePrevProperties:function(){this.prevPosition={top:this.position.top,left:this.position.left},this.prevSize={width:this.size.width,height:this.size.height}},_applyChanges:function(){var t={};return this.position.top!==this.prevPosition.top&&(t.top=this.position.top+"px"),this.position.left!==this.prevPosition.left&&(t.left=this.position.left+"px"),this.size.width!==this.prevSize.width&&(t.width=this.size.width+"px"),this.size.height!==this.prevSize.height&&(t.height=this.size.height+"px"),this.helper.css(t),t},_updateVirtualBoundaries:function(t){var e,i,s,n,a,o=this.options;a={minWidth:this._isNumber(o.minWidth)?o.minWidth:0,maxWidth:this._isNumber(o.maxWidth)?o.maxWidth:1/0,minHeight:this._isNumber(o.minHeight)?o.minHeight:0,maxHeight:this._isNumber(o.maxHeight)?o.maxHeight:1/0},(this._aspectRatio||t)&&(e=a.minHeight*this.aspectRatio,s=a.minWidth/this.aspectRatio,i=a.maxHeight*this.aspectRatio,n=a.maxWidth/this.aspectRatio,e>a.minWidth&&(a.minWidth=e),s>a.minHeight&&(a.minHeight=s),a.maxWidth>i&&(a.maxWidth=i),a.maxHeight>n&&(a.maxHeight=n)),this._vBoundaries=a},_updateCache:function(t){this.offset=this.helper.offset(),this._isNumber(t.left)&&(this.position.left=t.left),this._isNumber(t.top)&&(this.position.top=t.top),this._isNumber(t.height)&&(this.size.height=t.height),this._isNumber(t.width)&&(this.size.width=t.width)},_updateRatio:function(t){var e=this.position,i=this.size,s=this.axis;return this._isNumber(t.height)?t.width=t.height*this.aspectRatio:this._isNumber(t.width)&&(t.height=t.width/this.aspectRatio),"sw"===s&&(t.left=e.left+(i.width-t.width),t.top=null),"nw"===s&&(t.top=e.top+(i.height-t.height),t.left=e.left+(i.width-t.width)),t},_respectSize:function(t){var e=this._vBoundaries,i=this.axis,s=this._isNumber(t.width)&&e.maxWidth&&e.maxWidth<t.width,n=this._isNumber(t.height)&&e.maxHeight&&e.maxHeight<t.height,a=this._isNumber(t.width)&&e.minWidth&&e.minWidth>t.width,o=this._isNumber(t.height)&&e.minHeight&&e.minHeight>t.height,r=this.originalPosition.left+this.originalSize.width,h=this.originalPosition.top+this.originalSize.height,l=/sw|nw|w/.test(i),u=/nw|ne|n/.test(i);return a&&(t.width=e.minWidth),o&&(t.height=e.minHeight),s&&(t.width=e.maxWidth),n&&(t.height=e.maxHeight),a&&l&&(t.left=r-e.minWidth),s&&l&&(t.left=r-e.maxWidth),o&&u&&(t.top=h-e.minHeight),n&&u&&(t.top=h-e.maxHeight),t.width||t.height||t.left||!t.top?t.width||t.height||t.top||!t.left||(t.left=null):t.top=null,t},_getPaddingPlusBorderDimensions:function(t){for(var e=0,i=[],s=[t.css("borderTopWidth"),t.css("borderRightWidth"),t.css("borderBottomWidth"),t.css("borderLeftWidth")],n=[t.css("paddingTop"),t.css("paddingRight"),t.css("paddingBottom"),t.css("paddingLeft")];4>e;e++)i[e]=parseFloat(s[e])||0,i[e]+=parseFloat(n[e])||0;return{height:i[0]+i[2],width:i[1]+i[3]}},_proportionallyResize:function(){if(this._proportionallyResizeElements.length)for(var t,e=0,i=this.helper||this.element;this._proportionallyResizeElements.length>e;e++)t=this._proportionallyResizeElements[e],this.outerDimensions||(this.outerDimensions=this._getPaddingPlusBorderDimensions(t)),t.css({height:i.height()-this.outerDimensions.height||0,width:i.width()-this.outerDimensions.width||0})},_renderProxy:function(){var e=this.element,i=this.options;this.elementOffset=e.offset(),this._helper?(this.helper=this.helper||t("<div style='overflow:hidden;'></div>"),this._addClass(this.helper,this._helper),this.helper.css({width:this.element.outerWidth(),height:this.element.outerHeight(),position:"absolute",left:this.elementOffset.left+"px",top:this.elementOffset.top+"px",zIndex:++i.zIndex}),this.helper.appendTo("body").disableSelection()):this.helper=this.element},_change:{e:function(t,e){return{width:this.originalSize.width+e}},w:function(t,e){var i=this.originalSize,s=this.originalPosition;return{left:s.left+e,width:i.width-e}},n:function(t,e,i){var s=this.originalSize,n=this.originalPosition;return{top:n.top+i,height:s.height-i}},s:function(t,e,i){return{height:this.originalSize.height+i}},se:function(e,i,s){return t.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[e,i,s]))},sw:function(e,i,s){return t.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[e,i,s]))},ne:function(e,i,s){return t.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[e,i,s]))},nw:function(e,i,s){return t.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[e,i,s]))}},_propagate:function(e,i){t.ui.plugin.call(this,e,[i,this.ui()]),"resize"!==e&&this._trigger(e,i,this.ui())},plugins:{},ui:function(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition}}}),t.ui.plugin.add("resizable","animate",{stop:function(e){var i=t(this).resizable("instance"),s=i.options,n=i._proportionallyResizeElements,a=n.length&&/textarea/i.test(n[0].nodeName),o=a&&i._hasScroll(n[0],"left")?0:i.sizeDiff.height,r=a?0:i.sizeDiff.width,h={width:i.size.width-r,height:i.size.height-o},l=parseFloat(i.element.css("left"))+(i.position.left-i.originalPosition.left)||null,u=parseFloat(i.element.css("top"))+(i.position.top-i.originalPosition.top)||null;i.element.animate(t.extend(h,u&&l?{top:u,left:l}:{}),{duration:s.animateDuration,easing:s.animateEasing,step:function(){var s={width:parseFloat(i.element.css("width")),height:parseFloat(i.element.css("height")),top:parseFloat(i.element.css("top")),left:parseFloat(i.element.css("left"))};n&&n.length&&t(n[0]).css({width:s.width,height:s.height}),i._updateCache(s),i._propagate("resize",e)}})}}),t.ui.plugin.add("resizable","containment",{start:function(){var e,i,s,n,a,o,r,h=t(this).resizable("instance"),l=h.options,u=h.element,c=l.containment,d=c instanceof t?c.get(0):/parent/.test(c)?u.parent().get(0):c;d&&(h.containerElement=t(d),/document/.test(c)||c===document?(h.containerOffset={left:0,top:0},h.containerPosition={left:0,top:0},h.parentData={element:t(document),left:0,top:0,width:t(document).width(),height:t(document).height()||document.body.parentNode.scrollHeight}):(e=t(d),i=[],t(["Top","Right","Left","Bottom"]).each(function(t,s){i[t]=h._num(e.css("padding"+s))}),h.containerOffset=e.offset(),h.containerPosition=e.position(),h.containerSize={height:e.innerHeight()-i[3],width:e.innerWidth()-i[1]},s=h.containerOffset,n=h.containerSize.height,a=h.containerSize.width,o=h._hasScroll(d,"left")?d.scrollWidth:a,r=h._hasScroll(d)?d.scrollHeight:n,h.parentData={element:d,left:s.left,top:s.top,width:o,height:r}))},resize:function(e){var i,s,n,a,o=t(this).resizable("instance"),r=o.options,h=o.containerOffset,l=o.position,u=o._aspectRatio||e.shiftKey,c={top:0,left:0},d=o.containerElement,p=!0;d[0]!==document&&/static/.test(d.css("position"))&&(c=h),l.left<(o._helper?h.left:0)&&(o.size.width=o.size.width+(o._helper?o.position.left-h.left:o.position.left-c.left),u&&(o.size.height=o.size.width/o.aspectRatio,p=!1),o.position.left=r.helper?h.left:0),l.top<(o._helper?h.top:0)&&(o.size.height=o.size.height+(o._helper?o.position.top-h.top:o.position.top),u&&(o.size.width=o.size.height*o.aspectRatio,p=!1),o.position.top=o._helper?h.top:0),n=o.containerElement.get(0)===o.element.parent().get(0),a=/relative|absolute/.test(o.containerElement.css("position")),n&&a?(o.offset.left=o.parentData.left+o.position.left,o.offset.top=o.parentData.top+o.position.top):(o.offset.left=o.element.offset().left,o.offset.top=o.element.offset().top),i=Math.abs(o.sizeDiff.width+(o._helper?o.offset.left-c.left:o.offset.left-h.left)),s=Math.abs(o.sizeDiff.height+(o._helper?o.offset.top-c.top:o.offset.top-h.top)),i+o.size.width>=o.parentData.width&&(o.size.width=o.parentData.width-i,u&&(o.size.height=o.size.width/o.aspectRatio,p=!1)),s+o.size.height>=o.parentData.height&&(o.size.height=o.parentData.height-s,u&&(o.size.width=o.size.height*o.aspectRatio,p=!1)),p||(o.position.left=o.prevPosition.left,o.position.top=o.prevPosition.top,o.size.width=o.prevSize.width,o.size.height=o.prevSize.height)},stop:function(){var e=t(this).resizable("instance"),i=e.options,s=e.containerOffset,n=e.containerPosition,a=e.containerElement,o=t(e.helper),r=o.offset(),h=o.outerWidth()-e.sizeDiff.width,l=o.outerHeight()-e.sizeDiff.height;e._helper&&!i.animate&&/relative/.test(a.css("position"))&&t(this).css({left:r.left-n.left-s.left,width:h,height:l}),e._helper&&!i.animate&&/static/.test(a.css("position"))&&t(this).css({left:r.left-n.left-s.left,width:h,height:l})}}),t.ui.plugin.add("resizable","alsoResize",{start:function(){var e=t(this).resizable("instance"),i=e.options;t(i.alsoResize).each(function(){var e=t(this);e.data("ui-resizable-alsoresize",{width:parseFloat(e.width()),height:parseFloat(e.height()),left:parseFloat(e.css("left")),top:parseFloat(e.css("top"))})})},resize:function(e,i){var s=t(this).resizable("instance"),n=s.options,a=s.originalSize,o=s.originalPosition,r={height:s.size.height-a.height||0,width:s.size.width-a.width||0,top:s.position.top-o.top||0,left:s.position.left-o.left||0}; t(n.alsoResize).each(function(){var e=t(this),s=t(this).data("ui-resizable-alsoresize"),n={},a=e.parents(i.originalElement[0]).length?["width","height"]:["width","height","top","left"];t.each(a,function(t,e){var i=(s[e]||0)+(r[e]||0);i&&i>=0&&(n[e]=i||null)}),e.css(n)})},stop:function(){t(this).removeData("ui-resizable-alsoresize")}}),t.ui.plugin.add("resizable","ghost",{start:function(){var e=t(this).resizable("instance"),i=e.size;e.ghost=e.originalElement.clone(),e.ghost.css({opacity:.25,display:"block",position:"relative",height:i.height,width:i.width,margin:0,left:0,top:0}),e._addClass(e.ghost,"ui-resizable-ghost"),t.uiBackCompat!==!1&&"string"==typeof e.options.ghost&&e.ghost.addClass(this.options.ghost),e.ghost.appendTo(e.helper)},resize:function(){var e=t(this).resizable("instance");e.ghost&&e.ghost.css({position:"relative",height:e.size.height,width:e.size.width})},stop:function(){var e=t(this).resizable("instance");e.ghost&&e.helper&&e.helper.get(0).removeChild(e.ghost.get(0))}}),t.ui.plugin.add("resizable","grid",{resize:function(){var e,i=t(this).resizable("instance"),s=i.options,n=i.size,a=i.originalSize,o=i.originalPosition,r=i.axis,h="number"==typeof s.grid?[s.grid,s.grid]:s.grid,l=h[0]||1,u=h[1]||1,c=Math.round((n.width-a.width)/l)*l,d=Math.round((n.height-a.height)/u)*u,p=a.width+c,f=a.height+d,m=s.maxWidth&&p>s.maxWidth,g=s.maxHeight&&f>s.maxHeight,_=s.minWidth&&s.minWidth>p,v=s.minHeight&&s.minHeight>f;s.grid=h,_&&(p+=l),v&&(f+=u),m&&(p-=l),g&&(f-=u),/^(se|s|e)$/.test(r)?(i.size.width=p,i.size.height=f):/^(ne)$/.test(r)?(i.size.width=p,i.size.height=f,i.position.top=o.top-d):/^(sw)$/.test(r)?(i.size.width=p,i.size.height=f,i.position.left=o.left-c):((0>=f-u||0>=p-l)&&(e=i._getPaddingPlusBorderDimensions(this)),f-u>0?(i.size.height=f,i.position.top=o.top-d):(f=u-e.height,i.size.height=f,i.position.top=o.top+a.height-f),p-l>0?(i.size.width=p,i.position.left=o.left-c):(p=l-e.width,i.size.width=p,i.position.left=o.left+a.width-p))}}),t.ui.resizable,t.widget("ui.selectable",t.ui.mouse,{version:"1.12.1",options:{appendTo:"body",autoRefresh:!0,distance:0,filter:"*",tolerance:"touch",selected:null,selecting:null,start:null,stop:null,unselected:null,unselecting:null},_create:function(){var e=this;this._addClass("ui-selectable"),this.dragged=!1,this.refresh=function(){e.elementPos=t(e.element[0]).offset(),e.selectees=t(e.options.filter,e.element[0]),e._addClass(e.selectees,"ui-selectee"),e.selectees.each(function(){var i=t(this),s=i.offset(),n={left:s.left-e.elementPos.left,top:s.top-e.elementPos.top};t.data(this,"selectable-item",{element:this,$element:i,left:n.left,top:n.top,right:n.left+i.outerWidth(),bottom:n.top+i.outerHeight(),startselected:!1,selected:i.hasClass("ui-selected"),selecting:i.hasClass("ui-selecting"),unselecting:i.hasClass("ui-unselecting")})})},this.refresh(),this._mouseInit(),this.helper=t("<div>"),this._addClass(this.helper,"ui-selectable-helper")},_destroy:function(){this.selectees.removeData("selectable-item"),this._mouseDestroy()},_mouseStart:function(e){var i=this,s=this.options;this.opos=[e.pageX,e.pageY],this.elementPos=t(this.element[0]).offset(),this.options.disabled||(this.selectees=t(s.filter,this.element[0]),this._trigger("start",e),t(s.appendTo).append(this.helper),this.helper.css({left:e.pageX,top:e.pageY,width:0,height:0}),s.autoRefresh&&this.refresh(),this.selectees.filter(".ui-selected").each(function(){var s=t.data(this,"selectable-item");s.startselected=!0,e.metaKey||e.ctrlKey||(i._removeClass(s.$element,"ui-selected"),s.selected=!1,i._addClass(s.$element,"ui-unselecting"),s.unselecting=!0,i._trigger("unselecting",e,{unselecting:s.element}))}),t(e.target).parents().addBack().each(function(){var s,n=t.data(this,"selectable-item");return n?(s=!e.metaKey&&!e.ctrlKey||!n.$element.hasClass("ui-selected"),i._removeClass(n.$element,s?"ui-unselecting":"ui-selected")._addClass(n.$element,s?"ui-selecting":"ui-unselecting"),n.unselecting=!s,n.selecting=s,n.selected=s,s?i._trigger("selecting",e,{selecting:n.element}):i._trigger("unselecting",e,{unselecting:n.element}),!1):void 0}))},_mouseDrag:function(e){if(this.dragged=!0,!this.options.disabled){var i,s=this,n=this.options,a=this.opos[0],o=this.opos[1],r=e.pageX,h=e.pageY;return a>r&&(i=r,r=a,a=i),o>h&&(i=h,h=o,o=i),this.helper.css({left:a,top:o,width:r-a,height:h-o}),this.selectees.each(function(){var i=t.data(this,"selectable-item"),l=!1,u={};i&&i.element!==s.element[0]&&(u.left=i.left+s.elementPos.left,u.right=i.right+s.elementPos.left,u.top=i.top+s.elementPos.top,u.bottom=i.bottom+s.elementPos.top,"touch"===n.tolerance?l=!(u.left>r||a>u.right||u.top>h||o>u.bottom):"fit"===n.tolerance&&(l=u.left>a&&r>u.right&&u.top>o&&h>u.bottom),l?(i.selected&&(s._removeClass(i.$element,"ui-selected"),i.selected=!1),i.unselecting&&(s._removeClass(i.$element,"ui-unselecting"),i.unselecting=!1),i.selecting||(s._addClass(i.$element,"ui-selecting"),i.selecting=!0,s._trigger("selecting",e,{selecting:i.element}))):(i.selecting&&((e.metaKey||e.ctrlKey)&&i.startselected?(s._removeClass(i.$element,"ui-selecting"),i.selecting=!1,s._addClass(i.$element,"ui-selected"),i.selected=!0):(s._removeClass(i.$element,"ui-selecting"),i.selecting=!1,i.startselected&&(s._addClass(i.$element,"ui-unselecting"),i.unselecting=!0),s._trigger("unselecting",e,{unselecting:i.element}))),i.selected&&(e.metaKey||e.ctrlKey||i.startselected||(s._removeClass(i.$element,"ui-selected"),i.selected=!1,s._addClass(i.$element,"ui-unselecting"),i.unselecting=!0,s._trigger("unselecting",e,{unselecting:i.element})))))}),!1}},_mouseStop:function(e){var i=this;return this.dragged=!1,t(".ui-unselecting",this.element[0]).each(function(){var s=t.data(this,"selectable-item");i._removeClass(s.$element,"ui-unselecting"),s.unselecting=!1,s.startselected=!1,i._trigger("unselected",e,{unselected:s.element})}),t(".ui-selecting",this.element[0]).each(function(){var s=t.data(this,"selectable-item");i._removeClass(s.$element,"ui-selecting")._addClass(s.$element,"ui-selected"),s.selecting=!1,s.selected=!0,s.startselected=!0,i._trigger("selected",e,{selected:s.element})}),this._trigger("stop",e),this.helper.remove(),!1}}),t.widget("ui.sortable",t.ui.mouse,{version:"1.12.1",widgetEventPrefix:"sort",ready:!1,options:{appendTo:"parent",axis:!1,connectWith:!1,containment:!1,cursor:"auto",cursorAt:!1,dropOnEmpty:!0,forcePlaceholderSize:!1,forceHelperSize:!1,grid:!1,handle:!1,helper:"original",items:"> *",opacity:!1,placeholder:!1,revert:!1,scroll:!0,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1e3,activate:null,beforeStop:null,change:null,deactivate:null,out:null,over:null,receive:null,remove:null,sort:null,start:null,stop:null,update:null},_isOverAxis:function(t,e,i){return t>=e&&e+i>t},_isFloating:function(t){return/left|right/.test(t.css("float"))||/inline|table-cell/.test(t.css("display"))},_create:function(){this.containerCache={},this._addClass("ui-sortable"),this.refresh(),this.offset=this.element.offset(),this._mouseInit(),this._setHandleClassName(),this.ready=!0},_setOption:function(t,e){this._super(t,e),"handle"===t&&this._setHandleClassName()},_setHandleClassName:function(){var e=this;this._removeClass(this.element.find(".ui-sortable-handle"),"ui-sortable-handle"),t.each(this.items,function(){e._addClass(this.instance.options.handle?this.item.find(this.instance.options.handle):this.item,"ui-sortable-handle")})},_destroy:function(){this._mouseDestroy();for(var t=this.items.length-1;t>=0;t--)this.items[t].item.removeData(this.widgetName+"-item");return this},_mouseCapture:function(e,i){var s=null,n=!1,a=this;return this.reverting?!1:this.options.disabled||"static"===this.options.type?!1:(this._refreshItems(e),t(e.target).parents().each(function(){return t.data(this,a.widgetName+"-item")===a?(s=t(this),!1):void 0}),t.data(e.target,a.widgetName+"-item")===a&&(s=t(e.target)),s?!this.options.handle||i||(t(this.options.handle,s).find("*").addBack().each(function(){this===e.target&&(n=!0)}),n)?(this.currentItem=s,this._removeCurrentsFromItems(),!0):!1:!1)},_mouseStart:function(e,i,s){var n,a,o=this.options;if(this.currentContainer=this,this.refreshPositions(),this.helper=this._createHelper(e),this._cacheHelperProportions(),this._cacheMargins(),this.scrollParent=this.helper.scrollParent(),this.offset=this.currentItem.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},t.extend(this.offset,{click:{left:e.pageX-this.offset.left,top:e.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.helper.css("position","absolute"),this.cssPosition=this.helper.css("position"),this.originalPosition=this._generatePosition(e),this.originalPageX=e.pageX,this.originalPageY=e.pageY,o.cursorAt&&this._adjustOffsetFromHelper(o.cursorAt),this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]},this.helper[0]!==this.currentItem[0]&&this.currentItem.hide(),this._createPlaceholder(),o.containment&&this._setContainment(),o.cursor&&"auto"!==o.cursor&&(a=this.document.find("body"),this.storedCursor=a.css("cursor"),a.css("cursor",o.cursor),this.storedStylesheet=t("<style>*{ cursor: "+o.cursor+" !important; }</style>").appendTo(a)),o.opacity&&(this.helper.css("opacity")&&(this._storedOpacity=this.helper.css("opacity")),this.helper.css("opacity",o.opacity)),o.zIndex&&(this.helper.css("zIndex")&&(this._storedZIndex=this.helper.css("zIndex")),this.helper.css("zIndex",o.zIndex)),this.scrollParent[0]!==this.document[0]&&"HTML"!==this.scrollParent[0].tagName&&(this.overflowOffset=this.scrollParent.offset()),this._trigger("start",e,this._uiHash()),this._preserveHelperProportions||this._cacheHelperProportions(),!s)for(n=this.containers.length-1;n>=0;n--)this.containers[n]._trigger("activate",e,this._uiHash(this));return t.ui.ddmanager&&(t.ui.ddmanager.current=this),t.ui.ddmanager&&!o.dropBehaviour&&t.ui.ddmanager.prepareOffsets(this,e),this.dragging=!0,this._addClass(this.helper,"ui-sortable-helper"),this._mouseDrag(e),!0},_mouseDrag:function(e){var i,s,n,a,o=this.options,r=!1;for(this.position=this._generatePosition(e),this.positionAbs=this._convertPositionTo("absolute"),this.lastPositionAbs||(this.lastPositionAbs=this.positionAbs),this.options.scroll&&(this.scrollParent[0]!==this.document[0]&&"HTML"!==this.scrollParent[0].tagName?(this.overflowOffset.top+this.scrollParent[0].offsetHeight-e.pageY<o.scrollSensitivity?this.scrollParent[0].scrollTop=r=this.scrollParent[0].scrollTop+o.scrollSpeed:e.pageY-this.overflowOffset.top<o.scrollSensitivity&&(this.scrollParent[0].scrollTop=r=this.scrollParent[0].scrollTop-o.scrollSpeed),this.overflowOffset.left+this.scrollParent[0].offsetWidth-e.pageX<o.scrollSensitivity?this.scrollParent[0].scrollLeft=r=this.scrollParent[0].scrollLeft+o.scrollSpeed:e.pageX-this.overflowOffset.left<o.scrollSensitivity&&(this.scrollParent[0].scrollLeft=r=this.scrollParent[0].scrollLeft-o.scrollSpeed)):(e.pageY-this.document.scrollTop()<o.scrollSensitivity?r=this.document.scrollTop(this.document.scrollTop()-o.scrollSpeed):this.window.height()-(e.pageY-this.document.scrollTop())<o.scrollSensitivity&&(r=this.document.scrollTop(this.document.scrollTop()+o.scrollSpeed)),e.pageX-this.document.scrollLeft()<o.scrollSensitivity?r=this.document.scrollLeft(this.document.scrollLeft()-o.scrollSpeed):this.window.width()-(e.pageX-this.document.scrollLeft())<o.scrollSensitivity&&(r=this.document.scrollLeft(this.document.scrollLeft()+o.scrollSpeed))),r!==!1&&t.ui.ddmanager&&!o.dropBehaviour&&t.ui.ddmanager.prepareOffsets(this,e)),this.positionAbs=this._convertPositionTo("absolute"),this.options.axis&&"y"===this.options.axis||(this.helper[0].style.left=this.position.left+"px"),this.options.axis&&"x"===this.options.axis||(this.helper[0].style.top=this.position.top+"px"),i=this.items.length-1;i>=0;i--)if(s=this.items[i],n=s.item[0],a=this._intersectsWithPointer(s),a&&s.instance===this.currentContainer&&n!==this.currentItem[0]&&this.placeholder[1===a?"next":"prev"]()[0]!==n&&!t.contains(this.placeholder[0],n)&&("semi-dynamic"===this.options.type?!t.contains(this.element[0],n):!0)){if(this.direction=1===a?"down":"up","pointer"!==this.options.tolerance&&!this._intersectsWithSides(s))break;this._rearrange(e,s),this._trigger("change",e,this._uiHash());break}return this._contactContainers(e),t.ui.ddmanager&&t.ui.ddmanager.drag(this,e),this._trigger("sort",e,this._uiHash()),this.lastPositionAbs=this.positionAbs,!1},_mouseStop:function(e,i){if(e){if(t.ui.ddmanager&&!this.options.dropBehaviour&&t.ui.ddmanager.drop(this,e),this.options.revert){var s=this,n=this.placeholder.offset(),a=this.options.axis,o={};a&&"x"!==a||(o.left=n.left-this.offset.parent.left-this.margins.left+(this.offsetParent[0]===this.document[0].body?0:this.offsetParent[0].scrollLeft)),a&&"y"!==a||(o.top=n.top-this.offset.parent.top-this.margins.top+(this.offsetParent[0]===this.document[0].body?0:this.offsetParent[0].scrollTop)),this.reverting=!0,t(this.helper).animate(o,parseInt(this.options.revert,10)||500,function(){s._clear(e)})}else this._clear(e,i);return!1}},cancel:function(){if(this.dragging){this._mouseUp(new t.Event("mouseup",{target:null})),"original"===this.options.helper?(this.currentItem.css(this._storedCSS),this._removeClass(this.currentItem,"ui-sortable-helper")):this.currentItem.show();for(var e=this.containers.length-1;e>=0;e--)this.containers[e]._trigger("deactivate",null,this._uiHash(this)),this.containers[e].containerCache.over&&(this.containers[e]._trigger("out",null,this._uiHash(this)),this.containers[e].containerCache.over=0)}return this.placeholder&&(this.placeholder[0].parentNode&&this.placeholder[0].parentNode.removeChild(this.placeholder[0]),"original"!==this.options.helper&&this.helper&&this.helper[0].parentNode&&this.helper.remove(),t.extend(this,{helper:null,dragging:!1,reverting:!1,_noFinalSort:null}),this.domPosition.prev?t(this.domPosition.prev).after(this.currentItem):t(this.domPosition.parent).prepend(this.currentItem)),this},serialize:function(e){var i=this._getItemsAsjQuery(e&&e.connected),s=[];return e=e||{},t(i).each(function(){var i=(t(e.item||this).attr(e.attribute||"id")||"").match(e.expression||/(.+)[\-=_](.+)/);i&&s.push((e.key||i[1]+"[]")+"="+(e.key&&e.expression?i[1]:i[2]))}),!s.length&&e.key&&s.push(e.key+"="),s.join("&")},toArray:function(e){var i=this._getItemsAsjQuery(e&&e.connected),s=[];return e=e||{},i.each(function(){s.push(t(e.item||this).attr(e.attribute||"id")||"")}),s},_intersectsWith:function(t){var e=this.positionAbs.left,i=e+this.helperProportions.width,s=this.positionAbs.top,n=s+this.helperProportions.height,a=t.left,o=a+t.width,r=t.top,h=r+t.height,l=this.offset.click.top,u=this.offset.click.left,c="x"===this.options.axis||s+l>r&&h>s+l,d="y"===this.options.axis||e+u>a&&o>e+u,p=c&&d;return"pointer"===this.options.tolerance||this.options.forcePointerForContainers||"pointer"!==this.options.tolerance&&this.helperProportions[this.floating?"width":"height"]>t[this.floating?"width":"height"]?p:e+this.helperProportions.width/2>a&&o>i-this.helperProportions.width/2&&s+this.helperProportions.height/2>r&&h>n-this.helperProportions.height/2},_intersectsWithPointer:function(t){var e,i,s="x"===this.options.axis||this._isOverAxis(this.positionAbs.top+this.offset.click.top,t.top,t.height),n="y"===this.options.axis||this._isOverAxis(this.positionAbs.left+this.offset.click.left,t.left,t.width),a=s&&n;return a?(e=this._getDragVerticalDirection(),i=this._getDragHorizontalDirection(),this.floating?"right"===i||"down"===e?2:1:e&&("down"===e?2:1)):!1},_intersectsWithSides:function(t){var e=this._isOverAxis(this.positionAbs.top+this.offset.click.top,t.top+t.height/2,t.height),i=this._isOverAxis(this.positionAbs.left+this.offset.click.left,t.left+t.width/2,t.width),s=this._getDragVerticalDirection(),n=this._getDragHorizontalDirection();return this.floating&&n?"right"===n&&i||"left"===n&&!i:s&&("down"===s&&e||"up"===s&&!e)},_getDragVerticalDirection:function(){var t=this.positionAbs.top-this.lastPositionAbs.top;return 0!==t&&(t>0?"down":"up")},_getDragHorizontalDirection:function(){var t=this.positionAbs.left-this.lastPositionAbs.left;return 0!==t&&(t>0?"right":"left")},refresh:function(t){return this._refreshItems(t),this._setHandleClassName(),this.refreshPositions(),this},_connectWith:function(){var t=this.options;return t.connectWith.constructor===String?[t.connectWith]:t.connectWith},_getItemsAsjQuery:function(e){function i(){r.push(this)}var s,n,a,o,r=[],h=[],l=this._connectWith();if(l&&e)for(s=l.length-1;s>=0;s--)for(a=t(l[s],this.document[0]),n=a.length-1;n>=0;n--)o=t.data(a[n],this.widgetFullName),o&&o!==this&&!o.options.disabled&&h.push([t.isFunction(o.options.items)?o.options.items.call(o.element):t(o.options.items,o.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),o]);for(h.push([t.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):t(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]),s=h.length-1;s>=0;s--)h[s][0].each(i);return t(r)},_removeCurrentsFromItems:function(){var e=this.currentItem.find(":data("+this.widgetName+"-item)");this.items=t.grep(this.items,function(t){for(var i=0;e.length>i;i++)if(e[i]===t.item[0])return!1;return!0})},_refreshItems:function(e){this.items=[],this.containers=[this];var i,s,n,a,o,r,h,l,u=this.items,c=[[t.isFunction(this.options.items)?this.options.items.call(this.element[0],e,{item:this.currentItem}):t(this.options.items,this.element),this]],d=this._connectWith();if(d&&this.ready)for(i=d.length-1;i>=0;i--)for(n=t(d[i],this.document[0]),s=n.length-1;s>=0;s--)a=t.data(n[s],this.widgetFullName),a&&a!==this&&!a.options.disabled&&(c.push([t.isFunction(a.options.items)?a.options.items.call(a.element[0],e,{item:this.currentItem}):t(a.options.items,a.element),a]),this.containers.push(a));for(i=c.length-1;i>=0;i--)for(o=c[i][1],r=c[i][0],s=0,l=r.length;l>s;s++)h=t(r[s]),h.data(this.widgetName+"-item",o),u.push({item:h,instance:o,width:0,height:0,left:0,top:0})},refreshPositions:function(e){this.floating=this.items.length?"x"===this.options.axis||this._isFloating(this.items[0].item):!1,this.offsetParent&&this.helper&&(this.offset.parent=this._getParentOffset());var i,s,n,a;for(i=this.items.length-1;i>=0;i--)s=this.items[i],s.instance!==this.currentContainer&&this.currentContainer&&s.item[0]!==this.currentItem[0]||(n=this.options.toleranceElement?t(this.options.toleranceElement,s.item):s.item,e||(s.width=n.outerWidth(),s.height=n.outerHeight()),a=n.offset(),s.left=a.left,s.top=a.top);if(this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(i=this.containers.length-1;i>=0;i--)a=this.containers[i].element.offset(),this.containers[i].containerCache.left=a.left,this.containers[i].containerCache.top=a.top,this.containers[i].containerCache.width=this.containers[i].element.outerWidth(),this.containers[i].containerCache.height=this.containers[i].element.outerHeight();return this},_createPlaceholder:function(e){e=e||this;var i,s=e.options;s.placeholder&&s.placeholder.constructor!==String||(i=s.placeholder,s.placeholder={element:function(){var s=e.currentItem[0].nodeName.toLowerCase(),n=t("<"+s+">",e.document[0]);return e._addClass(n,"ui-sortable-placeholder",i||e.currentItem[0].className)._removeClass(n,"ui-sortable-helper"),"tbody"===s?e._createTrPlaceholder(e.currentItem.find("tr").eq(0),t("<tr>",e.document[0]).appendTo(n)):"tr"===s?e._createTrPlaceholder(e.currentItem,n):"img"===s&&n.attr("src",e.currentItem.attr("src")),i||n.css("visibility","hidden"),n},update:function(t,n){(!i||s.forcePlaceholderSize)&&(n.height()||n.height(e.currentItem.innerHeight()-parseInt(e.currentItem.css("paddingTop")||0,10)-parseInt(e.currentItem.css("paddingBottom")||0,10)),n.width()||n.width(e.currentItem.innerWidth()-parseInt(e.currentItem.css("paddingLeft")||0,10)-parseInt(e.currentItem.css("paddingRight")||0,10)))}}),e.placeholder=t(s.placeholder.element.call(e.element,e.currentItem)),e.currentItem.after(e.placeholder),s.placeholder.update(e,e.placeholder)},_createTrPlaceholder:function(e,i){var s=this;e.children().each(function(){t("<td>&#160;</td>",s.document[0]).attr("colspan",t(this).attr("colspan")||1).appendTo(i)})},_contactContainers:function(e){var i,s,n,a,o,r,h,l,u,c,d=null,p=null;for(i=this.containers.length-1;i>=0;i--)if(!t.contains(this.currentItem[0],this.containers[i].element[0]))if(this._intersectsWith(this.containers[i].containerCache)){if(d&&t.contains(this.containers[i].element[0],d.element[0]))continue;d=this.containers[i],p=i}else this.containers[i].containerCache.over&&(this.containers[i]._trigger("out",e,this._uiHash(this)),this.containers[i].containerCache.over=0);if(d)if(1===this.containers.length)this.containers[p].containerCache.over||(this.containers[p]._trigger("over",e,this._uiHash(this)),this.containers[p].containerCache.over=1);else{for(n=1e4,a=null,u=d.floating||this._isFloating(this.currentItem),o=u?"left":"top",r=u?"width":"height",c=u?"pageX":"pageY",s=this.items.length-1;s>=0;s--)t.contains(this.containers[p].element[0],this.items[s].item[0])&&this.items[s].item[0]!==this.currentItem[0]&&(h=this.items[s].item.offset()[o],l=!1,e[c]-h>this.items[s][r]/2&&(l=!0),n>Math.abs(e[c]-h)&&(n=Math.abs(e[c]-h),a=this.items[s],this.direction=l?"up":"down"));if(!a&&!this.options.dropOnEmpty)return;if(this.currentContainer===this.containers[p])return this.currentContainer.containerCache.over||(this.containers[p]._trigger("over",e,this._uiHash()),this.currentContainer.containerCache.over=1),void 0;a?this._rearrange(e,a,null,!0):this._rearrange(e,null,this.containers[p].element,!0),this._trigger("change",e,this._uiHash()),this.containers[p]._trigger("change",e,this._uiHash(this)),this.currentContainer=this.containers[p],this.options.placeholder.update(this.currentContainer,this.placeholder),this.containers[p]._trigger("over",e,this._uiHash(this)),this.containers[p].containerCache.over=1}},_createHelper:function(e){var i=this.options,s=t.isFunction(i.helper)?t(i.helper.apply(this.element[0],[e,this.currentItem])):"clone"===i.helper?this.currentItem.clone():this.currentItem;return s.parents("body").length||t("parent"!==i.appendTo?i.appendTo:this.currentItem[0].parentNode)[0].appendChild(s[0]),s[0]===this.currentItem[0]&&(this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")}),(!s[0].style.width||i.forceHelperSize)&&s.width(this.currentItem.width()),(!s[0].style.height||i.forceHelperSize)&&s.height(this.currentItem.height()),s},_adjustOffsetFromHelper:function(e){"string"==typeof e&&(e=e.split(" ")),t.isArray(e)&&(e={left:+e[0],top:+e[1]||0}),"left"in e&&(this.offset.click.left=e.left+this.margins.left),"right"in e&&(this.offset.click.left=this.helperProportions.width-e.right+this.margins.left),"top"in e&&(this.offset.click.top=e.top+this.margins.top),"bottom"in e&&(this.offset.click.top=this.helperProportions.height-e.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var e=this.offsetParent.offset();return"absolute"===this.cssPosition&&this.scrollParent[0]!==this.document[0]&&t.contains(this.scrollParent[0],this.offsetParent[0])&&(e.left+=this.scrollParent.scrollLeft(),e.top+=this.scrollParent.scrollTop()),(this.offsetParent[0]===this.document[0].body||this.offsetParent[0].tagName&&"html"===this.offsetParent[0].tagName.toLowerCase()&&t.ui.ie)&&(e={top:0,left:0}),{top:e.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:e.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"===this.cssPosition){var t=this.currentItem.position();return{top:t.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:t.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.currentItem.css("marginLeft"),10)||0,top:parseInt(this.currentItem.css("marginTop"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var e,i,s,n=this.options;"parent"===n.containment&&(n.containment=this.helper[0].parentNode),("document"===n.containment||"window"===n.containment)&&(this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,"document"===n.containment?this.document.width():this.window.width()-this.helperProportions.width-this.margins.left,("document"===n.containment?this.document.height()||document.body.parentNode.scrollHeight:this.window.height()||this.document[0].body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]),/^(document|window|parent)$/.test(n.containment)||(e=t(n.containment)[0],i=t(n.containment).offset(),s="hidden"!==t(e).css("overflow"),this.containment=[i.left+(parseInt(t(e).css("borderLeftWidth"),10)||0)+(parseInt(t(e).css("paddingLeft"),10)||0)-this.margins.left,i.top+(parseInt(t(e).css("borderTopWidth"),10)||0)+(parseInt(t(e).css("paddingTop"),10)||0)-this.margins.top,i.left+(s?Math.max(e.scrollWidth,e.offsetWidth):e.offsetWidth)-(parseInt(t(e).css("borderLeftWidth"),10)||0)-(parseInt(t(e).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,i.top+(s?Math.max(e.scrollHeight,e.offsetHeight):e.offsetHeight)-(parseInt(t(e).css("borderTopWidth"),10)||0)-(parseInt(t(e).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top])},_convertPositionTo:function(e,i){i||(i=this.position);var s="absolute"===e?1:-1,n="absolute"!==this.cssPosition||this.scrollParent[0]!==this.document[0]&&t.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,a=/(html|body)/i.test(n[0].tagName);return{top:i.top+this.offset.relative.top*s+this.offset.parent.top*s-("fixed"===this.cssPosition?-this.scrollParent.scrollTop():a?0:n.scrollTop())*s,left:i.left+this.offset.relative.left*s+this.offset.parent.left*s-("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():a?0:n.scrollLeft())*s}},_generatePosition:function(e){var i,s,n=this.options,a=e.pageX,o=e.pageY,r="absolute"!==this.cssPosition||this.scrollParent[0]!==this.document[0]&&t.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,h=/(html|body)/i.test(r[0].tagName);return"relative"!==this.cssPosition||this.scrollParent[0]!==this.document[0]&&this.scrollParent[0]!==this.offsetParent[0]||(this.offset.relative=this._getRelativeOffset()),this.originalPosition&&(this.containment&&(e.pageX-this.offset.click.left<this.containment[0]&&(a=this.containment[0]+this.offset.click.left),e.pageY-this.offset.click.top<this.containment[1]&&(o=this.containment[1]+this.offset.click.top),e.pageX-this.offset.click.left>this.containment[2]&&(a=this.containment[2]+this.offset.click.left),e.pageY-this.offset.click.top>this.containment[3]&&(o=this.containment[3]+this.offset.click.top)),n.grid&&(i=this.originalPageY+Math.round((o-this.originalPageY)/n.grid[1])*n.grid[1],o=this.containment?i-this.offset.click.top>=this.containment[1]&&i-this.offset.click.top<=this.containment[3]?i:i-this.offset.click.top>=this.containment[1]?i-n.grid[1]:i+n.grid[1]:i,s=this.originalPageX+Math.round((a-this.originalPageX)/n.grid[0])*n.grid[0],a=this.containment?s-this.offset.click.left>=this.containment[0]&&s-this.offset.click.left<=this.containment[2]?s:s-this.offset.click.left>=this.containment[0]?s-n.grid[0]:s+n.grid[0]:s)),{top:o-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.scrollParent.scrollTop():h?0:r.scrollTop()),left:a-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():h?0:r.scrollLeft())}},_rearrange:function(t,e,i,s){i?i[0].appendChild(this.placeholder[0]):e.item[0].parentNode.insertBefore(this.placeholder[0],"down"===this.direction?e.item[0]:e.item[0].nextSibling),this.counter=this.counter?++this.counter:1;var n=this.counter;this._delay(function(){n===this.counter&&this.refreshPositions(!s)})},_clear:function(t,e){function i(t,e,i){return function(s){i._trigger(t,s,e._uiHash(e))}}this.reverting=!1;var s,n=[];if(!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem),this._noFinalSort=null,this.helper[0]===this.currentItem[0]){for(s in this._storedCSS)("auto"===this._storedCSS[s]||"static"===this._storedCSS[s])&&(this._storedCSS[s]="");this.currentItem.css(this._storedCSS),this._removeClass(this.currentItem,"ui-sortable-helper")}else this.currentItem.show();for(this.fromOutside&&!e&&n.push(function(t){this._trigger("receive",t,this._uiHash(this.fromOutside))}),!this.fromOutside&&this.domPosition.prev===this.currentItem.prev().not(".ui-sortable-helper")[0]&&this.domPosition.parent===this.currentItem.parent()[0]||e||n.push(function(t){this._trigger("update",t,this._uiHash())}),this!==this.currentContainer&&(e||(n.push(function(t){this._trigger("remove",t,this._uiHash())}),n.push(function(t){return function(e){t._trigger("receive",e,this._uiHash(this))}}.call(this,this.currentContainer)),n.push(function(t){return function(e){t._trigger("update",e,this._uiHash(this))}}.call(this,this.currentContainer)))),s=this.containers.length-1;s>=0;s--)e||n.push(i("deactivate",this,this.containers[s])),this.containers[s].containerCache.over&&(n.push(i("out",this,this.containers[s])),this.containers[s].containerCache.over=0);if(this.storedCursor&&(this.document.find("body").css("cursor",this.storedCursor),this.storedStylesheet.remove()),this._storedOpacity&&this.helper.css("opacity",this._storedOpacity),this._storedZIndex&&this.helper.css("zIndex","auto"===this._storedZIndex?"":this._storedZIndex),this.dragging=!1,e||this._trigger("beforeStop",t,this._uiHash()),this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.cancelHelperRemoval||(this.helper[0]!==this.currentItem[0]&&this.helper.remove(),this.helper=null),!e){for(s=0;n.length>s;s++)n[s].call(this,t);this._trigger("stop",t,this._uiHash())}return this.fromOutside=!1,!this.cancelHelperRemoval},_trigger:function(){t.Widget.prototype._trigger.apply(this,arguments)===!1&&this.cancel()},_uiHash:function(e){var i=e||this;return{helper:i.helper,placeholder:i.placeholder||t([]),position:i.position,originalPosition:i.originalPosition,offset:i.positionAbs,item:i.currentItem,sender:e?e.element:null}}}),t.widget("ui.accordion",{version:"1.12.1",options:{active:0,animate:{},classes:{"ui-accordion-header":"ui-corner-top","ui-accordion-header-collapsed":"ui-corner-all","ui-accordion-content":"ui-corner-bottom"},collapsible:!1,event:"click",header:"> li > :first-child, > :not(li):even",heightStyle:"auto",icons:{activeHeader:"ui-icon-triangle-1-s",header:"ui-icon-triangle-1-e"},activate:null,beforeActivate:null},hideProps:{borderTopWidth:"hide",borderBottomWidth:"hide",paddingTop:"hide",paddingBottom:"hide",height:"hide"},showProps:{borderTopWidth:"show",borderBottomWidth:"show",paddingTop:"show",paddingBottom:"show",height:"show"},_create:function(){var e=this.options;this.prevShow=this.prevHide=t(),this._addClass("ui-accordion","ui-widget ui-helper-reset"),this.element.attr("role","tablist"),e.collapsible||e.active!==!1&&null!=e.active||(e.active=0),this._processPanels(),0>e.active&&(e.active+=this.headers.length),this._refresh()},_getCreateEventData:function(){return{header:this.active,panel:this.active.length?this.active.next():t()}},_createIcons:function(){var e,i,s=this.options.icons;s&&(e=t("<span>"),this._addClass(e,"ui-accordion-header-icon","ui-icon "+s.header),e.prependTo(this.headers),i=this.active.children(".ui-accordion-header-icon"),this._removeClass(i,s.header)._addClass(i,null,s.activeHeader)._addClass(this.headers,"ui-accordion-icons")) },_destroyIcons:function(){this._removeClass(this.headers,"ui-accordion-icons"),this.headers.children(".ui-accordion-header-icon").remove()},_destroy:function(){var t;this.element.removeAttr("role"),this.headers.removeAttr("role aria-expanded aria-selected aria-controls tabIndex").removeUniqueId(),this._destroyIcons(),t=this.headers.next().css("display","").removeAttr("role aria-hidden aria-labelledby").removeUniqueId(),"content"!==this.options.heightStyle&&t.css("height","")},_setOption:function(t,e){return"active"===t?(this._activate(e),void 0):("event"===t&&(this.options.event&&this._off(this.headers,this.options.event),this._setupEvents(e)),this._super(t,e),"collapsible"!==t||e||this.options.active!==!1||this._activate(0),"icons"===t&&(this._destroyIcons(),e&&this._createIcons()),void 0)},_setOptionDisabled:function(t){this._super(t),this.element.attr("aria-disabled",t),this._toggleClass(null,"ui-state-disabled",!!t),this._toggleClass(this.headers.add(this.headers.next()),null,"ui-state-disabled",!!t)},_keydown:function(e){if(!e.altKey&&!e.ctrlKey){var i=t.ui.keyCode,s=this.headers.length,n=this.headers.index(e.target),a=!1;switch(e.keyCode){case i.RIGHT:case i.DOWN:a=this.headers[(n+1)%s];break;case i.LEFT:case i.UP:a=this.headers[(n-1+s)%s];break;case i.SPACE:case i.ENTER:this._eventHandler(e);break;case i.HOME:a=this.headers[0];break;case i.END:a=this.headers[s-1]}a&&(t(e.target).attr("tabIndex",-1),t(a).attr("tabIndex",0),t(a).trigger("focus"),e.preventDefault())}},_panelKeyDown:function(e){e.keyCode===t.ui.keyCode.UP&&e.ctrlKey&&t(e.currentTarget).prev().trigger("focus")},refresh:function(){var e=this.options;this._processPanels(),e.active===!1&&e.collapsible===!0||!this.headers.length?(e.active=!1,this.active=t()):e.active===!1?this._activate(0):this.active.length&&!t.contains(this.element[0],this.active[0])?this.headers.length===this.headers.find(".ui-state-disabled").length?(e.active=!1,this.active=t()):this._activate(Math.max(0,e.active-1)):e.active=this.headers.index(this.active),this._destroyIcons(),this._refresh()},_processPanels:function(){var t=this.headers,e=this.panels;this.headers=this.element.find(this.options.header),this._addClass(this.headers,"ui-accordion-header ui-accordion-header-collapsed","ui-state-default"),this.panels=this.headers.next().filter(":not(.ui-accordion-content-active)").hide(),this._addClass(this.panels,"ui-accordion-content","ui-helper-reset ui-widget-content"),e&&(this._off(t.not(this.headers)),this._off(e.not(this.panels)))},_refresh:function(){var e,i=this.options,s=i.heightStyle,n=this.element.parent();this.active=this._findActive(i.active),this._addClass(this.active,"ui-accordion-header-active","ui-state-active")._removeClass(this.active,"ui-accordion-header-collapsed"),this._addClass(this.active.next(),"ui-accordion-content-active"),this.active.next().show(),this.headers.attr("role","tab").each(function(){var e=t(this),i=e.uniqueId().attr("id"),s=e.next(),n=s.uniqueId().attr("id");e.attr("aria-controls",n),s.attr("aria-labelledby",i)}).next().attr("role","tabpanel"),this.headers.not(this.active).attr({"aria-selected":"false","aria-expanded":"false",tabIndex:-1}).next().attr({"aria-hidden":"true"}).hide(),this.active.length?this.active.attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0}).next().attr({"aria-hidden":"false"}):this.headers.eq(0).attr("tabIndex",0),this._createIcons(),this._setupEvents(i.event),"fill"===s?(e=n.height(),this.element.siblings(":visible").each(function(){var i=t(this),s=i.css("position");"absolute"!==s&&"fixed"!==s&&(e-=i.outerHeight(!0))}),this.headers.each(function(){e-=t(this).outerHeight(!0)}),this.headers.next().each(function(){t(this).height(Math.max(0,e-t(this).innerHeight()+t(this).height()))}).css("overflow","auto")):"auto"===s&&(e=0,this.headers.next().each(function(){var i=t(this).is(":visible");i||t(this).show(),e=Math.max(e,t(this).css("height","").height()),i||t(this).hide()}).height(e))},_activate:function(e){var i=this._findActive(e)[0];i!==this.active[0]&&(i=i||this.active[0],this._eventHandler({target:i,currentTarget:i,preventDefault:t.noop}))},_findActive:function(e){return"number"==typeof e?this.headers.eq(e):t()},_setupEvents:function(e){var i={keydown:"_keydown"};e&&t.each(e.split(" "),function(t,e){i[e]="_eventHandler"}),this._off(this.headers.add(this.headers.next())),this._on(this.headers,i),this._on(this.headers.next(),{keydown:"_panelKeyDown"}),this._hoverable(this.headers),this._focusable(this.headers)},_eventHandler:function(e){var i,s,n=this.options,a=this.active,o=t(e.currentTarget),r=o[0]===a[0],h=r&&n.collapsible,l=h?t():o.next(),u=a.next(),c={oldHeader:a,oldPanel:u,newHeader:h?t():o,newPanel:l};e.preventDefault(),r&&!n.collapsible||this._trigger("beforeActivate",e,c)===!1||(n.active=h?!1:this.headers.index(o),this.active=r?t():o,this._toggle(c),this._removeClass(a,"ui-accordion-header-active","ui-state-active"),n.icons&&(i=a.children(".ui-accordion-header-icon"),this._removeClass(i,null,n.icons.activeHeader)._addClass(i,null,n.icons.header)),r||(this._removeClass(o,"ui-accordion-header-collapsed")._addClass(o,"ui-accordion-header-active","ui-state-active"),n.icons&&(s=o.children(".ui-accordion-header-icon"),this._removeClass(s,null,n.icons.header)._addClass(s,null,n.icons.activeHeader)),this._addClass(o.next(),"ui-accordion-content-active")))},_toggle:function(e){var i=e.newPanel,s=this.prevShow.length?this.prevShow:e.oldPanel;this.prevShow.add(this.prevHide).stop(!0,!0),this.prevShow=i,this.prevHide=s,this.options.animate?this._animate(i,s,e):(s.hide(),i.show(),this._toggleComplete(e)),s.attr({"aria-hidden":"true"}),s.prev().attr({"aria-selected":"false","aria-expanded":"false"}),i.length&&s.length?s.prev().attr({tabIndex:-1,"aria-expanded":"false"}):i.length&&this.headers.filter(function(){return 0===parseInt(t(this).attr("tabIndex"),10)}).attr("tabIndex",-1),i.attr("aria-hidden","false").prev().attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0})},_animate:function(t,e,i){var s,n,a,o=this,r=0,h=t.css("box-sizing"),l=t.length&&(!e.length||t.index()<e.index()),u=this.options.animate||{},c=l&&u.down||u,d=function(){o._toggleComplete(i)};return"number"==typeof c&&(a=c),"string"==typeof c&&(n=c),n=n||c.easing||u.easing,a=a||c.duration||u.duration,e.length?t.length?(s=t.show().outerHeight(),e.animate(this.hideProps,{duration:a,easing:n,step:function(t,e){e.now=Math.round(t)}}),t.hide().animate(this.showProps,{duration:a,easing:n,complete:d,step:function(t,i){i.now=Math.round(t),"height"!==i.prop?"content-box"===h&&(r+=i.now):"content"!==o.options.heightStyle&&(i.now=Math.round(s-e.outerHeight()-r),r=0)}}),void 0):e.animate(this.hideProps,a,n,d):t.animate(this.showProps,a,n,d)},_toggleComplete:function(t){var e=t.oldPanel,i=e.prev();this._removeClass(e,"ui-accordion-content-active"),this._removeClass(i,"ui-accordion-header-active")._addClass(i,"ui-accordion-header-collapsed"),e.length&&(e.parent()[0].className=e.parent()[0].className),this._trigger("activate",null,t)}});var d=/ui-corner-([a-z]){2,6}/g;t.widget("ui.controlgroup",{version:"1.12.1",defaultElement:"<div>",options:{direction:"horizontal",disabled:null,onlyVisible:!0,items:{button:"input[type=button], input[type=submit], input[type=reset], button, a",controlgroupLabel:".ui-controlgroup-label",checkboxradio:"input[type='checkbox'], input[type='radio']",selectmenu:"select",spinner:".ui-spinner-input"}},_create:function(){this._enhance()},_enhance:function(){this.element.attr("role","toolbar"),this.refresh()},_destroy:function(){this._callChildMethod("destroy"),this.childWidgets.removeData("ui-controlgroup-data"),this.element.removeAttr("role"),this.options.items.controlgroupLabel&&this.element.find(this.options.items.controlgroupLabel).find(".ui-controlgroup-label-contents").contents().unwrap()},_initWidgets:function(){var e=this,i=[];t.each(this.options.items,function(s,n){var a,o={};return n?"controlgroupLabel"===s?(a=e.element.find(n),a.each(function(){var e=t(this);e.children(".ui-controlgroup-label-contents").length||e.contents().wrapAll("<span class='ui-controlgroup-label-contents'></span>")}),e._addClass(a,null,"ui-widget ui-widget-content ui-state-default"),i=i.concat(a.get()),void 0):(t.fn[s]&&(o=e["_"+s+"Options"]?e["_"+s+"Options"]("middle"):{classes:{}},e.element.find(n).each(function(){var n=t(this),a=n[s]("instance"),r=t.widget.extend({},o);if("button"!==s||!n.parent(".ui-spinner").length){a||(a=n[s]()[s]("instance")),a&&(r.classes=e._resolveClassesValues(r.classes,a)),n[s](r);var h=n[s]("widget");t.data(h[0],"ui-controlgroup-data",a?a:n[s]("instance")),i.push(h[0])}})),void 0):void 0}),this.childWidgets=t(t.unique(i)),this._addClass(this.childWidgets,"ui-controlgroup-item")},_callChildMethod:function(e){this.childWidgets.each(function(){var i=t(this),s=i.data("ui-controlgroup-data");s&&s[e]&&s[e]()})},_updateCornerClass:function(t,e){var i="ui-corner-top ui-corner-bottom ui-corner-left ui-corner-right ui-corner-all",s=this._buildSimpleOptions(e,"label").classes.label;this._removeClass(t,null,i),this._addClass(t,null,s)},_buildSimpleOptions:function(t,e){var i="vertical"===this.options.direction,s={classes:{}};return s.classes[e]={middle:"",first:"ui-corner-"+(i?"top":"left"),last:"ui-corner-"+(i?"bottom":"right"),only:"ui-corner-all"}[t],s},_spinnerOptions:function(t){var e=this._buildSimpleOptions(t,"ui-spinner");return e.classes["ui-spinner-up"]="",e.classes["ui-spinner-down"]="",e},_buttonOptions:function(t){return this._buildSimpleOptions(t,"ui-button")},_checkboxradioOptions:function(t){return this._buildSimpleOptions(t,"ui-checkboxradio-label")},_selectmenuOptions:function(t){var e="vertical"===this.options.direction;return{width:e?"auto":!1,classes:{middle:{"ui-selectmenu-button-open":"","ui-selectmenu-button-closed":""},first:{"ui-selectmenu-button-open":"ui-corner-"+(e?"top":"tl"),"ui-selectmenu-button-closed":"ui-corner-"+(e?"top":"left")},last:{"ui-selectmenu-button-open":e?"":"ui-corner-tr","ui-selectmenu-button-closed":"ui-corner-"+(e?"bottom":"right")},only:{"ui-selectmenu-button-open":"ui-corner-top","ui-selectmenu-button-closed":"ui-corner-all"}}[t]}},_resolveClassesValues:function(e,i){var s={};return t.each(e,function(n){var a=i.options.classes[n]||"";a=t.trim(a.replace(d,"")),s[n]=(a+" "+e[n]).replace(/\s+/g," ")}),s},_setOption:function(t,e){return"direction"===t&&this._removeClass("ui-controlgroup-"+this.options.direction),this._super(t,e),"disabled"===t?(this._callChildMethod(e?"disable":"enable"),void 0):(this.refresh(),void 0)},refresh:function(){var e,i=this;this._addClass("ui-controlgroup ui-controlgroup-"+this.options.direction),"horizontal"===this.options.direction&&this._addClass(null,"ui-helper-clearfix"),this._initWidgets(),e=this.childWidgets,this.options.onlyVisible&&(e=e.filter(":visible")),e.length&&(t.each(["first","last"],function(t,s){var n=e[s]().data("ui-controlgroup-data");if(n&&i["_"+n.widgetName+"Options"]){var a=i["_"+n.widgetName+"Options"](1===e.length?"only":s);a.classes=i._resolveClassesValues(a.classes,n),n.element[n.widgetName](a)}else i._updateCornerClass(e[s](),s)}),this._callChildMethod("refresh"))}}),t.widget("ui.checkboxradio",[t.ui.formResetMixin,{version:"1.12.1",options:{disabled:null,label:null,icon:!0,classes:{"ui-checkboxradio-label":"ui-corner-all","ui-checkboxradio-icon":"ui-corner-all"}},_getCreateOptions:function(){var e,i,s=this,n=this._super()||{};return this._readType(),i=this.element.labels(),this.label=t(i[i.length-1]),this.label.length||t.error("No label found for checkboxradio widget"),this.originalLabel="",this.label.contents().not(this.element[0]).each(function(){s.originalLabel+=3===this.nodeType?t(this).text():this.outerHTML}),this.originalLabel&&(n.label=this.originalLabel),e=this.element[0].disabled,null!=e&&(n.disabled=e),n},_create:function(){var t=this.element[0].checked;this._bindFormResetHandler(),null==this.options.disabled&&(this.options.disabled=this.element[0].disabled),this._setOption("disabled",this.options.disabled),this._addClass("ui-checkboxradio","ui-helper-hidden-accessible"),this._addClass(this.label,"ui-checkboxradio-label","ui-button ui-widget"),"radio"===this.type&&this._addClass(this.label,"ui-checkboxradio-radio-label"),this.options.label&&this.options.label!==this.originalLabel?this._updateLabel():this.originalLabel&&(this.options.label=this.originalLabel),this._enhance(),t&&(this._addClass(this.label,"ui-checkboxradio-checked","ui-state-active"),this.icon&&this._addClass(this.icon,null,"ui-state-hover")),this._on({change:"_toggleClasses",focus:function(){this._addClass(this.label,null,"ui-state-focus ui-visual-focus")},blur:function(){this._removeClass(this.label,null,"ui-state-focus ui-visual-focus")}})},_readType:function(){var e=this.element[0].nodeName.toLowerCase();this.type=this.element[0].type,"input"===e&&/radio|checkbox/.test(this.type)||t.error("Can't create checkboxradio on element.nodeName="+e+" and element.type="+this.type)},_enhance:function(){this._updateIcon(this.element[0].checked)},widget:function(){return this.label},_getRadioGroup:function(){var e,i=this.element[0].name,s="input[name='"+t.ui.escapeSelector(i)+"']";return i?(e=this.form.length?t(this.form[0].elements).filter(s):t(s).filter(function(){return 0===t(this).form().length}),e.not(this.element)):t([])},_toggleClasses:function(){var e=this.element[0].checked;this._toggleClass(this.label,"ui-checkboxradio-checked","ui-state-active",e),this.options.icon&&"checkbox"===this.type&&this._toggleClass(this.icon,null,"ui-icon-check ui-state-checked",e)._toggleClass(this.icon,null,"ui-icon-blank",!e),"radio"===this.type&&this._getRadioGroup().each(function(){var e=t(this).checkboxradio("instance");e&&e._removeClass(e.label,"ui-checkboxradio-checked","ui-state-active")})},_destroy:function(){this._unbindFormResetHandler(),this.icon&&(this.icon.remove(),this.iconSpace.remove())},_setOption:function(t,e){return"label"!==t||e?(this._super(t,e),"disabled"===t?(this._toggleClass(this.label,null,"ui-state-disabled",e),this.element[0].disabled=e,void 0):(this.refresh(),void 0)):void 0},_updateIcon:function(e){var i="ui-icon ui-icon-background ";this.options.icon?(this.icon||(this.icon=t("<span>"),this.iconSpace=t("<span> </span>"),this._addClass(this.iconSpace,"ui-checkboxradio-icon-space")),"checkbox"===this.type?(i+=e?"ui-icon-check ui-state-checked":"ui-icon-blank",this._removeClass(this.icon,null,e?"ui-icon-blank":"ui-icon-check")):i+="ui-icon-blank",this._addClass(this.icon,"ui-checkboxradio-icon",i),e||this._removeClass(this.icon,null,"ui-icon-check ui-state-checked"),this.icon.prependTo(this.label).after(this.iconSpace)):void 0!==this.icon&&(this.icon.remove(),this.iconSpace.remove(),delete this.icon)},_updateLabel:function(){var t=this.label.contents().not(this.element[0]);this.icon&&(t=t.not(this.icon[0])),this.iconSpace&&(t=t.not(this.iconSpace[0])),t.remove(),this.label.append(this.options.label)},refresh:function(){var t=this.element[0].checked,e=this.element[0].disabled;this._updateIcon(t),this._toggleClass(this.label,"ui-checkboxradio-checked","ui-state-active",t),null!==this.options.label&&this._updateLabel(),e!==this.options.disabled&&this._setOptions({disabled:e})}}]),t.ui.checkboxradio,t.widget("ui.button",{version:"1.12.1",defaultElement:"<button>",options:{classes:{"ui-button":"ui-corner-all"},disabled:null,icon:null,iconPosition:"beginning",label:null,showLabel:!0},_getCreateOptions:function(){var t,e=this._super()||{};return this.isInput=this.element.is("input"),t=this.element[0].disabled,null!=t&&(e.disabled=t),this.originalLabel=this.isInput?this.element.val():this.element.html(),this.originalLabel&&(e.label=this.originalLabel),e},_create:function(){!this.option.showLabel&!this.options.icon&&(this.options.showLabel=!0),null==this.options.disabled&&(this.options.disabled=this.element[0].disabled||!1),this.hasTitle=!!this.element.attr("title"),this.options.label&&this.options.label!==this.originalLabel&&(this.isInput?this.element.val(this.options.label):this.element.html(this.options.label)),this._addClass("ui-button","ui-widget"),this._setOption("disabled",this.options.disabled),this._enhance(),this.element.is("a")&&this._on({keyup:function(e){e.keyCode===t.ui.keyCode.SPACE&&(e.preventDefault(),this.element[0].click?this.element[0].click():this.element.trigger("click"))}})},_enhance:function(){this.element.is("button")||this.element.attr("role","button"),this.options.icon&&(this._updateIcon("icon",this.options.icon),this._updateTooltip())},_updateTooltip:function(){this.title=this.element.attr("title"),this.options.showLabel||this.title||this.element.attr("title",this.options.label)},_updateIcon:function(e,i){var s="iconPosition"!==e,n=s?this.options.iconPosition:i,a="top"===n||"bottom"===n;this.icon?s&&this._removeClass(this.icon,null,this.options.icon):(this.icon=t("<span>"),this._addClass(this.icon,"ui-button-icon","ui-icon"),this.options.showLabel||this._addClass("ui-button-icon-only")),s&&this._addClass(this.icon,null,i),this._attachIcon(n),a?(this._addClass(this.icon,null,"ui-widget-icon-block"),this.iconSpace&&this.iconSpace.remove()):(this.iconSpace||(this.iconSpace=t("<span> </span>"),this._addClass(this.iconSpace,"ui-button-icon-space")),this._removeClass(this.icon,null,"ui-wiget-icon-block"),this._attachIconSpace(n))},_destroy:function(){this.element.removeAttr("role"),this.icon&&this.icon.remove(),this.iconSpace&&this.iconSpace.remove(),this.hasTitle||this.element.removeAttr("title")},_attachIconSpace:function(t){this.icon[/^(?:end|bottom)/.test(t)?"before":"after"](this.iconSpace)},_attachIcon:function(t){this.element[/^(?:end|bottom)/.test(t)?"append":"prepend"](this.icon)},_setOptions:function(t){var e=void 0===t.showLabel?this.options.showLabel:t.showLabel,i=void 0===t.icon?this.options.icon:t.icon;e||i||(t.showLabel=!0),this._super(t)},_setOption:function(t,e){"icon"===t&&(e?this._updateIcon(t,e):this.icon&&(this.icon.remove(),this.iconSpace&&this.iconSpace.remove())),"iconPosition"===t&&this._updateIcon(t,e),"showLabel"===t&&(this._toggleClass("ui-button-icon-only",null,!e),this._updateTooltip()),"label"===t&&(this.isInput?this.element.val(e):(this.element.html(e),this.icon&&(this._attachIcon(this.options.iconPosition),this._attachIconSpace(this.options.iconPosition)))),this._super(t,e),"disabled"===t&&(this._toggleClass(null,"ui-state-disabled",e),this.element[0].disabled=e,e&&this.element.blur())},refresh:function(){var t=this.element.is("input, button")?this.element[0].disabled:this.element.hasClass("ui-button-disabled");t!==this.options.disabled&&this._setOptions({disabled:t}),this._updateTooltip()}}),t.uiBackCompat!==!1&&(t.widget("ui.button",t.ui.button,{options:{text:!0,icons:{primary:null,secondary:null}},_create:function(){this.options.showLabel&&!this.options.text&&(this.options.showLabel=this.options.text),!this.options.showLabel&&this.options.text&&(this.options.text=this.options.showLabel),this.options.icon||!this.options.icons.primary&&!this.options.icons.secondary?this.options.icon&&(this.options.icons.primary=this.options.icon):this.options.icons.primary?this.options.icon=this.options.icons.primary:(this.options.icon=this.options.icons.secondary,this.options.iconPosition="end"),this._super()},_setOption:function(t,e){return"text"===t?(this._super("showLabel",e),void 0):("showLabel"===t&&(this.options.text=e),"icon"===t&&(this.options.icons.primary=e),"icons"===t&&(e.primary?(this._super("icon",e.primary),this._super("iconPosition","beginning")):e.secondary&&(this._super("icon",e.secondary),this._super("iconPosition","end"))),this._superApply(arguments),void 0)}}),t.fn.button=function(e){return function(){return!this.length||this.length&&"INPUT"!==this[0].tagName||this.length&&"INPUT"===this[0].tagName&&"checkbox"!==this.attr("type")&&"radio"!==this.attr("type")?e.apply(this,arguments):(t.ui.checkboxradio||t.error("Checkboxradio widget missing"),0===arguments.length?this.checkboxradio({icon:!1}):this.checkboxradio.apply(this,arguments))}}(t.fn.button),t.fn.buttonset=function(){return t.ui.controlgroup||t.error("Controlgroup widget missing"),"option"===arguments[0]&&"items"===arguments[1]&&arguments[2]?this.controlgroup.apply(this,[arguments[0],"items.button",arguments[2]]):"option"===arguments[0]&&"items"===arguments[1]?this.controlgroup.apply(this,[arguments[0],"items.button"]):("object"==typeof arguments[0]&&arguments[0].items&&(arguments[0].items={button:arguments[0].items}),this.controlgroup.apply(this,arguments))}),t.ui.button,t.extend(t.ui,{datepicker:{version:"1.12.1"}});var p;t.extend(s.prototype,{markerClassName:"hasDatepicker",maxRows:4,_widgetDatepicker:function(){return this.dpDiv},setDefaults:function(t){return o(this._defaults,t||{}),this},_attachDatepicker:function(e,i){var s,n,a;s=e.nodeName.toLowerCase(),n="div"===s||"span"===s,e.id||(this.uuid+=1,e.id="dp"+this.uuid),a=this._newInst(t(e),n),a.settings=t.extend({},i||{}),"input"===s?this._connectDatepicker(e,a):n&&this._inlineDatepicker(e,a)},_newInst:function(e,i){var s=e[0].id.replace(/([^A-Za-z0-9_\-])/g,"\\\\$1");return{id:s,input:e,selectedDay:0,selectedMonth:0,selectedYear:0,drawMonth:0,drawYear:0,inline:i,dpDiv:i?n(t("<div class='"+this._inlineClass+" ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")):this.dpDiv}},_connectDatepicker:function(e,i){var s=t(e);i.append=t([]),i.trigger=t([]),s.hasClass(this.markerClassName)||(this._attachments(s,i),s.addClass(this.markerClassName).on("keydown",this._doKeyDown).on("keypress",this._doKeyPress).on("keyup",this._doKeyUp),this._autoSize(i),t.data(e,"datepicker",i),i.settings.disabled&&this._disableDatepicker(e))},_attachments:function(e,i){var s,n,a,o=this._get(i,"appendText"),r=this._get(i,"isRTL");i.append&&i.append.remove(),o&&(i.append=t("<span class='"+this._appendClass+"'>"+o+"</span>"),e[r?"before":"after"](i.append)),e.off("focus",this._showDatepicker),i.trigger&&i.trigger.remove(),s=this._get(i,"showOn"),("focus"===s||"both"===s)&&e.on("focus",this._showDatepicker),("button"===s||"both"===s)&&(n=this._get(i,"buttonText"),a=this._get(i,"buttonImage"),i.trigger=t(this._get(i,"buttonImageOnly")?t("<img/>").addClass(this._triggerClass).attr({src:a,alt:n,title:n}):t("<button type='button'></button>").addClass(this._triggerClass).html(a?t("<img/>").attr({src:a,alt:n,title:n}):n)),e[r?"before":"after"](i.trigger),i.trigger.on("click",function(){return t.datepicker._datepickerShowing&&t.datepicker._lastInput===e[0]?t.datepicker._hideDatepicker():t.datepicker._datepickerShowing&&t.datepicker._lastInput!==e[0]?(t.datepicker._hideDatepicker(),t.datepicker._showDatepicker(e[0])):t.datepicker._showDatepicker(e[0]),!1}))},_autoSize:function(t){if(this._get(t,"autoSize")&&!t.inline){var e,i,s,n,a=new Date(2009,11,20),o=this._get(t,"dateFormat");o.match(/[DM]/)&&(e=function(t){for(i=0,s=0,n=0;t.length>n;n++)t[n].length>i&&(i=t[n].length,s=n);return s},a.setMonth(e(this._get(t,o.match(/MM/)?"monthNames":"monthNamesShort"))),a.setDate(e(this._get(t,o.match(/DD/)?"dayNames":"dayNamesShort"))+20-a.getDay())),t.input.attr("size",this._formatDate(t,a).length)}},_inlineDatepicker:function(e,i){var s=t(e);s.hasClass(this.markerClassName)||(s.addClass(this.markerClassName).append(i.dpDiv),t.data(e,"datepicker",i),this._setDate(i,this._getDefaultDate(i),!0),this._updateDatepicker(i),this._updateAlternate(i),i.settings.disabled&&this._disableDatepicker(e),i.dpDiv.css("display","block"))},_dialogDatepicker:function(e,i,s,n,a){var r,h,l,u,c,d=this._dialogInst;return d||(this.uuid+=1,r="dp"+this.uuid,this._dialogInput=t("<input type='text' id='"+r+"' style='position: absolute; top: -100px; width: 0px;'/>"),this._dialogInput.on("keydown",this._doKeyDown),t("body").append(this._dialogInput),d=this._dialogInst=this._newInst(this._dialogInput,!1),d.settings={},t.data(this._dialogInput[0],"datepicker",d)),o(d.settings,n||{}),i=i&&i.constructor===Date?this._formatDate(d,i):i,this._dialogInput.val(i),this._pos=a?a.length?a:[a.pageX,a.pageY]:null,this._pos||(h=document.documentElement.clientWidth,l=document.documentElement.clientHeight,u=document.documentElement.scrollLeft||document.body.scrollLeft,c=document.documentElement.scrollTop||document.body.scrollTop,this._pos=[h/2-100+u,l/2-150+c]),this._dialogInput.css("left",this._pos[0]+20+"px").css("top",this._pos[1]+"px"),d.settings.onSelect=s,this._inDialog=!0,this.dpDiv.addClass(this._dialogClass),this._showDatepicker(this._dialogInput[0]),t.blockUI&&t.blockUI(this.dpDiv),t.data(this._dialogInput[0],"datepicker",d),this},_destroyDatepicker:function(e){var i,s=t(e),n=t.data(e,"datepicker");s.hasClass(this.markerClassName)&&(i=e.nodeName.toLowerCase(),t.removeData(e,"datepicker"),"input"===i?(n.append.remove(),n.trigger.remove(),s.removeClass(this.markerClassName).off("focus",this._showDatepicker).off("keydown",this._doKeyDown).off("keypress",this._doKeyPress).off("keyup",this._doKeyUp)):("div"===i||"span"===i)&&s.removeClass(this.markerClassName).empty(),p===n&&(p=null))},_enableDatepicker:function(e){var i,s,n=t(e),a=t.data(e,"datepicker");n.hasClass(this.markerClassName)&&(i=e.nodeName.toLowerCase(),"input"===i?(e.disabled=!1,a.trigger.filter("button").each(function(){this.disabled=!1}).end().filter("img").css({opacity:"1.0",cursor:""})):("div"===i||"span"===i)&&(s=n.children("."+this._inlineClass),s.children().removeClass("ui-state-disabled"),s.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!1)),this._disabledInputs=t.map(this._disabledInputs,function(t){return t===e?null:t}))},_disableDatepicker:function(e){var i,s,n=t(e),a=t.data(e,"datepicker");n.hasClass(this.markerClassName)&&(i=e.nodeName.toLowerCase(),"input"===i?(e.disabled=!0,a.trigger.filter("button").each(function(){this.disabled=!0}).end().filter("img").css({opacity:"0.5",cursor:"default"})):("div"===i||"span"===i)&&(s=n.children("."+this._inlineClass),s.children().addClass("ui-state-disabled"),s.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!0)),this._disabledInputs=t.map(this._disabledInputs,function(t){return t===e?null:t}),this._disabledInputs[this._disabledInputs.length]=e)},_isDisabledDatepicker:function(t){if(!t)return!1;for(var e=0;this._disabledInputs.length>e;e++)if(this._disabledInputs[e]===t)return!0;return!1},_getInst:function(e){try{return t.data(e,"datepicker")}catch(i){throw"Missing instance data for this datepicker"}},_optionDatepicker:function(e,i,s){var n,a,r,h,l=this._getInst(e);return 2===arguments.length&&"string"==typeof i?"defaults"===i?t.extend({},t.datepicker._defaults):l?"all"===i?t.extend({},l.settings):this._get(l,i):null:(n=i||{},"string"==typeof i&&(n={},n[i]=s),l&&(this._curInst===l&&this._hideDatepicker(),a=this._getDateDatepicker(e,!0),r=this._getMinMaxDate(l,"min"),h=this._getMinMaxDate(l,"max"),o(l.settings,n),null!==r&&void 0!==n.dateFormat&&void 0===n.minDate&&(l.settings.minDate=this._formatDate(l,r)),null!==h&&void 0!==n.dateFormat&&void 0===n.maxDate&&(l.settings.maxDate=this._formatDate(l,h)),"disabled"in n&&(n.disabled?this._disableDatepicker(e):this._enableDatepicker(e)),this._attachments(t(e),l),this._autoSize(l),this._setDate(l,a),this._updateAlternate(l),this._updateDatepicker(l)),void 0)},_changeDatepicker:function(t,e,i){this._optionDatepicker(t,e,i)},_refreshDatepicker:function(t){var e=this._getInst(t);e&&this._updateDatepicker(e)},_setDateDatepicker:function(t,e){var i=this._getInst(t);i&&(this._setDate(i,e),this._updateDatepicker(i),this._updateAlternate(i))},_getDateDatepicker:function(t,e){var i=this._getInst(t);return i&&!i.inline&&this._setDateFromField(i,e),i?this._getDate(i):null},_doKeyDown:function(e){var i,s,n,a=t.datepicker._getInst(e.target),o=!0,r=a.dpDiv.is(".ui-datepicker-rtl");if(a._keyEvent=!0,t.datepicker._datepickerShowing)switch(e.keyCode){case 9:t.datepicker._hideDatepicker(),o=!1;break;case 13:return n=t("td."+t.datepicker._dayOverClass+":not(."+t.datepicker._currentClass+")",a.dpDiv),n[0]&&t.datepicker._selectDay(e.target,a.selectedMonth,a.selectedYear,n[0]),i=t.datepicker._get(a,"onSelect"),i?(s=t.datepicker._formatDate(a),i.apply(a.input?a.input[0]:null,[s,a])):t.datepicker._hideDatepicker(),!1;case 27:t.datepicker._hideDatepicker();break;case 33:t.datepicker._adjustDate(e.target,e.ctrlKey?-t.datepicker._get(a,"stepBigMonths"):-t.datepicker._get(a,"stepMonths"),"M");break;case 34:t.datepicker._adjustDate(e.target,e.ctrlKey?+t.datepicker._get(a,"stepBigMonths"):+t.datepicker._get(a,"stepMonths"),"M");break;case 35:(e.ctrlKey||e.metaKey)&&t.datepicker._clearDate(e.target),o=e.ctrlKey||e.metaKey;break;case 36:(e.ctrlKey||e.metaKey)&&t.datepicker._gotoToday(e.target),o=e.ctrlKey||e.metaKey;break;case 37:(e.ctrlKey||e.metaKey)&&t.datepicker._adjustDate(e.target,r?1:-1,"D"),o=e.ctrlKey||e.metaKey,e.originalEvent.altKey&&t.datepicker._adjustDate(e.target,e.ctrlKey?-t.datepicker._get(a,"stepBigMonths"):-t.datepicker._get(a,"stepMonths"),"M");break;case 38:(e.ctrlKey||e.metaKey)&&t.datepicker._adjustDate(e.target,-7,"D"),o=e.ctrlKey||e.metaKey;break;case 39:(e.ctrlKey||e.metaKey)&&t.datepicker._adjustDate(e.target,r?-1:1,"D"),o=e.ctrlKey||e.metaKey,e.originalEvent.altKey&&t.datepicker._adjustDate(e.target,e.ctrlKey?+t.datepicker._get(a,"stepBigMonths"):+t.datepicker._get(a,"stepMonths"),"M");break;case 40:(e.ctrlKey||e.metaKey)&&t.datepicker._adjustDate(e.target,7,"D"),o=e.ctrlKey||e.metaKey;break;default:o=!1}else 36===e.keyCode&&e.ctrlKey?t.datepicker._showDatepicker(this):o=!1;o&&(e.preventDefault(),e.stopPropagation())},_doKeyPress:function(e){var i,s,n=t.datepicker._getInst(e.target);return t.datepicker._get(n,"constrainInput")?(i=t.datepicker._possibleChars(t.datepicker._get(n,"dateFormat")),s=String.fromCharCode(null==e.charCode?e.keyCode:e.charCode),e.ctrlKey||e.metaKey||" ">s||!i||i.indexOf(s)>-1):void 0},_doKeyUp:function(e){var i,s=t.datepicker._getInst(e.target);if(s.input.val()!==s.lastVal)try{i=t.datepicker.parseDate(t.datepicker._get(s,"dateFormat"),s.input?s.input.val():null,t.datepicker._getFormatConfig(s)),i&&(t.datepicker._setDateFromField(s),t.datepicker._updateAlternate(s),t.datepicker._updateDatepicker(s))}catch(n){}return!0},_showDatepicker:function(e){if(e=e.target||e,"input"!==e.nodeName.toLowerCase()&&(e=t("input",e.parentNode)[0]),!t.datepicker._isDisabledDatepicker(e)&&t.datepicker._lastInput!==e){var s,n,a,r,h,l,u;s=t.datepicker._getInst(e),t.datepicker._curInst&&t.datepicker._curInst!==s&&(t.datepicker._curInst.dpDiv.stop(!0,!0),s&&t.datepicker._datepickerShowing&&t.datepicker._hideDatepicker(t.datepicker._curInst.input[0])),n=t.datepicker._get(s,"beforeShow"),a=n?n.apply(e,[e,s]):{},a!==!1&&(o(s.settings,a),s.lastVal=null,t.datepicker._lastInput=e,t.datepicker._setDateFromField(s),t.datepicker._inDialog&&(e.value=""),t.datepicker._pos||(t.datepicker._pos=t.datepicker._findPos(e),t.datepicker._pos[1]+=e.offsetHeight),r=!1,t(e).parents().each(function(){return r|="fixed"===t(this).css("position"),!r}),h={left:t.datepicker._pos[0],top:t.datepicker._pos[1]},t.datepicker._pos=null,s.dpDiv.empty(),s.dpDiv.css({position:"absolute",display:"block",top:"-1000px"}),t.datepicker._updateDatepicker(s),h=t.datepicker._checkOffset(s,h,r),s.dpDiv.css({position:t.datepicker._inDialog&&t.blockUI?"static":r?"fixed":"absolute",display:"none",left:h.left+"px",top:h.top+"px"}),s.inline||(l=t.datepicker._get(s,"showAnim"),u=t.datepicker._get(s,"duration"),s.dpDiv.css("z-index",i(t(e))+1),t.datepicker._datepickerShowing=!0,t.effects&&t.effects.effect[l]?s.dpDiv.show(l,t.datepicker._get(s,"showOptions"),u):s.dpDiv[l||"show"](l?u:null),t.datepicker._shouldFocusInput(s)&&s.input.trigger("focus"),t.datepicker._curInst=s))}},_updateDatepicker:function(e){this.maxRows=4,p=e,e.dpDiv.empty().append(this._generateHTML(e)),this._attachHandlers(e);var i,s=this._getNumberOfMonths(e),n=s[1],o=17,r=e.dpDiv.find("."+this._dayOverClass+" a");r.length>0&&a.apply(r.get(0)),e.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width(""),n>1&&e.dpDiv.addClass("ui-datepicker-multi-"+n).css("width",o*n+"em"),e.dpDiv[(1!==s[0]||1!==s[1]?"add":"remove")+"Class"]("ui-datepicker-multi"),e.dpDiv[(this._get(e,"isRTL")?"add":"remove")+"Class"]("ui-datepicker-rtl"),e===t.datepicker._curInst&&t.datepicker._datepickerShowing&&t.datepicker._shouldFocusInput(e)&&e.input.trigger("focus"),e.yearshtml&&(i=e.yearshtml,setTimeout(function(){i===e.yearshtml&&e.yearshtml&&e.dpDiv.find("select.ui-datepicker-year:first").replaceWith(e.yearshtml),i=e.yearshtml=null },0))},_shouldFocusInput:function(t){return t.input&&t.input.is(":visible")&&!t.input.is(":disabled")&&!t.input.is(":focus")},_checkOffset:function(e,i,s){var n=e.dpDiv.outerWidth(),a=e.dpDiv.outerHeight(),o=e.input?e.input.outerWidth():0,r=e.input?e.input.outerHeight():0,h=document.documentElement.clientWidth+(s?0:t(document).scrollLeft()),l=document.documentElement.clientHeight+(s?0:t(document).scrollTop());return i.left-=this._get(e,"isRTL")?n-o:0,i.left-=s&&i.left===e.input.offset().left?t(document).scrollLeft():0,i.top-=s&&i.top===e.input.offset().top+r?t(document).scrollTop():0,i.left-=Math.min(i.left,i.left+n>h&&h>n?Math.abs(i.left+n-h):0),i.top-=Math.min(i.top,i.top+a>l&&l>a?Math.abs(a+r):0),i},_findPos:function(e){for(var i,s=this._getInst(e),n=this._get(s,"isRTL");e&&("hidden"===e.type||1!==e.nodeType||t.expr.filters.hidden(e));)e=e[n?"previousSibling":"nextSibling"];return i=t(e).offset(),[i.left,i.top]},_hideDatepicker:function(e){var i,s,n,a,o=this._curInst;!o||e&&o!==t.data(e,"datepicker")||this._datepickerShowing&&(i=this._get(o,"showAnim"),s=this._get(o,"duration"),n=function(){t.datepicker._tidyDialog(o)},t.effects&&(t.effects.effect[i]||t.effects[i])?o.dpDiv.hide(i,t.datepicker._get(o,"showOptions"),s,n):o.dpDiv["slideDown"===i?"slideUp":"fadeIn"===i?"fadeOut":"hide"](i?s:null,n),i||n(),this._datepickerShowing=!1,a=this._get(o,"onClose"),a&&a.apply(o.input?o.input[0]:null,[o.input?o.input.val():"",o]),this._lastInput=null,this._inDialog&&(this._dialogInput.css({position:"absolute",left:"0",top:"-100px"}),t.blockUI&&(t.unblockUI(),t("body").append(this.dpDiv))),this._inDialog=!1)},_tidyDialog:function(t){t.dpDiv.removeClass(this._dialogClass).off(".ui-datepicker-calendar")},_checkExternalClick:function(e){if(t.datepicker._curInst){var i=t(e.target),s=t.datepicker._getInst(i[0]);(i[0].id!==t.datepicker._mainDivId&&0===i.parents("#"+t.datepicker._mainDivId).length&&!i.hasClass(t.datepicker.markerClassName)&&!i.closest("."+t.datepicker._triggerClass).length&&t.datepicker._datepickerShowing&&(!t.datepicker._inDialog||!t.blockUI)||i.hasClass(t.datepicker.markerClassName)&&t.datepicker._curInst!==s)&&t.datepicker._hideDatepicker()}},_adjustDate:function(e,i,s){var n=t(e),a=this._getInst(n[0]);this._isDisabledDatepicker(n[0])||(this._adjustInstDate(a,i+("M"===s?this._get(a,"showCurrentAtPos"):0),s),this._updateDatepicker(a))},_gotoToday:function(e){var i,s=t(e),n=this._getInst(s[0]);this._get(n,"gotoCurrent")&&n.currentDay?(n.selectedDay=n.currentDay,n.drawMonth=n.selectedMonth=n.currentMonth,n.drawYear=n.selectedYear=n.currentYear):(i=new Date,n.selectedDay=i.getDate(),n.drawMonth=n.selectedMonth=i.getMonth(),n.drawYear=n.selectedYear=i.getFullYear()),this._notifyChange(n),this._adjustDate(s)},_selectMonthYear:function(e,i,s){var n=t(e),a=this._getInst(n[0]);a["selected"+("M"===s?"Month":"Year")]=a["draw"+("M"===s?"Month":"Year")]=parseInt(i.options[i.selectedIndex].value,10),this._notifyChange(a),this._adjustDate(n)},_selectDay:function(e,i,s,n){var a,o=t(e);t(n).hasClass(this._unselectableClass)||this._isDisabledDatepicker(o[0])||(a=this._getInst(o[0]),a.selectedDay=a.currentDay=t("a",n).html(),a.selectedMonth=a.currentMonth=i,a.selectedYear=a.currentYear=s,this._selectDate(e,this._formatDate(a,a.currentDay,a.currentMonth,a.currentYear)))},_clearDate:function(e){var i=t(e);this._selectDate(i,"")},_selectDate:function(e,i){var s,n=t(e),a=this._getInst(n[0]);i=null!=i?i:this._formatDate(a),a.input&&a.input.val(i),this._updateAlternate(a),s=this._get(a,"onSelect"),s?s.apply(a.input?a.input[0]:null,[i,a]):a.input&&a.input.trigger("change"),a.inline?this._updateDatepicker(a):(this._hideDatepicker(),this._lastInput=a.input[0],"object"!=typeof a.input[0]&&a.input.trigger("focus"),this._lastInput=null)},_updateAlternate:function(e){var i,s,n,a=this._get(e,"altField");a&&(i=this._get(e,"altFormat")||this._get(e,"dateFormat"),s=this._getDate(e),n=this.formatDate(i,s,this._getFormatConfig(e)),t(a).val(n))},noWeekends:function(t){var e=t.getDay();return[e>0&&6>e,""]},iso8601Week:function(t){var e,i=new Date(t.getTime());return i.setDate(i.getDate()+4-(i.getDay()||7)),e=i.getTime(),i.setMonth(0),i.setDate(1),Math.floor(Math.round((e-i)/864e5)/7)+1},parseDate:function(e,i,s){if(null==e||null==i)throw"Invalid arguments";if(i="object"==typeof i?""+i:i+"",""===i)return null;var n,a,o,r,h=0,l=(s?s.shortYearCutoff:null)||this._defaults.shortYearCutoff,u="string"!=typeof l?l:(new Date).getFullYear()%100+parseInt(l,10),c=(s?s.dayNamesShort:null)||this._defaults.dayNamesShort,d=(s?s.dayNames:null)||this._defaults.dayNames,p=(s?s.monthNamesShort:null)||this._defaults.monthNamesShort,f=(s?s.monthNames:null)||this._defaults.monthNames,m=-1,g=-1,_=-1,v=-1,b=!1,y=function(t){var i=e.length>n+1&&e.charAt(n+1)===t;return i&&n++,i},w=function(t){var e=y(t),s="@"===t?14:"!"===t?20:"y"===t&&e?4:"o"===t?3:2,n="y"===t?s:1,a=RegExp("^\\d{"+n+","+s+"}"),o=i.substring(h).match(a);if(!o)throw"Missing number at position "+h;return h+=o[0].length,parseInt(o[0],10)},k=function(e,s,n){var a=-1,o=t.map(y(e)?n:s,function(t,e){return[[e,t]]}).sort(function(t,e){return-(t[1].length-e[1].length)});if(t.each(o,function(t,e){var s=e[1];return i.substr(h,s.length).toLowerCase()===s.toLowerCase()?(a=e[0],h+=s.length,!1):void 0}),-1!==a)return a+1;throw"Unknown name at position "+h},x=function(){if(i.charAt(h)!==e.charAt(n))throw"Unexpected literal at position "+h;h++};for(n=0;e.length>n;n++)if(b)"'"!==e.charAt(n)||y("'")?x():b=!1;else switch(e.charAt(n)){case"d":_=w("d");break;case"D":k("D",c,d);break;case"o":v=w("o");break;case"m":g=w("m");break;case"M":g=k("M",p,f);break;case"y":m=w("y");break;case"@":r=new Date(w("@")),m=r.getFullYear(),g=r.getMonth()+1,_=r.getDate();break;case"!":r=new Date((w("!")-this._ticksTo1970)/1e4),m=r.getFullYear(),g=r.getMonth()+1,_=r.getDate();break;case"'":y("'")?x():b=!0;break;default:x()}if(i.length>h&&(o=i.substr(h),!/^\s+/.test(o)))throw"Extra/unparsed characters found in date: "+o;if(-1===m?m=(new Date).getFullYear():100>m&&(m+=(new Date).getFullYear()-(new Date).getFullYear()%100+(u>=m?0:-100)),v>-1)for(g=1,_=v;;){if(a=this._getDaysInMonth(m,g-1),a>=_)break;g++,_-=a}if(r=this._daylightSavingAdjust(new Date(m,g-1,_)),r.getFullYear()!==m||r.getMonth()+1!==g||r.getDate()!==_)throw"Invalid date";return r},ATOM:"yy-mm-dd",COOKIE:"D, dd M yy",ISO_8601:"yy-mm-dd",RFC_822:"D, d M y",RFC_850:"DD, dd-M-y",RFC_1036:"D, d M y",RFC_1123:"D, d M yy",RFC_2822:"D, d M yy",RSS:"D, d M y",TICKS:"!",TIMESTAMP:"@",W3C:"yy-mm-dd",_ticksTo1970:1e7*60*60*24*(718685+Math.floor(492.5)-Math.floor(19.7)+Math.floor(4.925)),formatDate:function(t,e,i){if(!e)return"";var s,n=(i?i.dayNamesShort:null)||this._defaults.dayNamesShort,a=(i?i.dayNames:null)||this._defaults.dayNames,o=(i?i.monthNamesShort:null)||this._defaults.monthNamesShort,r=(i?i.monthNames:null)||this._defaults.monthNames,h=function(e){var i=t.length>s+1&&t.charAt(s+1)===e;return i&&s++,i},l=function(t,e,i){var s=""+e;if(h(t))for(;i>s.length;)s="0"+s;return s},u=function(t,e,i,s){return h(t)?s[e]:i[e]},c="",d=!1;if(e)for(s=0;t.length>s;s++)if(d)"'"!==t.charAt(s)||h("'")?c+=t.charAt(s):d=!1;else switch(t.charAt(s)){case"d":c+=l("d",e.getDate(),2);break;case"D":c+=u("D",e.getDay(),n,a);break;case"o":c+=l("o",Math.round((new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime()-new Date(e.getFullYear(),0,0).getTime())/864e5),3);break;case"m":c+=l("m",e.getMonth()+1,2);break;case"M":c+=u("M",e.getMonth(),o,r);break;case"y":c+=h("y")?e.getFullYear():(10>e.getFullYear()%100?"0":"")+e.getFullYear()%100;break;case"@":c+=e.getTime();break;case"!":c+=1e4*e.getTime()+this._ticksTo1970;break;case"'":h("'")?c+="'":d=!0;break;default:c+=t.charAt(s)}return c},_possibleChars:function(t){var e,i="",s=!1,n=function(i){var s=t.length>e+1&&t.charAt(e+1)===i;return s&&e++,s};for(e=0;t.length>e;e++)if(s)"'"!==t.charAt(e)||n("'")?i+=t.charAt(e):s=!1;else switch(t.charAt(e)){case"d":case"m":case"y":case"@":i+="0123456789";break;case"D":case"M":return null;case"'":n("'")?i+="'":s=!0;break;default:i+=t.charAt(e)}return i},_get:function(t,e){return void 0!==t.settings[e]?t.settings[e]:this._defaults[e]},_setDateFromField:function(t,e){if(t.input.val()!==t.lastVal){var i=this._get(t,"dateFormat"),s=t.lastVal=t.input?t.input.val():null,n=this._getDefaultDate(t),a=n,o=this._getFormatConfig(t);try{a=this.parseDate(i,s,o)||n}catch(r){s=e?"":s}t.selectedDay=a.getDate(),t.drawMonth=t.selectedMonth=a.getMonth(),t.drawYear=t.selectedYear=a.getFullYear(),t.currentDay=s?a.getDate():0,t.currentMonth=s?a.getMonth():0,t.currentYear=s?a.getFullYear():0,this._adjustInstDate(t)}},_getDefaultDate:function(t){return this._restrictMinMax(t,this._determineDate(t,this._get(t,"defaultDate"),new Date))},_determineDate:function(e,i,s){var n=function(t){var e=new Date;return e.setDate(e.getDate()+t),e},a=function(i){try{return t.datepicker.parseDate(t.datepicker._get(e,"dateFormat"),i,t.datepicker._getFormatConfig(e))}catch(s){}for(var n=(i.toLowerCase().match(/^c/)?t.datepicker._getDate(e):null)||new Date,a=n.getFullYear(),o=n.getMonth(),r=n.getDate(),h=/([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,l=h.exec(i);l;){switch(l[2]||"d"){case"d":case"D":r+=parseInt(l[1],10);break;case"w":case"W":r+=7*parseInt(l[1],10);break;case"m":case"M":o+=parseInt(l[1],10),r=Math.min(r,t.datepicker._getDaysInMonth(a,o));break;case"y":case"Y":a+=parseInt(l[1],10),r=Math.min(r,t.datepicker._getDaysInMonth(a,o))}l=h.exec(i)}return new Date(a,o,r)},o=null==i||""===i?s:"string"==typeof i?a(i):"number"==typeof i?isNaN(i)?s:n(i):new Date(i.getTime());return o=o&&"Invalid Date"==""+o?s:o,o&&(o.setHours(0),o.setMinutes(0),o.setSeconds(0),o.setMilliseconds(0)),this._daylightSavingAdjust(o)},_daylightSavingAdjust:function(t){return t?(t.setHours(t.getHours()>12?t.getHours()+2:0),t):null},_setDate:function(t,e,i){var s=!e,n=t.selectedMonth,a=t.selectedYear,o=this._restrictMinMax(t,this._determineDate(t,e,new Date));t.selectedDay=t.currentDay=o.getDate(),t.drawMonth=t.selectedMonth=t.currentMonth=o.getMonth(),t.drawYear=t.selectedYear=t.currentYear=o.getFullYear(),n===t.selectedMonth&&a===t.selectedYear||i||this._notifyChange(t),this._adjustInstDate(t),t.input&&t.input.val(s?"":this._formatDate(t))},_getDate:function(t){var e=!t.currentYear||t.input&&""===t.input.val()?null:this._daylightSavingAdjust(new Date(t.currentYear,t.currentMonth,t.currentDay));return e},_attachHandlers:function(e){var i=this._get(e,"stepMonths"),s="#"+e.id.replace(/\\\\/g,"\\");e.dpDiv.find("[data-handler]").map(function(){var e={prev:function(){t.datepicker._adjustDate(s,-i,"M")},next:function(){t.datepicker._adjustDate(s,+i,"M")},hide:function(){t.datepicker._hideDatepicker()},today:function(){t.datepicker._gotoToday(s)},selectDay:function(){return t.datepicker._selectDay(s,+this.getAttribute("data-month"),+this.getAttribute("data-year"),this),!1},selectMonth:function(){return t.datepicker._selectMonthYear(s,this,"M"),!1},selectYear:function(){return t.datepicker._selectMonthYear(s,this,"Y"),!1}};t(this).on(this.getAttribute("data-event"),e[this.getAttribute("data-handler")])})},_generateHTML:function(t){var e,i,s,n,a,o,r,h,l,u,c,d,p,f,m,g,_,v,b,y,w,k,x,D,C,T,M,S,I,P,N,A,H,z,O,E,F,W,L,R=new Date,Y=this._daylightSavingAdjust(new Date(R.getFullYear(),R.getMonth(),R.getDate())),j=this._get(t,"isRTL"),B=this._get(t,"showButtonPanel"),K=this._get(t,"hideIfNoPrevNext"),q=this._get(t,"navigationAsDateFormat"),U=this._getNumberOfMonths(t),V=this._get(t,"showCurrentAtPos"),$=this._get(t,"stepMonths"),J=1!==U[0]||1!==U[1],X=this._daylightSavingAdjust(t.currentDay?new Date(t.currentYear,t.currentMonth,t.currentDay):new Date(9999,9,9)),G=this._getMinMaxDate(t,"min"),Q=this._getMinMaxDate(t,"max"),Z=t.drawMonth-V,te=t.drawYear;if(0>Z&&(Z+=12,te--),Q)for(e=this._daylightSavingAdjust(new Date(Q.getFullYear(),Q.getMonth()-U[0]*U[1]+1,Q.getDate())),e=G&&G>e?G:e;this._daylightSavingAdjust(new Date(te,Z,1))>e;)Z--,0>Z&&(Z=11,te--);for(t.drawMonth=Z,t.drawYear=te,i=this._get(t,"prevText"),i=q?this.formatDate(i,this._daylightSavingAdjust(new Date(te,Z-$,1)),this._getFormatConfig(t)):i,s=this._canAdjustMonth(t,-1,te,Z)?"<a class='ui-datepicker-prev ui-corner-all' data-handler='prev' data-event='click' title='"+i+"'><span class='ui-icon ui-icon-circle-triangle-"+(j?"e":"w")+"'>"+i+"</span></a>":K?"":"<a class='ui-datepicker-prev ui-corner-all ui-state-disabled' title='"+i+"'><span class='ui-icon ui-icon-circle-triangle-"+(j?"e":"w")+"'>"+i+"</span></a>",n=this._get(t,"nextText"),n=q?this.formatDate(n,this._daylightSavingAdjust(new Date(te,Z+$,1)),this._getFormatConfig(t)):n,a=this._canAdjustMonth(t,1,te,Z)?"<a class='ui-datepicker-next ui-corner-all' data-handler='next' data-event='click' title='"+n+"'><span class='ui-icon ui-icon-circle-triangle-"+(j?"w":"e")+"'>"+n+"</span></a>":K?"":"<a class='ui-datepicker-next ui-corner-all ui-state-disabled' title='"+n+"'><span class='ui-icon ui-icon-circle-triangle-"+(j?"w":"e")+"'>"+n+"</span></a>",o=this._get(t,"currentText"),r=this._get(t,"gotoCurrent")&&t.currentDay?X:Y,o=q?this.formatDate(o,r,this._getFormatConfig(t)):o,h=t.inline?"":"<button type='button' class='ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all' data-handler='hide' data-event='click'>"+this._get(t,"closeText")+"</button>",l=B?"<div class='ui-datepicker-buttonpane ui-widget-content'>"+(j?h:"")+(this._isInRange(t,r)?"<button type='button' class='ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all' data-handler='today' data-event='click'>"+o+"</button>":"")+(j?"":h)+"</div>":"",u=parseInt(this._get(t,"firstDay"),10),u=isNaN(u)?0:u,c=this._get(t,"showWeek"),d=this._get(t,"dayNames"),p=this._get(t,"dayNamesMin"),f=this._get(t,"monthNames"),m=this._get(t,"monthNamesShort"),g=this._get(t,"beforeShowDay"),_=this._get(t,"showOtherMonths"),v=this._get(t,"selectOtherMonths"),b=this._getDefaultDate(t),y="",k=0;U[0]>k;k++){for(x="",this.maxRows=4,D=0;U[1]>D;D++){if(C=this._daylightSavingAdjust(new Date(te,Z,t.selectedDay)),T=" ui-corner-all",M="",J){if(M+="<div class='ui-datepicker-group",U[1]>1)switch(D){case 0:M+=" ui-datepicker-group-first",T=" ui-corner-"+(j?"right":"left");break;case U[1]-1:M+=" ui-datepicker-group-last",T=" ui-corner-"+(j?"left":"right");break;default:M+=" ui-datepicker-group-middle",T=""}M+="'>"}for(M+="<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix"+T+"'>"+(/all|left/.test(T)&&0===k?j?a:s:"")+(/all|right/.test(T)&&0===k?j?s:a:"")+this._generateMonthYearHeader(t,Z,te,G,Q,k>0||D>0,f,m)+"</div><table class='ui-datepicker-calendar'><thead>"+"<tr>",S=c?"<th class='ui-datepicker-week-col'>"+this._get(t,"weekHeader")+"</th>":"",w=0;7>w;w++)I=(w+u)%7,S+="<th scope='col'"+((w+u+6)%7>=5?" class='ui-datepicker-week-end'":"")+">"+"<span title='"+d[I]+"'>"+p[I]+"</span></th>";for(M+=S+"</tr></thead><tbody>",P=this._getDaysInMonth(te,Z),te===t.selectedYear&&Z===t.selectedMonth&&(t.selectedDay=Math.min(t.selectedDay,P)),N=(this._getFirstDayOfMonth(te,Z)-u+7)%7,A=Math.ceil((N+P)/7),H=J?this.maxRows>A?this.maxRows:A:A,this.maxRows=H,z=this._daylightSavingAdjust(new Date(te,Z,1-N)),O=0;H>O;O++){for(M+="<tr>",E=c?"<td class='ui-datepicker-week-col'>"+this._get(t,"calculateWeek")(z)+"</td>":"",w=0;7>w;w++)F=g?g.apply(t.input?t.input[0]:null,[z]):[!0,""],W=z.getMonth()!==Z,L=W&&!v||!F[0]||G&&G>z||Q&&z>Q,E+="<td class='"+((w+u+6)%7>=5?" ui-datepicker-week-end":"")+(W?" ui-datepicker-other-month":"")+(z.getTime()===C.getTime()&&Z===t.selectedMonth&&t._keyEvent||b.getTime()===z.getTime()&&b.getTime()===C.getTime()?" "+this._dayOverClass:"")+(L?" "+this._unselectableClass+" ui-state-disabled":"")+(W&&!_?"":" "+F[1]+(z.getTime()===X.getTime()?" "+this._currentClass:"")+(z.getTime()===Y.getTime()?" ui-datepicker-today":""))+"'"+(W&&!_||!F[2]?"":" title='"+F[2].replace(/'/g,"&#39;")+"'")+(L?"":" data-handler='selectDay' data-event='click' data-month='"+z.getMonth()+"' data-year='"+z.getFullYear()+"'")+">"+(W&&!_?"&#xa0;":L?"<span class='ui-state-default'>"+z.getDate()+"</span>":"<a class='ui-state-default"+(z.getTime()===Y.getTime()?" ui-state-highlight":"")+(z.getTime()===X.getTime()?" ui-state-active":"")+(W?" ui-priority-secondary":"")+"' href='#'>"+z.getDate()+"</a>")+"</td>",z.setDate(z.getDate()+1),z=this._daylightSavingAdjust(z);M+=E+"</tr>"}Z++,Z>11&&(Z=0,te++),M+="</tbody></table>"+(J?"</div>"+(U[0]>0&&D===U[1]-1?"<div class='ui-datepicker-row-break'></div>":""):""),x+=M}y+=x}return y+=l,t._keyEvent=!1,y},_generateMonthYearHeader:function(t,e,i,s,n,a,o,r){var h,l,u,c,d,p,f,m,g=this._get(t,"changeMonth"),_=this._get(t,"changeYear"),v=this._get(t,"showMonthAfterYear"),b="<div class='ui-datepicker-title'>",y="";if(a||!g)y+="<span class='ui-datepicker-month'>"+o[e]+"</span>";else{for(h=s&&s.getFullYear()===i,l=n&&n.getFullYear()===i,y+="<select class='ui-datepicker-month' data-handler='selectMonth' data-event='change'>",u=0;12>u;u++)(!h||u>=s.getMonth())&&(!l||n.getMonth()>=u)&&(y+="<option value='"+u+"'"+(u===e?" selected='selected'":"")+">"+r[u]+"</option>");y+="</select>"}if(v||(b+=y+(!a&&g&&_?"":"&#xa0;")),!t.yearshtml)if(t.yearshtml="",a||!_)b+="<span class='ui-datepicker-year'>"+i+"</span>";else{for(c=this._get(t,"yearRange").split(":"),d=(new Date).getFullYear(),p=function(t){var e=t.match(/c[+\-].*/)?i+parseInt(t.substring(1),10):t.match(/[+\-].*/)?d+parseInt(t,10):parseInt(t,10);return isNaN(e)?d:e},f=p(c[0]),m=Math.max(f,p(c[1]||"")),f=s?Math.max(f,s.getFullYear()):f,m=n?Math.min(m,n.getFullYear()):m,t.yearshtml+="<select class='ui-datepicker-year' data-handler='selectYear' data-event='change'>";m>=f;f++)t.yearshtml+="<option value='"+f+"'"+(f===i?" selected='selected'":"")+">"+f+"</option>";t.yearshtml+="</select>",b+=t.yearshtml,t.yearshtml=null}return b+=this._get(t,"yearSuffix"),v&&(b+=(!a&&g&&_?"":"&#xa0;")+y),b+="</div>"},_adjustInstDate:function(t,e,i){var s=t.selectedYear+("Y"===i?e:0),n=t.selectedMonth+("M"===i?e:0),a=Math.min(t.selectedDay,this._getDaysInMonth(s,n))+("D"===i?e:0),o=this._restrictMinMax(t,this._daylightSavingAdjust(new Date(s,n,a)));t.selectedDay=o.getDate(),t.drawMonth=t.selectedMonth=o.getMonth(),t.drawYear=t.selectedYear=o.getFullYear(),("M"===i||"Y"===i)&&this._notifyChange(t)},_restrictMinMax:function(t,e){var i=this._getMinMaxDate(t,"min"),s=this._getMinMaxDate(t,"max"),n=i&&i>e?i:e;return s&&n>s?s:n},_notifyChange:function(t){var e=this._get(t,"onChangeMonthYear");e&&e.apply(t.input?t.input[0]:null,[t.selectedYear,t.selectedMonth+1,t])},_getNumberOfMonths:function(t){var e=this._get(t,"numberOfMonths");return null==e?[1,1]:"number"==typeof e?[1,e]:e},_getMinMaxDate:function(t,e){return this._determineDate(t,this._get(t,e+"Date"),null)},_getDaysInMonth:function(t,e){return 32-this._daylightSavingAdjust(new Date(t,e,32)).getDate()},_getFirstDayOfMonth:function(t,e){return new Date(t,e,1).getDay()},_canAdjustMonth:function(t,e,i,s){var n=this._getNumberOfMonths(t),a=this._daylightSavingAdjust(new Date(i,s+(0>e?e:n[0]*n[1]),1));return 0>e&&a.setDate(this._getDaysInMonth(a.getFullYear(),a.getMonth())),this._isInRange(t,a)},_isInRange:function(t,e){var i,s,n=this._getMinMaxDate(t,"min"),a=this._getMinMaxDate(t,"max"),o=null,r=null,h=this._get(t,"yearRange");return h&&(i=h.split(":"),s=(new Date).getFullYear(),o=parseInt(i[0],10),r=parseInt(i[1],10),i[0].match(/[+\-].*/)&&(o+=s),i[1].match(/[+\-].*/)&&(r+=s)),(!n||e.getTime()>=n.getTime())&&(!a||e.getTime()<=a.getTime())&&(!o||e.getFullYear()>=o)&&(!r||r>=e.getFullYear())},_getFormatConfig:function(t){var e=this._get(t,"shortYearCutoff");return e="string"!=typeof e?e:(new Date).getFullYear()%100+parseInt(e,10),{shortYearCutoff:e,dayNamesShort:this._get(t,"dayNamesShort"),dayNames:this._get(t,"dayNames"),monthNamesShort:this._get(t,"monthNamesShort"),monthNames:this._get(t,"monthNames")}},_formatDate:function(t,e,i,s){e||(t.currentDay=t.selectedDay,t.currentMonth=t.selectedMonth,t.currentYear=t.selectedYear);var n=e?"object"==typeof e?e:this._daylightSavingAdjust(new Date(s,i,e)):this._daylightSavingAdjust(new Date(t.currentYear,t.currentMonth,t.currentDay));return this.formatDate(this._get(t,"dateFormat"),n,this._getFormatConfig(t))}}),t.fn.datepicker=function(e){if(!this.length)return this;t.datepicker.initialized||(t(document).on("mousedown",t.datepicker._checkExternalClick),t.datepicker.initialized=!0),0===t("#"+t.datepicker._mainDivId).length&&t("body").append(t.datepicker.dpDiv);var i=Array.prototype.slice.call(arguments,1);return"string"!=typeof e||"isDisabled"!==e&&"getDate"!==e&&"widget"!==e?"option"===e&&2===arguments.length&&"string"==typeof arguments[1]?t.datepicker["_"+e+"Datepicker"].apply(t.datepicker,[this[0]].concat(i)):this.each(function(){"string"==typeof e?t.datepicker["_"+e+"Datepicker"].apply(t.datepicker,[this].concat(i)):t.datepicker._attachDatepicker(this,e)}):t.datepicker["_"+e+"Datepicker"].apply(t.datepicker,[this[0]].concat(i))},t.datepicker=new s,t.datepicker.initialized=!1,t.datepicker.uuid=(new Date).getTime(),t.datepicker.version="1.12.1",t.datepicker,t.widget("ui.dialog",{version:"1.12.1",options:{appendTo:"body",autoOpen:!0,buttons:[],classes:{"ui-dialog":"ui-corner-all","ui-dialog-titlebar":"ui-corner-all"},closeOnEscape:!0,closeText:"Close",draggable:!0,hide:null,height:"auto",maxHeight:null,maxWidth:null,minHeight:150,minWidth:150,modal:!1,position:{my:"center",at:"center",of:window,collision:"fit",using:function(e){var i=t(this).css(e).offset().top;0>i&&t(this).css("top",e.top-i)}},resizable:!0,show:null,title:null,width:300,beforeClose:null,close:null,drag:null,dragStart:null,dragStop:null,focus:null,open:null,resize:null,resizeStart:null,resizeStop:null},sizeRelatedOptions:{buttons:!0,height:!0,maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0,width:!0},resizableRelatedOptions:{maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0},_create:function(){this.originalCss={display:this.element[0].style.display,width:this.element[0].style.width,minHeight:this.element[0].style.minHeight,maxHeight:this.element[0].style.maxHeight,height:this.element[0].style.height},this.originalPosition={parent:this.element.parent(),index:this.element.parent().children().index(this.element)},this.originalTitle=this.element.attr("title"),null==this.options.title&&null!=this.originalTitle&&(this.options.title=this.originalTitle),this.options.disabled&&(this.options.disabled=!1),this._createWrapper(),this.element.show().removeAttr("title").appendTo(this.uiDialog),this._addClass("ui-dialog-content","ui-widget-content"),this._createTitlebar(),this._createButtonPane(),this.options.draggable&&t.fn.draggable&&this._makeDraggable(),this.options.resizable&&t.fn.resizable&&this._makeResizable(),this._isOpen=!1,this._trackFocus()},_init:function(){this.options.autoOpen&&this.open()},_appendTo:function(){var e=this.options.appendTo;return e&&(e.jquery||e.nodeType)?t(e):this.document.find(e||"body").eq(0)},_destroy:function(){var t,e=this.originalPosition;this._untrackInstance(),this._destroyOverlay(),this.element.removeUniqueId().css(this.originalCss).detach(),this.uiDialog.remove(),this.originalTitle&&this.element.attr("title",this.originalTitle),t=e.parent.children().eq(e.index),t.length&&t[0]!==this.element[0]?t.before(this.element):e.parent.append(this.element)},widget:function(){return this.uiDialog},disable:t.noop,enable:t.noop,close:function(e){var i=this;this._isOpen&&this._trigger("beforeClose",e)!==!1&&(this._isOpen=!1,this._focusedElement=null,this._destroyOverlay(),this._untrackInstance(),this.opener.filter(":focusable").trigger("focus").length||t.ui.safeBlur(t.ui.safeActiveElement(this.document[0])),this._hide(this.uiDialog,this.options.hide,function(){i._trigger("close",e)}))},isOpen:function(){return this._isOpen},moveToTop:function(){this._moveToTop()},_moveToTop:function(e,i){var s=!1,n=this.uiDialog.siblings(".ui-front:visible").map(function(){return+t(this).css("z-index")}).get(),a=Math.max.apply(null,n);return a>=+this.uiDialog.css("z-index")&&(this.uiDialog.css("z-index",a+1),s=!0),s&&!i&&this._trigger("focus",e),s},open:function(){var e=this;return this._isOpen?(this._moveToTop()&&this._focusTabbable(),void 0):(this._isOpen=!0,this.opener=t(t.ui.safeActiveElement(this.document[0])),this._size(),this._position(),this._createOverlay(),this._moveToTop(null,!0),this.overlay&&this.overlay.css("z-index",this.uiDialog.css("z-index")-1),this._show(this.uiDialog,this.options.show,function(){e._focusTabbable(),e._trigger("focus")}),this._makeFocusTarget(),this._trigger("open"),void 0)},_focusTabbable:function(){var t=this._focusedElement;t||(t=this.element.find("[autofocus]")),t.length||(t=this.element.find(":tabbable")),t.length||(t=this.uiDialogButtonPane.find(":tabbable")),t.length||(t=this.uiDialogTitlebarClose.filter(":tabbable")),t.length||(t=this.uiDialog),t.eq(0).trigger("focus")},_keepFocus:function(e){function i(){var e=t.ui.safeActiveElement(this.document[0]),i=this.uiDialog[0]===e||t.contains(this.uiDialog[0],e);i||this._focusTabbable()}e.preventDefault(),i.call(this),this._delay(i)},_createWrapper:function(){this.uiDialog=t("<div>").hide().attr({tabIndex:-1,role:"dialog"}).appendTo(this._appendTo()),this._addClass(this.uiDialog,"ui-dialog","ui-widget ui-widget-content ui-front"),this._on(this.uiDialog,{keydown:function(e){if(this.options.closeOnEscape&&!e.isDefaultPrevented()&&e.keyCode&&e.keyCode===t.ui.keyCode.ESCAPE)return e.preventDefault(),this.close(e),void 0;if(e.keyCode===t.ui.keyCode.TAB&&!e.isDefaultPrevented()){var i=this.uiDialog.find(":tabbable"),s=i.filter(":first"),n=i.filter(":last");e.target!==n[0]&&e.target!==this.uiDialog[0]||e.shiftKey?e.target!==s[0]&&e.target!==this.uiDialog[0]||!e.shiftKey||(this._delay(function(){n.trigger("focus")}),e.preventDefault()):(this._delay(function(){s.trigger("focus")}),e.preventDefault())}},mousedown:function(t){this._moveToTop(t)&&this._focusTabbable()}}),this.element.find("[aria-describedby]").length||this.uiDialog.attr({"aria-describedby":this.element.uniqueId().attr("id")})},_createTitlebar:function(){var e;this.uiDialogTitlebar=t("<div>"),this._addClass(this.uiDialogTitlebar,"ui-dialog-titlebar","ui-widget-header ui-helper-clearfix"),this._on(this.uiDialogTitlebar,{mousedown:function(e){t(e.target).closest(".ui-dialog-titlebar-close")||this.uiDialog.trigger("focus")}}),this.uiDialogTitlebarClose=t("<button type='button'></button>").button({label:t("<a>").text(this.options.closeText).html(),icon:"ui-icon-closethick",showLabel:!1}).appendTo(this.uiDialogTitlebar),this._addClass(this.uiDialogTitlebarClose,"ui-dialog-titlebar-close"),this._on(this.uiDialogTitlebarClose,{click:function(t){t.preventDefault(),this.close(t)}}),e=t("<span>").uniqueId().prependTo(this.uiDialogTitlebar),this._addClass(e,"ui-dialog-title"),this._title(e),this.uiDialogTitlebar.prependTo(this.uiDialog),this.uiDialog.attr({"aria-labelledby":e.attr("id")})},_title:function(t){this.options.title?t.text(this.options.title):t.html("&#160;")},_createButtonPane:function(){this.uiDialogButtonPane=t("<div>"),this._addClass(this.uiDialogButtonPane,"ui-dialog-buttonpane","ui-widget-content ui-helper-clearfix"),this.uiButtonSet=t("<div>").appendTo(this.uiDialogButtonPane),this._addClass(this.uiButtonSet,"ui-dialog-buttonset"),this._createButtons()},_createButtons:function(){var e=this,i=this.options.buttons;return this.uiDialogButtonPane.remove(),this.uiButtonSet.empty(),t.isEmptyObject(i)||t.isArray(i)&&!i.length?(this._removeClass(this.uiDialog,"ui-dialog-buttons"),void 0):(t.each(i,function(i,s){var n,a;s=t.isFunction(s)?{click:s,text:i}:s,s=t.extend({type:"button"},s),n=s.click,a={icon:s.icon,iconPosition:s.iconPosition,showLabel:s.showLabel,icons:s.icons,text:s.text},delete s.click,delete s.icon,delete s.iconPosition,delete s.showLabel,delete s.icons,"boolean"==typeof s.text&&delete s.text,t("<button></button>",s).button(a).appendTo(e.uiButtonSet).on("click",function(){n.apply(e.element[0],arguments)})}),this._addClass(this.uiDialog,"ui-dialog-buttons"),this.uiDialogButtonPane.appendTo(this.uiDialog),void 0)},_makeDraggable:function(){function e(t){return{position:t.position,offset:t.offset}}var i=this,s=this.options;this.uiDialog.draggable({cancel:".ui-dialog-content, .ui-dialog-titlebar-close",handle:".ui-dialog-titlebar",containment:"document",start:function(s,n){i._addClass(t(this),"ui-dialog-dragging"),i._blockFrames(),i._trigger("dragStart",s,e(n))},drag:function(t,s){i._trigger("drag",t,e(s))},stop:function(n,a){var o=a.offset.left-i.document.scrollLeft(),r=a.offset.top-i.document.scrollTop();s.position={my:"left top",at:"left"+(o>=0?"+":"")+o+" "+"top"+(r>=0?"+":"")+r,of:i.window},i._removeClass(t(this),"ui-dialog-dragging"),i._unblockFrames(),i._trigger("dragStop",n,e(a))}})},_makeResizable:function(){function e(t){return{originalPosition:t.originalPosition,originalSize:t.originalSize,position:t.position,size:t.size}}var i=this,s=this.options,n=s.resizable,a=this.uiDialog.css("position"),o="string"==typeof n?n:"n,e,s,w,se,sw,ne,nw";this.uiDialog.resizable({cancel:".ui-dialog-content",containment:"document",alsoResize:this.element,maxWidth:s.maxWidth,maxHeight:s.maxHeight,minWidth:s.minWidth,minHeight:this._minHeight(),handles:o,start:function(s,n){i._addClass(t(this),"ui-dialog-resizing"),i._blockFrames(),i._trigger("resizeStart",s,e(n))},resize:function(t,s){i._trigger("resize",t,e(s))},stop:function(n,a){var o=i.uiDialog.offset(),r=o.left-i.document.scrollLeft(),h=o.top-i.document.scrollTop();s.height=i.uiDialog.height(),s.width=i.uiDialog.width(),s.position={my:"left top",at:"left"+(r>=0?"+":"")+r+" "+"top"+(h>=0?"+":"")+h,of:i.window},i._removeClass(t(this),"ui-dialog-resizing"),i._unblockFrames(),i._trigger("resizeStop",n,e(a))}}).css("position",a)},_trackFocus:function(){this._on(this.widget(),{focusin:function(e){this._makeFocusTarget(),this._focusedElement=t(e.target)}})},_makeFocusTarget:function(){this._untrackInstance(),this._trackingInstances().unshift(this)},_untrackInstance:function(){var e=this._trackingInstances(),i=t.inArray(this,e);-1!==i&&e.splice(i,1)},_trackingInstances:function(){var t=this.document.data("ui-dialog-instances");return t||(t=[],this.document.data("ui-dialog-instances",t)),t},_minHeight:function(){var t=this.options;return"auto"===t.height?t.minHeight:Math.min(t.minHeight,t.height)},_position:function(){var t=this.uiDialog.is(":visible");t||this.uiDialog.show(),this.uiDialog.position(this.options.position),t||this.uiDialog.hide()},_setOptions:function(e){var i=this,s=!1,n={};t.each(e,function(t,e){i._setOption(t,e),t in i.sizeRelatedOptions&&(s=!0),t in i.resizableRelatedOptions&&(n[t]=e)}),s&&(this._size(),this._position()),this.uiDialog.is(":data(ui-resizable)")&&this.uiDialog.resizable("option",n)},_setOption:function(e,i){var s,n,a=this.uiDialog;"disabled"!==e&&(this._super(e,i),"appendTo"===e&&this.uiDialog.appendTo(this._appendTo()),"buttons"===e&&this._createButtons(),"closeText"===e&&this.uiDialogTitlebarClose.button({label:t("<a>").text(""+this.options.closeText).html()}),"draggable"===e&&(s=a.is(":data(ui-draggable)"),s&&!i&&a.draggable("destroy"),!s&&i&&this._makeDraggable()),"position"===e&&this._position(),"resizable"===e&&(n=a.is(":data(ui-resizable)"),n&&!i&&a.resizable("destroy"),n&&"string"==typeof i&&a.resizable("option","handles",i),n||i===!1||this._makeResizable()),"title"===e&&this._title(this.uiDialogTitlebar.find(".ui-dialog-title")))},_size:function(){var t,e,i,s=this.options;this.element.show().css({width:"auto",minHeight:0,maxHeight:"none",height:0}),s.minWidth>s.width&&(s.width=s.minWidth),t=this.uiDialog.css({height:"auto",width:s.width}).outerHeight(),e=Math.max(0,s.minHeight-t),i="number"==typeof s.maxHeight?Math.max(0,s.maxHeight-t):"none","auto"===s.height?this.element.css({minHeight:e,maxHeight:i,height:"auto"}):this.element.height(Math.max(0,s.height-t)),this.uiDialog.is(":data(ui-resizable)")&&this.uiDialog.resizable("option","minHeight",this._minHeight())},_blockFrames:function(){this.iframeBlocks=this.document.find("iframe").map(function(){var e=t(this); return t("<div>").css({position:"absolute",width:e.outerWidth(),height:e.outerHeight()}).appendTo(e.parent()).offset(e.offset())[0]})},_unblockFrames:function(){this.iframeBlocks&&(this.iframeBlocks.remove(),delete this.iframeBlocks)},_allowInteraction:function(e){return t(e.target).closest(".ui-dialog").length?!0:!!t(e.target).closest(".ui-datepicker").length},_createOverlay:function(){if(this.options.modal){var e=!0;this._delay(function(){e=!1}),this.document.data("ui-dialog-overlays")||this._on(this.document,{focusin:function(t){e||this._allowInteraction(t)||(t.preventDefault(),this._trackingInstances()[0]._focusTabbable())}}),this.overlay=t("<div>").appendTo(this._appendTo()),this._addClass(this.overlay,null,"ui-widget-overlay ui-front"),this._on(this.overlay,{mousedown:"_keepFocus"}),this.document.data("ui-dialog-overlays",(this.document.data("ui-dialog-overlays")||0)+1)}},_destroyOverlay:function(){if(this.options.modal&&this.overlay){var t=this.document.data("ui-dialog-overlays")-1;t?this.document.data("ui-dialog-overlays",t):(this._off(this.document,"focusin"),this.document.removeData("ui-dialog-overlays")),this.overlay.remove(),this.overlay=null}}}),t.uiBackCompat!==!1&&t.widget("ui.dialog",t.ui.dialog,{options:{dialogClass:""},_createWrapper:function(){this._super(),this.uiDialog.addClass(this.options.dialogClass)},_setOption:function(t,e){"dialogClass"===t&&this.uiDialog.removeClass(this.options.dialogClass).addClass(e),this._superApply(arguments)}}),t.ui.dialog,t.widget("ui.menu",{version:"1.12.1",defaultElement:"<ul>",delay:300,options:{icons:{submenu:"ui-icon-caret-1-e"},items:"> *",menus:"ul",position:{my:"left top",at:"right top"},role:"menu",blur:null,focus:null,select:null},_create:function(){this.activeMenu=this.element,this.mouseHandled=!1,this.element.uniqueId().attr({role:this.options.role,tabIndex:0}),this._addClass("ui-menu","ui-widget ui-widget-content"),this._on({"mousedown .ui-menu-item":function(t){t.preventDefault()},"click .ui-menu-item":function(e){var i=t(e.target),s=t(t.ui.safeActiveElement(this.document[0]));!this.mouseHandled&&i.not(".ui-state-disabled").length&&(this.select(e),e.isPropagationStopped()||(this.mouseHandled=!0),i.has(".ui-menu").length?this.expand(e):!this.element.is(":focus")&&s.closest(".ui-menu").length&&(this.element.trigger("focus",[!0]),this.active&&1===this.active.parents(".ui-menu").length&&clearTimeout(this.timer)))},"mouseenter .ui-menu-item":function(e){if(!this.previousFilter){var i=t(e.target).closest(".ui-menu-item"),s=t(e.currentTarget);i[0]===s[0]&&(this._removeClass(s.siblings().children(".ui-state-active"),null,"ui-state-active"),this.focus(e,s))}},mouseleave:"collapseAll","mouseleave .ui-menu":"collapseAll",focus:function(t,e){var i=this.active||this.element.find(this.options.items).eq(0);e||this.focus(t,i)},blur:function(e){this._delay(function(){var i=!t.contains(this.element[0],t.ui.safeActiveElement(this.document[0]));i&&this.collapseAll(e)})},keydown:"_keydown"}),this.refresh(),this._on(this.document,{click:function(t){this._closeOnDocumentClick(t)&&this.collapseAll(t),this.mouseHandled=!1}})},_destroy:function(){var e=this.element.find(".ui-menu-item").removeAttr("role aria-disabled"),i=e.children(".ui-menu-item-wrapper").removeUniqueId().removeAttr("tabIndex role aria-haspopup");this.element.removeAttr("aria-activedescendant").find(".ui-menu").addBack().removeAttr("role aria-labelledby aria-expanded aria-hidden aria-disabled tabIndex").removeUniqueId().show(),i.children().each(function(){var e=t(this);e.data("ui-menu-submenu-caret")&&e.remove()})},_keydown:function(e){var i,s,n,a,o=!0;switch(e.keyCode){case t.ui.keyCode.PAGE_UP:this.previousPage(e);break;case t.ui.keyCode.PAGE_DOWN:this.nextPage(e);break;case t.ui.keyCode.HOME:this._move("first","first",e);break;case t.ui.keyCode.END:this._move("last","last",e);break;case t.ui.keyCode.UP:this.previous(e);break;case t.ui.keyCode.DOWN:this.next(e);break;case t.ui.keyCode.LEFT:this.collapse(e);break;case t.ui.keyCode.RIGHT:this.active&&!this.active.is(".ui-state-disabled")&&this.expand(e);break;case t.ui.keyCode.ENTER:case t.ui.keyCode.SPACE:this._activate(e);break;case t.ui.keyCode.ESCAPE:this.collapse(e);break;default:o=!1,s=this.previousFilter||"",a=!1,n=e.keyCode>=96&&105>=e.keyCode?""+(e.keyCode-96):String.fromCharCode(e.keyCode),clearTimeout(this.filterTimer),n===s?a=!0:n=s+n,i=this._filterMenuItems(n),i=a&&-1!==i.index(this.active.next())?this.active.nextAll(".ui-menu-item"):i,i.length||(n=String.fromCharCode(e.keyCode),i=this._filterMenuItems(n)),i.length?(this.focus(e,i),this.previousFilter=n,this.filterTimer=this._delay(function(){delete this.previousFilter},1e3)):delete this.previousFilter}o&&e.preventDefault()},_activate:function(t){this.active&&!this.active.is(".ui-state-disabled")&&(this.active.children("[aria-haspopup='true']").length?this.expand(t):this.select(t))},refresh:function(){var e,i,s,n,a,o=this,r=this.options.icons.submenu,h=this.element.find(this.options.menus);this._toggleClass("ui-menu-icons",null,!!this.element.find(".ui-icon").length),s=h.filter(":not(.ui-menu)").hide().attr({role:this.options.role,"aria-hidden":"true","aria-expanded":"false"}).each(function(){var e=t(this),i=e.prev(),s=t("<span>").data("ui-menu-submenu-caret",!0);o._addClass(s,"ui-menu-icon","ui-icon "+r),i.attr("aria-haspopup","true").prepend(s),e.attr("aria-labelledby",i.attr("id"))}),this._addClass(s,"ui-menu","ui-widget ui-widget-content ui-front"),e=h.add(this.element),i=e.find(this.options.items),i.not(".ui-menu-item").each(function(){var e=t(this);o._isDivider(e)&&o._addClass(e,"ui-menu-divider","ui-widget-content")}),n=i.not(".ui-menu-item, .ui-menu-divider"),a=n.children().not(".ui-menu").uniqueId().attr({tabIndex:-1,role:this._itemRole()}),this._addClass(n,"ui-menu-item")._addClass(a,"ui-menu-item-wrapper"),i.filter(".ui-state-disabled").attr("aria-disabled","true"),this.active&&!t.contains(this.element[0],this.active[0])&&this.blur()},_itemRole:function(){return{menu:"menuitem",listbox:"option"}[this.options.role]},_setOption:function(t,e){if("icons"===t){var i=this.element.find(".ui-menu-icon");this._removeClass(i,null,this.options.icons.submenu)._addClass(i,null,e.submenu)}this._super(t,e)},_setOptionDisabled:function(t){this._super(t),this.element.attr("aria-disabled",t+""),this._toggleClass(null,"ui-state-disabled",!!t)},focus:function(t,e){var i,s,n;this.blur(t,t&&"focus"===t.type),this._scrollIntoView(e),this.active=e.first(),s=this.active.children(".ui-menu-item-wrapper"),this._addClass(s,null,"ui-state-active"),this.options.role&&this.element.attr("aria-activedescendant",s.attr("id")),n=this.active.parent().closest(".ui-menu-item").children(".ui-menu-item-wrapper"),this._addClass(n,null,"ui-state-active"),t&&"keydown"===t.type?this._close():this.timer=this._delay(function(){this._close()},this.delay),i=e.children(".ui-menu"),i.length&&t&&/^mouse/.test(t.type)&&this._startOpening(i),this.activeMenu=e.parent(),this._trigger("focus",t,{item:e})},_scrollIntoView:function(e){var i,s,n,a,o,r;this._hasScroll()&&(i=parseFloat(t.css(this.activeMenu[0],"borderTopWidth"))||0,s=parseFloat(t.css(this.activeMenu[0],"paddingTop"))||0,n=e.offset().top-this.activeMenu.offset().top-i-s,a=this.activeMenu.scrollTop(),o=this.activeMenu.height(),r=e.outerHeight(),0>n?this.activeMenu.scrollTop(a+n):n+r>o&&this.activeMenu.scrollTop(a+n-o+r))},blur:function(t,e){e||clearTimeout(this.timer),this.active&&(this._removeClass(this.active.children(".ui-menu-item-wrapper"),null,"ui-state-active"),this._trigger("blur",t,{item:this.active}),this.active=null)},_startOpening:function(t){clearTimeout(this.timer),"true"===t.attr("aria-hidden")&&(this.timer=this._delay(function(){this._close(),this._open(t)},this.delay))},_open:function(e){var i=t.extend({of:this.active},this.options.position);clearTimeout(this.timer),this.element.find(".ui-menu").not(e.parents(".ui-menu")).hide().attr("aria-hidden","true"),e.show().removeAttr("aria-hidden").attr("aria-expanded","true").position(i)},collapseAll:function(e,i){clearTimeout(this.timer),this.timer=this._delay(function(){var s=i?this.element:t(e&&e.target).closest(this.element.find(".ui-menu"));s.length||(s=this.element),this._close(s),this.blur(e),this._removeClass(s.find(".ui-state-active"),null,"ui-state-active"),this.activeMenu=s},this.delay)},_close:function(t){t||(t=this.active?this.active.parent():this.element),t.find(".ui-menu").hide().attr("aria-hidden","true").attr("aria-expanded","false")},_closeOnDocumentClick:function(e){return!t(e.target).closest(".ui-menu").length},_isDivider:function(t){return!/[^\-\u2014\u2013\s]/.test(t.text())},collapse:function(t){var e=this.active&&this.active.parent().closest(".ui-menu-item",this.element);e&&e.length&&(this._close(),this.focus(t,e))},expand:function(t){var e=this.active&&this.active.children(".ui-menu ").find(this.options.items).first();e&&e.length&&(this._open(e.parent()),this._delay(function(){this.focus(t,e)}))},next:function(t){this._move("next","first",t)},previous:function(t){this._move("prev","last",t)},isFirstItem:function(){return this.active&&!this.active.prevAll(".ui-menu-item").length},isLastItem:function(){return this.active&&!this.active.nextAll(".ui-menu-item").length},_move:function(t,e,i){var s;this.active&&(s="first"===t||"last"===t?this.active["first"===t?"prevAll":"nextAll"](".ui-menu-item").eq(-1):this.active[t+"All"](".ui-menu-item").eq(0)),s&&s.length&&this.active||(s=this.activeMenu.find(this.options.items)[e]()),this.focus(i,s)},nextPage:function(e){var i,s,n;return this.active?(this.isLastItem()||(this._hasScroll()?(s=this.active.offset().top,n=this.element.height(),this.active.nextAll(".ui-menu-item").each(function(){return i=t(this),0>i.offset().top-s-n}),this.focus(e,i)):this.focus(e,this.activeMenu.find(this.options.items)[this.active?"last":"first"]())),void 0):(this.next(e),void 0)},previousPage:function(e){var i,s,n;return this.active?(this.isFirstItem()||(this._hasScroll()?(s=this.active.offset().top,n=this.element.height(),this.active.prevAll(".ui-menu-item").each(function(){return i=t(this),i.offset().top-s+n>0}),this.focus(e,i)):this.focus(e,this.activeMenu.find(this.options.items).first())),void 0):(this.next(e),void 0)},_hasScroll:function(){return this.element.outerHeight()<this.element.prop("scrollHeight")},select:function(e){this.active=this.active||t(e.target).closest(".ui-menu-item");var i={item:this.active};this.active.has(".ui-menu").length||this.collapseAll(e,!0),this._trigger("select",e,i)},_filterMenuItems:function(e){var i=e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&"),s=RegExp("^"+i,"i");return this.activeMenu.find(this.options.items).filter(".ui-menu-item").filter(function(){return s.test(t.trim(t(this).children(".ui-menu-item-wrapper").text()))})}}),t.widget("ui.progressbar",{version:"1.12.1",options:{classes:{"ui-progressbar":"ui-corner-all","ui-progressbar-value":"ui-corner-left","ui-progressbar-complete":"ui-corner-right"},max:100,value:0,change:null,complete:null},min:0,_create:function(){this.oldValue=this.options.value=this._constrainedValue(),this.element.attr({role:"progressbar","aria-valuemin":this.min}),this._addClass("ui-progressbar","ui-widget ui-widget-content"),this.valueDiv=t("<div>").appendTo(this.element),this._addClass(this.valueDiv,"ui-progressbar-value","ui-widget-header"),this._refreshValue()},_destroy:function(){this.element.removeAttr("role aria-valuemin aria-valuemax aria-valuenow"),this.valueDiv.remove()},value:function(t){return void 0===t?this.options.value:(this.options.value=this._constrainedValue(t),this._refreshValue(),void 0)},_constrainedValue:function(t){return void 0===t&&(t=this.options.value),this.indeterminate=t===!1,"number"!=typeof t&&(t=0),this.indeterminate?!1:Math.min(this.options.max,Math.max(this.min,t))},_setOptions:function(t){var e=t.value;delete t.value,this._super(t),this.options.value=this._constrainedValue(e),this._refreshValue()},_setOption:function(t,e){"max"===t&&(e=Math.max(this.min,e)),this._super(t,e)},_setOptionDisabled:function(t){this._super(t),this.element.attr("aria-disabled",t),this._toggleClass(null,"ui-state-disabled",!!t)},_percentage:function(){return this.indeterminate?100:100*(this.options.value-this.min)/(this.options.max-this.min)},_refreshValue:function(){var e=this.options.value,i=this._percentage();this.valueDiv.toggle(this.indeterminate||e>this.min).width(i.toFixed(0)+"%"),this._toggleClass(this.valueDiv,"ui-progressbar-complete",null,e===this.options.max)._toggleClass("ui-progressbar-indeterminate",null,this.indeterminate),this.indeterminate?(this.element.removeAttr("aria-valuenow"),this.overlayDiv||(this.overlayDiv=t("<div>").appendTo(this.valueDiv),this._addClass(this.overlayDiv,"ui-progressbar-overlay"))):(this.element.attr({"aria-valuemax":this.options.max,"aria-valuenow":e}),this.overlayDiv&&(this.overlayDiv.remove(),this.overlayDiv=null)),this.oldValue!==e&&(this.oldValue=e,this._trigger("change")),e===this.options.max&&this._trigger("complete")}}),t.widget("ui.selectmenu",[t.ui.formResetMixin,{version:"1.12.1",defaultElement:"<select>",options:{appendTo:null,classes:{"ui-selectmenu-button-open":"ui-corner-top","ui-selectmenu-button-closed":"ui-corner-all"},disabled:null,icons:{button:"ui-icon-triangle-1-s"},position:{my:"left top",at:"left bottom",collision:"none"},width:!1,change:null,close:null,focus:null,open:null,select:null},_create:function(){var e=this.element.uniqueId().attr("id");this.ids={element:e,button:e+"-button",menu:e+"-menu"},this._drawButton(),this._drawMenu(),this._bindFormResetHandler(),this._rendered=!1,this.menuItems=t()},_drawButton:function(){var e,i=this,s=this._parseOption(this.element.find("option:selected"),this.element[0].selectedIndex);this.labels=this.element.labels().attr("for",this.ids.button),this._on(this.labels,{click:function(t){this.button.focus(),t.preventDefault()}}),this.element.hide(),this.button=t("<span>",{tabindex:this.options.disabled?-1:0,id:this.ids.button,role:"combobox","aria-expanded":"false","aria-autocomplete":"list","aria-owns":this.ids.menu,"aria-haspopup":"true",title:this.element.attr("title")}).insertAfter(this.element),this._addClass(this.button,"ui-selectmenu-button ui-selectmenu-button-closed","ui-button ui-widget"),e=t("<span>").appendTo(this.button),this._addClass(e,"ui-selectmenu-icon","ui-icon "+this.options.icons.button),this.buttonItem=this._renderButtonItem(s).appendTo(this.button),this.options.width!==!1&&this._resizeButton(),this._on(this.button,this._buttonEvents),this.button.one("focusin",function(){i._rendered||i._refreshMenu()})},_drawMenu:function(){var e=this;this.menu=t("<ul>",{"aria-hidden":"true","aria-labelledby":this.ids.button,id:this.ids.menu}),this.menuWrap=t("<div>").append(this.menu),this._addClass(this.menuWrap,"ui-selectmenu-menu","ui-front"),this.menuWrap.appendTo(this._appendTo()),this.menuInstance=this.menu.menu({classes:{"ui-menu":"ui-corner-bottom"},role:"listbox",select:function(t,i){t.preventDefault(),e._setSelection(),e._select(i.item.data("ui-selectmenu-item"),t)},focus:function(t,i){var s=i.item.data("ui-selectmenu-item");null!=e.focusIndex&&s.index!==e.focusIndex&&(e._trigger("focus",t,{item:s}),e.isOpen||e._select(s,t)),e.focusIndex=s.index,e.button.attr("aria-activedescendant",e.menuItems.eq(s.index).attr("id"))}}).menu("instance"),this.menuInstance._off(this.menu,"mouseleave"),this.menuInstance._closeOnDocumentClick=function(){return!1},this.menuInstance._isDivider=function(){return!1}},refresh:function(){this._refreshMenu(),this.buttonItem.replaceWith(this.buttonItem=this._renderButtonItem(this._getSelectedItem().data("ui-selectmenu-item")||{})),null===this.options.width&&this._resizeButton()},_refreshMenu:function(){var t,e=this.element.find("option");this.menu.empty(),this._parseOptions(e),this._renderMenu(this.menu,this.items),this.menuInstance.refresh(),this.menuItems=this.menu.find("li").not(".ui-selectmenu-optgroup").find(".ui-menu-item-wrapper"),this._rendered=!0,e.length&&(t=this._getSelectedItem(),this.menuInstance.focus(null,t),this._setAria(t.data("ui-selectmenu-item")),this._setOption("disabled",this.element.prop("disabled")))},open:function(t){this.options.disabled||(this._rendered?(this._removeClass(this.menu.find(".ui-state-active"),null,"ui-state-active"),this.menuInstance.focus(null,this._getSelectedItem())):this._refreshMenu(),this.menuItems.length&&(this.isOpen=!0,this._toggleAttr(),this._resizeMenu(),this._position(),this._on(this.document,this._documentClick),this._trigger("open",t)))},_position:function(){this.menuWrap.position(t.extend({of:this.button},this.options.position))},close:function(t){this.isOpen&&(this.isOpen=!1,this._toggleAttr(),this.range=null,this._off(this.document),this._trigger("close",t))},widget:function(){return this.button},menuWidget:function(){return this.menu},_renderButtonItem:function(e){var i=t("<span>");return this._setText(i,e.label),this._addClass(i,"ui-selectmenu-text"),i},_renderMenu:function(e,i){var s=this,n="";t.each(i,function(i,a){var o;a.optgroup!==n&&(o=t("<li>",{text:a.optgroup}),s._addClass(o,"ui-selectmenu-optgroup","ui-menu-divider"+(a.element.parent("optgroup").prop("disabled")?" ui-state-disabled":"")),o.appendTo(e),n=a.optgroup),s._renderItemData(e,a)})},_renderItemData:function(t,e){return this._renderItem(t,e).data("ui-selectmenu-item",e)},_renderItem:function(e,i){var s=t("<li>"),n=t("<div>",{title:i.element.attr("title")});return i.disabled&&this._addClass(s,null,"ui-state-disabled"),this._setText(n,i.label),s.append(n).appendTo(e)},_setText:function(t,e){e?t.text(e):t.html("&#160;")},_move:function(t,e){var i,s,n=".ui-menu-item";this.isOpen?i=this.menuItems.eq(this.focusIndex).parent("li"):(i=this.menuItems.eq(this.element[0].selectedIndex).parent("li"),n+=":not(.ui-state-disabled)"),s="first"===t||"last"===t?i["first"===t?"prevAll":"nextAll"](n).eq(-1):i[t+"All"](n).eq(0),s.length&&this.menuInstance.focus(e,s)},_getSelectedItem:function(){return this.menuItems.eq(this.element[0].selectedIndex).parent("li")},_toggle:function(t){this[this.isOpen?"close":"open"](t)},_setSelection:function(){var t;this.range&&(window.getSelection?(t=window.getSelection(),t.removeAllRanges(),t.addRange(this.range)):this.range.select(),this.button.focus())},_documentClick:{mousedown:function(e){this.isOpen&&(t(e.target).closest(".ui-selectmenu-menu, #"+t.ui.escapeSelector(this.ids.button)).length||this.close(e))}},_buttonEvents:{mousedown:function(){var t;window.getSelection?(t=window.getSelection(),t.rangeCount&&(this.range=t.getRangeAt(0))):this.range=document.selection.createRange()},click:function(t){this._setSelection(),this._toggle(t)},keydown:function(e){var i=!0;switch(e.keyCode){case t.ui.keyCode.TAB:case t.ui.keyCode.ESCAPE:this.close(e),i=!1;break;case t.ui.keyCode.ENTER:this.isOpen&&this._selectFocusedItem(e);break;case t.ui.keyCode.UP:e.altKey?this._toggle(e):this._move("prev",e);break;case t.ui.keyCode.DOWN:e.altKey?this._toggle(e):this._move("next",e);break;case t.ui.keyCode.SPACE:this.isOpen?this._selectFocusedItem(e):this._toggle(e);break;case t.ui.keyCode.LEFT:this._move("prev",e);break;case t.ui.keyCode.RIGHT:this._move("next",e);break;case t.ui.keyCode.HOME:case t.ui.keyCode.PAGE_UP:this._move("first",e);break;case t.ui.keyCode.END:case t.ui.keyCode.PAGE_DOWN:this._move("last",e);break;default:this.menu.trigger(e),i=!1}i&&e.preventDefault()}},_selectFocusedItem:function(t){var e=this.menuItems.eq(this.focusIndex).parent("li");e.hasClass("ui-state-disabled")||this._select(e.data("ui-selectmenu-item"),t)},_select:function(t,e){var i=this.element[0].selectedIndex;this.element[0].selectedIndex=t.index,this.buttonItem.replaceWith(this.buttonItem=this._renderButtonItem(t)),this._setAria(t),this._trigger("select",e,{item:t}),t.index!==i&&this._trigger("change",e,{item:t}),this.close(e)},_setAria:function(t){var e=this.menuItems.eq(t.index).attr("id");this.button.attr({"aria-labelledby":e,"aria-activedescendant":e}),this.menu.attr("aria-activedescendant",e)},_setOption:function(t,e){if("icons"===t){var i=this.button.find("span.ui-icon");this._removeClass(i,null,this.options.icons.button)._addClass(i,null,e.button)}this._super(t,e),"appendTo"===t&&this.menuWrap.appendTo(this._appendTo()),"width"===t&&this._resizeButton()},_setOptionDisabled:function(t){this._super(t),this.menuInstance.option("disabled",t),this.button.attr("aria-disabled",t),this._toggleClass(this.button,null,"ui-state-disabled",t),this.element.prop("disabled",t),t?(this.button.attr("tabindex",-1),this.close()):this.button.attr("tabindex",0)},_appendTo:function(){var e=this.options.appendTo;return e&&(e=e.jquery||e.nodeType?t(e):this.document.find(e).eq(0)),e&&e[0]||(e=this.element.closest(".ui-front, dialog")),e.length||(e=this.document[0].body),e},_toggleAttr:function(){this.button.attr("aria-expanded",this.isOpen),this._removeClass(this.button,"ui-selectmenu-button-"+(this.isOpen?"closed":"open"))._addClass(this.button,"ui-selectmenu-button-"+(this.isOpen?"open":"closed"))._toggleClass(this.menuWrap,"ui-selectmenu-open",null,this.isOpen),this.menu.attr("aria-hidden",!this.isOpen)},_resizeButton:function(){var t=this.options.width;return t===!1?(this.button.css("width",""),void 0):(null===t&&(t=this.element.show().outerWidth(),this.element.hide()),this.button.outerWidth(t),void 0)},_resizeMenu:function(){this.menu.outerWidth(Math.max(this.button.outerWidth(),this.menu.width("").outerWidth()+1))},_getCreateOptions:function(){var t=this._super();return t.disabled=this.element.prop("disabled"),t},_parseOptions:function(e){var i=this,s=[];e.each(function(e,n){s.push(i._parseOption(t(n),e))}),this.items=s},_parseOption:function(t,e){var i=t.parent("optgroup");return{element:t,index:e,value:t.val(),label:t.text(),optgroup:i.attr("label")||"",disabled:i.prop("disabled")||t.prop("disabled")}},_destroy:function(){this._unbindFormResetHandler(),this.menuWrap.remove(),this.button.remove(),this.element.show(),this.element.removeUniqueId(),this.labels.attr("for",this.ids.element)}}]),t.widget("ui.slider",t.ui.mouse,{version:"1.12.1",widgetEventPrefix:"slide",options:{animate:!1,classes:{"ui-slider":"ui-corner-all","ui-slider-handle":"ui-corner-all","ui-slider-range":"ui-corner-all ui-widget-header"},distance:0,max:100,min:0,orientation:"horizontal",range:!1,step:1,value:0,values:null,change:null,slide:null,start:null,stop:null},numPages:5,_create:function(){this._keySliding=!1,this._mouseSliding=!1,this._animateOff=!0,this._handleIndex=null,this._detectOrientation(),this._mouseInit(),this._calculateNewMax(),this._addClass("ui-slider ui-slider-"+this.orientation,"ui-widget ui-widget-content"),this._refresh(),this._animateOff=!1},_refresh:function(){this._createRange(),this._createHandles(),this._setupEvents(),this._refreshValue()},_createHandles:function(){var e,i,s=this.options,n=this.element.find(".ui-slider-handle"),a="<span tabindex='0'></span>",o=[];for(i=s.values&&s.values.length||1,n.length>i&&(n.slice(i).remove(),n=n.slice(0,i)),e=n.length;i>e;e++)o.push(a);this.handles=n.add(t(o.join("")).appendTo(this.element)),this._addClass(this.handles,"ui-slider-handle","ui-state-default"),this.handle=this.handles.eq(0),this.handles.each(function(e){t(this).data("ui-slider-handle-index",e).attr("tabIndex",0)})},_createRange:function(){var e=this.options;e.range?(e.range===!0&&(e.values?e.values.length&&2!==e.values.length?e.values=[e.values[0],e.values[0]]:t.isArray(e.values)&&(e.values=e.values.slice(0)):e.values=[this._valueMin(),this._valueMin()]),this.range&&this.range.length?(this._removeClass(this.range,"ui-slider-range-min ui-slider-range-max"),this.range.css({left:"",bottom:""})):(this.range=t("<div>").appendTo(this.element),this._addClass(this.range,"ui-slider-range")),("min"===e.range||"max"===e.range)&&this._addClass(this.range,"ui-slider-range-"+e.range)):(this.range&&this.range.remove(),this.range=null)},_setupEvents:function(){this._off(this.handles),this._on(this.handles,this._handleEvents),this._hoverable(this.handles),this._focusable(this.handles)},_destroy:function(){this.handles.remove(),this.range&&this.range.remove(),this._mouseDestroy()},_mouseCapture:function(e){var i,s,n,a,o,r,h,l,u=this,c=this.options;return c.disabled?!1:(this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()},this.elementOffset=this.element.offset(),i={x:e.pageX,y:e.pageY},s=this._normValueFromMouse(i),n=this._valueMax()-this._valueMin()+1,this.handles.each(function(e){var i=Math.abs(s-u.values(e));(n>i||n===i&&(e===u._lastChangedValue||u.values(e)===c.min))&&(n=i,a=t(this),o=e)}),r=this._start(e,o),r===!1?!1:(this._mouseSliding=!0,this._handleIndex=o,this._addClass(a,null,"ui-state-active"),a.trigger("focus"),h=a.offset(),l=!t(e.target).parents().addBack().is(".ui-slider-handle"),this._clickOffset=l?{left:0,top:0}:{left:e.pageX-h.left-a.width()/2,top:e.pageY-h.top-a.height()/2-(parseInt(a.css("borderTopWidth"),10)||0)-(parseInt(a.css("borderBottomWidth"),10)||0)+(parseInt(a.css("marginTop"),10)||0)},this.handles.hasClass("ui-state-hover")||this._slide(e,o,s),this._animateOff=!0,!0))},_mouseStart:function(){return!0},_mouseDrag:function(t){var e={x:t.pageX,y:t.pageY},i=this._normValueFromMouse(e);return this._slide(t,this._handleIndex,i),!1},_mouseStop:function(t){return this._removeClass(this.handles,null,"ui-state-active"),this._mouseSliding=!1,this._stop(t,this._handleIndex),this._change(t,this._handleIndex),this._handleIndex=null,this._clickOffset=null,this._animateOff=!1,!1},_detectOrientation:function(){this.orientation="vertical"===this.options.orientation?"vertical":"horizontal"},_normValueFromMouse:function(t){var e,i,s,n,a;return"horizontal"===this.orientation?(e=this.elementSize.width,i=t.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)):(e=this.elementSize.height,i=t.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)),s=i/e,s>1&&(s=1),0>s&&(s=0),"vertical"===this.orientation&&(s=1-s),n=this._valueMax()-this._valueMin(),a=this._valueMin()+s*n,this._trimAlignValue(a)},_uiHash:function(t,e,i){var s={handle:this.handles[t],handleIndex:t,value:void 0!==e?e:this.value()};return this._hasMultipleValues()&&(s.value=void 0!==e?e:this.values(t),s.values=i||this.values()),s},_hasMultipleValues:function(){return this.options.values&&this.options.values.length},_start:function(t,e){return this._trigger("start",t,this._uiHash(e))},_slide:function(t,e,i){var s,n,a=this.value(),o=this.values();this._hasMultipleValues()&&(n=this.values(e?0:1),a=this.values(e),2===this.options.values.length&&this.options.range===!0&&(i=0===e?Math.min(n,i):Math.max(n,i)),o[e]=i),i!==a&&(s=this._trigger("slide",t,this._uiHash(e,i,o)),s!==!1&&(this._hasMultipleValues()?this.values(e,i):this.value(i)))},_stop:function(t,e){this._trigger("stop",t,this._uiHash(e))},_change:function(t,e){this._keySliding||this._mouseSliding||(this._lastChangedValue=e,this._trigger("change",t,this._uiHash(e)))},value:function(t){return arguments.length?(this.options.value=this._trimAlignValue(t),this._refreshValue(),this._change(null,0),void 0):this._value()},values:function(e,i){var s,n,a;if(arguments.length>1)return this.options.values[e]=this._trimAlignValue(i),this._refreshValue(),this._change(null,e),void 0;if(!arguments.length)return this._values();if(!t.isArray(arguments[0]))return this._hasMultipleValues()?this._values(e):this.value();for(s=this.options.values,n=arguments[0],a=0;s.length>a;a+=1)s[a]=this._trimAlignValue(n[a]),this._change(null,a);this._refreshValue()},_setOption:function(e,i){var s,n=0;switch("range"===e&&this.options.range===!0&&("min"===i?(this.options.value=this._values(0),this.options.values=null):"max"===i&&(this.options.value=this._values(this.options.values.length-1),this.options.values=null)),t.isArray(this.options.values)&&(n=this.options.values.length),this._super(e,i),e){case"orientation":this._detectOrientation(),this._removeClass("ui-slider-horizontal ui-slider-vertical")._addClass("ui-slider-"+this.orientation),this._refreshValue(),this.options.range&&this._refreshRange(i),this.handles.css("horizontal"===i?"bottom":"left","");break;case"value":this._animateOff=!0,this._refreshValue(),this._change(null,0),this._animateOff=!1;break;case"values":for(this._animateOff=!0,this._refreshValue(),s=n-1;s>=0;s--)this._change(null,s);this._animateOff=!1;break;case"step":case"min":case"max":this._animateOff=!0,this._calculateNewMax(),this._refreshValue(),this._animateOff=!1;break;case"range":this._animateOff=!0,this._refresh(),this._animateOff=!1}},_setOptionDisabled:function(t){this._super(t),this._toggleClass(null,"ui-state-disabled",!!t)},_value:function(){var t=this.options.value;return t=this._trimAlignValue(t)},_values:function(t){var e,i,s;if(arguments.length)return e=this.options.values[t],e=this._trimAlignValue(e);if(this._hasMultipleValues()){for(i=this.options.values.slice(),s=0;i.length>s;s+=1)i[s]=this._trimAlignValue(i[s]);return i}return[]},_trimAlignValue:function(t){if(this._valueMin()>=t)return this._valueMin();if(t>=this._valueMax())return this._valueMax();var e=this.options.step>0?this.options.step:1,i=(t-this._valueMin())%e,s=t-i;return 2*Math.abs(i)>=e&&(s+=i>0?e:-e),parseFloat(s.toFixed(5))},_calculateNewMax:function(){var t=this.options.max,e=this._valueMin(),i=this.options.step,s=Math.round((t-e)/i)*i;t=s+e,t>this.options.max&&(t-=i),this.max=parseFloat(t.toFixed(this._precision()))},_precision:function(){var t=this._precisionOf(this.options.step);return null!==this.options.min&&(t=Math.max(t,this._precisionOf(this.options.min))),t},_precisionOf:function(t){var e=""+t,i=e.indexOf(".");return-1===i?0:e.length-i-1},_valueMin:function(){return this.options.min},_valueMax:function(){return this.max},_refreshRange:function(t){"vertical"===t&&this.range.css({width:"",left:""}),"horizontal"===t&&this.range.css({height:"",bottom:""})},_refreshValue:function(){var e,i,s,n,a,o=this.options.range,r=this.options,h=this,l=this._animateOff?!1:r.animate,u={};this._hasMultipleValues()?this.handles.each(function(s){i=100*((h.values(s)-h._valueMin())/(h._valueMax()-h._valueMin())),u["horizontal"===h.orientation?"left":"bottom"]=i+"%",t(this).stop(1,1)[l?"animate":"css"](u,r.animate),h.options.range===!0&&("horizontal"===h.orientation?(0===s&&h.range.stop(1,1)[l?"animate":"css"]({left:i+"%"},r.animate),1===s&&h.range[l?"animate":"css"]({width:i-e+"%"},{queue:!1,duration:r.animate})):(0===s&&h.range.stop(1,1)[l?"animate":"css"]({bottom:i+"%"},r.animate),1===s&&h.range[l?"animate":"css"]({height:i-e+"%"},{queue:!1,duration:r.animate}))),e=i}):(s=this.value(),n=this._valueMin(),a=this._valueMax(),i=a!==n?100*((s-n)/(a-n)):0,u["horizontal"===this.orientation?"left":"bottom"]=i+"%",this.handle.stop(1,1)[l?"animate":"css"](u,r.animate),"min"===o&&"horizontal"===this.orientation&&this.range.stop(1,1)[l?"animate":"css"]({width:i+"%"},r.animate),"max"===o&&"horizontal"===this.orientation&&this.range.stop(1,1)[l?"animate":"css"]({width:100-i+"%"},r.animate),"min"===o&&"vertical"===this.orientation&&this.range.stop(1,1)[l?"animate":"css"]({height:i+"%"},r.animate),"max"===o&&"vertical"===this.orientation&&this.range.stop(1,1)[l?"animate":"css"]({height:100-i+"%"},r.animate))},_handleEvents:{keydown:function(e){var i,s,n,a,o=t(e.target).data("ui-slider-handle-index");switch(e.keyCode){case t.ui.keyCode.HOME:case t.ui.keyCode.END:case t.ui.keyCode.PAGE_UP:case t.ui.keyCode.PAGE_DOWN:case t.ui.keyCode.UP:case t.ui.keyCode.RIGHT:case t.ui.keyCode.DOWN:case t.ui.keyCode.LEFT:if(e.preventDefault(),!this._keySliding&&(this._keySliding=!0,this._addClass(t(e.target),null,"ui-state-active"),i=this._start(e,o),i===!1))return}switch(a=this.options.step,s=n=this._hasMultipleValues()?this.values(o):this.value(),e.keyCode){case t.ui.keyCode.HOME:n=this._valueMin();break;case t.ui.keyCode.END:n=this._valueMax();break;case t.ui.keyCode.PAGE_UP:n=this._trimAlignValue(s+(this._valueMax()-this._valueMin())/this.numPages); break;case t.ui.keyCode.PAGE_DOWN:n=this._trimAlignValue(s-(this._valueMax()-this._valueMin())/this.numPages);break;case t.ui.keyCode.UP:case t.ui.keyCode.RIGHT:if(s===this._valueMax())return;n=this._trimAlignValue(s+a);break;case t.ui.keyCode.DOWN:case t.ui.keyCode.LEFT:if(s===this._valueMin())return;n=this._trimAlignValue(s-a)}this._slide(e,o,n)},keyup:function(e){var i=t(e.target).data("ui-slider-handle-index");this._keySliding&&(this._keySliding=!1,this._stop(e,i),this._change(e,i),this._removeClass(t(e.target),null,"ui-state-active"))}}}),t.widget("ui.spinner",{version:"1.12.1",defaultElement:"<input>",widgetEventPrefix:"spin",options:{classes:{"ui-spinner":"ui-corner-all","ui-spinner-down":"ui-corner-br","ui-spinner-up":"ui-corner-tr"},culture:null,icons:{down:"ui-icon-triangle-1-s",up:"ui-icon-triangle-1-n"},incremental:!0,max:null,min:null,numberFormat:null,page:10,step:1,change:null,spin:null,start:null,stop:null},_create:function(){this._setOption("max",this.options.max),this._setOption("min",this.options.min),this._setOption("step",this.options.step),""!==this.value()&&this._value(this.element.val(),!0),this._draw(),this._on(this._events),this._refresh(),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_getCreateOptions:function(){var e=this._super(),i=this.element;return t.each(["min","max","step"],function(t,s){var n=i.attr(s);null!=n&&n.length&&(e[s]=n)}),e},_events:{keydown:function(t){this._start(t)&&this._keydown(t)&&t.preventDefault()},keyup:"_stop",focus:function(){this.previous=this.element.val()},blur:function(t){return this.cancelBlur?(delete this.cancelBlur,void 0):(this._stop(),this._refresh(),this.previous!==this.element.val()&&this._trigger("change",t),void 0)},mousewheel:function(t,e){if(e){if(!this.spinning&&!this._start(t))return!1;this._spin((e>0?1:-1)*this.options.step,t),clearTimeout(this.mousewheelTimer),this.mousewheelTimer=this._delay(function(){this.spinning&&this._stop(t)},100),t.preventDefault()}},"mousedown .ui-spinner-button":function(e){function i(){var e=this.element[0]===t.ui.safeActiveElement(this.document[0]);e||(this.element.trigger("focus"),this.previous=s,this._delay(function(){this.previous=s}))}var s;s=this.element[0]===t.ui.safeActiveElement(this.document[0])?this.previous:this.element.val(),e.preventDefault(),i.call(this),this.cancelBlur=!0,this._delay(function(){delete this.cancelBlur,i.call(this)}),this._start(e)!==!1&&this._repeat(null,t(e.currentTarget).hasClass("ui-spinner-up")?1:-1,e)},"mouseup .ui-spinner-button":"_stop","mouseenter .ui-spinner-button":function(e){return t(e.currentTarget).hasClass("ui-state-active")?this._start(e)===!1?!1:(this._repeat(null,t(e.currentTarget).hasClass("ui-spinner-up")?1:-1,e),void 0):void 0},"mouseleave .ui-spinner-button":"_stop"},_enhance:function(){this.uiSpinner=this.element.attr("autocomplete","off").wrap("<span>").parent().append("<a></a><a></a>")},_draw:function(){this._enhance(),this._addClass(this.uiSpinner,"ui-spinner","ui-widget ui-widget-content"),this._addClass("ui-spinner-input"),this.element.attr("role","spinbutton"),this.buttons=this.uiSpinner.children("a").attr("tabIndex",-1).attr("aria-hidden",!0).button({classes:{"ui-button":""}}),this._removeClass(this.buttons,"ui-corner-all"),this._addClass(this.buttons.first(),"ui-spinner-button ui-spinner-up"),this._addClass(this.buttons.last(),"ui-spinner-button ui-spinner-down"),this.buttons.first().button({icon:this.options.icons.up,showLabel:!1}),this.buttons.last().button({icon:this.options.icons.down,showLabel:!1}),this.buttons.height()>Math.ceil(.5*this.uiSpinner.height())&&this.uiSpinner.height()>0&&this.uiSpinner.height(this.uiSpinner.height())},_keydown:function(e){var i=this.options,s=t.ui.keyCode;switch(e.keyCode){case s.UP:return this._repeat(null,1,e),!0;case s.DOWN:return this._repeat(null,-1,e),!0;case s.PAGE_UP:return this._repeat(null,i.page,e),!0;case s.PAGE_DOWN:return this._repeat(null,-i.page,e),!0}return!1},_start:function(t){return this.spinning||this._trigger("start",t)!==!1?(this.counter||(this.counter=1),this.spinning=!0,!0):!1},_repeat:function(t,e,i){t=t||500,clearTimeout(this.timer),this.timer=this._delay(function(){this._repeat(40,e,i)},t),this._spin(e*this.options.step,i)},_spin:function(t,e){var i=this.value()||0;this.counter||(this.counter=1),i=this._adjustValue(i+t*this._increment(this.counter)),this.spinning&&this._trigger("spin",e,{value:i})===!1||(this._value(i),this.counter++)},_increment:function(e){var i=this.options.incremental;return i?t.isFunction(i)?i(e):Math.floor(e*e*e/5e4-e*e/500+17*e/200+1):1},_precision:function(){var t=this._precisionOf(this.options.step);return null!==this.options.min&&(t=Math.max(t,this._precisionOf(this.options.min))),t},_precisionOf:function(t){var e=""+t,i=e.indexOf(".");return-1===i?0:e.length-i-1},_adjustValue:function(t){var e,i,s=this.options;return e=null!==s.min?s.min:0,i=t-e,i=Math.round(i/s.step)*s.step,t=e+i,t=parseFloat(t.toFixed(this._precision())),null!==s.max&&t>s.max?s.max:null!==s.min&&s.min>t?s.min:t},_stop:function(t){this.spinning&&(clearTimeout(this.timer),clearTimeout(this.mousewheelTimer),this.counter=0,this.spinning=!1,this._trigger("stop",t))},_setOption:function(t,e){var i,s,n;return"culture"===t||"numberFormat"===t?(i=this._parse(this.element.val()),this.options[t]=e,this.element.val(this._format(i)),void 0):(("max"===t||"min"===t||"step"===t)&&"string"==typeof e&&(e=this._parse(e)),"icons"===t&&(s=this.buttons.first().find(".ui-icon"),this._removeClass(s,null,this.options.icons.up),this._addClass(s,null,e.up),n=this.buttons.last().find(".ui-icon"),this._removeClass(n,null,this.options.icons.down),this._addClass(n,null,e.down)),this._super(t,e),void 0)},_setOptionDisabled:function(t){this._super(t),this._toggleClass(this.uiSpinner,null,"ui-state-disabled",!!t),this.element.prop("disabled",!!t),this.buttons.button(t?"disable":"enable")},_setOptions:r(function(t){this._super(t)}),_parse:function(t){return"string"==typeof t&&""!==t&&(t=window.Globalize&&this.options.numberFormat?Globalize.parseFloat(t,10,this.options.culture):+t),""===t||isNaN(t)?null:t},_format:function(t){return""===t?"":window.Globalize&&this.options.numberFormat?Globalize.format(t,this.options.numberFormat,this.options.culture):t},_refresh:function(){this.element.attr({"aria-valuemin":this.options.min,"aria-valuemax":this.options.max,"aria-valuenow":this._parse(this.element.val())})},isValid:function(){var t=this.value();return null===t?!1:t===this._adjustValue(t)},_value:function(t,e){var i;""!==t&&(i=this._parse(t),null!==i&&(e||(i=this._adjustValue(i)),t=this._format(i))),this.element.val(t),this._refresh()},_destroy:function(){this.element.prop("disabled",!1).removeAttr("autocomplete role aria-valuemin aria-valuemax aria-valuenow"),this.uiSpinner.replaceWith(this.element)},stepUp:r(function(t){this._stepUp(t)}),_stepUp:function(t){this._start()&&(this._spin((t||1)*this.options.step),this._stop())},stepDown:r(function(t){this._stepDown(t)}),_stepDown:function(t){this._start()&&(this._spin((t||1)*-this.options.step),this._stop())},pageUp:r(function(t){this._stepUp((t||1)*this.options.page)}),pageDown:r(function(t){this._stepDown((t||1)*this.options.page)}),value:function(t){return arguments.length?(r(this._value).call(this,t),void 0):this._parse(this.element.val())},widget:function(){return this.uiSpinner}}),t.uiBackCompat!==!1&&t.widget("ui.spinner",t.ui.spinner,{_enhance:function(){this.uiSpinner=this.element.attr("autocomplete","off").wrap(this._uiSpinnerHtml()).parent().append(this._buttonHtml())},_uiSpinnerHtml:function(){return"<span>"},_buttonHtml:function(){return"<a></a><a></a>"}}),t.ui.spinner,t.widget("ui.tabs",{version:"1.12.1",delay:300,options:{active:null,classes:{"ui-tabs":"ui-corner-all","ui-tabs-nav":"ui-corner-all","ui-tabs-panel":"ui-corner-bottom","ui-tabs-tab":"ui-corner-top"},collapsible:!1,event:"click",heightStyle:"content",hide:null,show:null,activate:null,beforeActivate:null,beforeLoad:null,load:null},_isLocal:function(){var t=/#.*$/;return function(e){var i,s;i=e.href.replace(t,""),s=location.href.replace(t,"");try{i=decodeURIComponent(i)}catch(n){}try{s=decodeURIComponent(s)}catch(n){}return e.hash.length>1&&i===s}}(),_create:function(){var e=this,i=this.options;this.running=!1,this._addClass("ui-tabs","ui-widget ui-widget-content"),this._toggleClass("ui-tabs-collapsible",null,i.collapsible),this._processTabs(),i.active=this._initialActive(),t.isArray(i.disabled)&&(i.disabled=t.unique(i.disabled.concat(t.map(this.tabs.filter(".ui-state-disabled"),function(t){return e.tabs.index(t)}))).sort()),this.active=this.options.active!==!1&&this.anchors.length?this._findActive(i.active):t(),this._refresh(),this.active.length&&this.load(i.active)},_initialActive:function(){var e=this.options.active,i=this.options.collapsible,s=location.hash.substring(1);return null===e&&(s&&this.tabs.each(function(i,n){return t(n).attr("aria-controls")===s?(e=i,!1):void 0}),null===e&&(e=this.tabs.index(this.tabs.filter(".ui-tabs-active"))),(null===e||-1===e)&&(e=this.tabs.length?0:!1)),e!==!1&&(e=this.tabs.index(this.tabs.eq(e)),-1===e&&(e=i?!1:0)),!i&&e===!1&&this.anchors.length&&(e=0),e},_getCreateEventData:function(){return{tab:this.active,panel:this.active.length?this._getPanelForTab(this.active):t()}},_tabKeydown:function(e){var i=t(t.ui.safeActiveElement(this.document[0])).closest("li"),s=this.tabs.index(i),n=!0;if(!this._handlePageNav(e)){switch(e.keyCode){case t.ui.keyCode.RIGHT:case t.ui.keyCode.DOWN:s++;break;case t.ui.keyCode.UP:case t.ui.keyCode.LEFT:n=!1,s--;break;case t.ui.keyCode.END:s=this.anchors.length-1;break;case t.ui.keyCode.HOME:s=0;break;case t.ui.keyCode.SPACE:return e.preventDefault(),clearTimeout(this.activating),this._activate(s),void 0;case t.ui.keyCode.ENTER:return e.preventDefault(),clearTimeout(this.activating),this._activate(s===this.options.active?!1:s),void 0;default:return}e.preventDefault(),clearTimeout(this.activating),s=this._focusNextTab(s,n),e.ctrlKey||e.metaKey||(i.attr("aria-selected","false"),this.tabs.eq(s).attr("aria-selected","true"),this.activating=this._delay(function(){this.option("active",s)},this.delay))}},_panelKeydown:function(e){this._handlePageNav(e)||e.ctrlKey&&e.keyCode===t.ui.keyCode.UP&&(e.preventDefault(),this.active.trigger("focus"))},_handlePageNav:function(e){return e.altKey&&e.keyCode===t.ui.keyCode.PAGE_UP?(this._activate(this._focusNextTab(this.options.active-1,!1)),!0):e.altKey&&e.keyCode===t.ui.keyCode.PAGE_DOWN?(this._activate(this._focusNextTab(this.options.active+1,!0)),!0):void 0},_findNextTab:function(e,i){function s(){return e>n&&(e=0),0>e&&(e=n),e}for(var n=this.tabs.length-1;-1!==t.inArray(s(),this.options.disabled);)e=i?e+1:e-1;return e},_focusNextTab:function(t,e){return t=this._findNextTab(t,e),this.tabs.eq(t).trigger("focus"),t},_setOption:function(t,e){return"active"===t?(this._activate(e),void 0):(this._super(t,e),"collapsible"===t&&(this._toggleClass("ui-tabs-collapsible",null,e),e||this.options.active!==!1||this._activate(0)),"event"===t&&this._setupEvents(e),"heightStyle"===t&&this._setupHeightStyle(e),void 0)},_sanitizeSelector:function(t){return t?t.replace(/[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g,"\\$&"):""},refresh:function(){var e=this.options,i=this.tablist.children(":has(a[href])");e.disabled=t.map(i.filter(".ui-state-disabled"),function(t){return i.index(t)}),this._processTabs(),e.active!==!1&&this.anchors.length?this.active.length&&!t.contains(this.tablist[0],this.active[0])?this.tabs.length===e.disabled.length?(e.active=!1,this.active=t()):this._activate(this._findNextTab(Math.max(0,e.active-1),!1)):e.active=this.tabs.index(this.active):(e.active=!1,this.active=t()),this._refresh()},_refresh:function(){this._setOptionDisabled(this.options.disabled),this._setupEvents(this.options.event),this._setupHeightStyle(this.options.heightStyle),this.tabs.not(this.active).attr({"aria-selected":"false","aria-expanded":"false",tabIndex:-1}),this.panels.not(this._getPanelForTab(this.active)).hide().attr({"aria-hidden":"true"}),this.active.length?(this.active.attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0}),this._addClass(this.active,"ui-tabs-active","ui-state-active"),this._getPanelForTab(this.active).show().attr({"aria-hidden":"false"})):this.tabs.eq(0).attr("tabIndex",0)},_processTabs:function(){var e=this,i=this.tabs,s=this.anchors,n=this.panels;this.tablist=this._getList().attr("role","tablist"),this._addClass(this.tablist,"ui-tabs-nav","ui-helper-reset ui-helper-clearfix ui-widget-header"),this.tablist.on("mousedown"+this.eventNamespace,"> li",function(e){t(this).is(".ui-state-disabled")&&e.preventDefault()}).on("focus"+this.eventNamespace,".ui-tabs-anchor",function(){t(this).closest("li").is(".ui-state-disabled")&&this.blur()}),this.tabs=this.tablist.find("> li:has(a[href])").attr({role:"tab",tabIndex:-1}),this._addClass(this.tabs,"ui-tabs-tab","ui-state-default"),this.anchors=this.tabs.map(function(){return t("a",this)[0]}).attr({role:"presentation",tabIndex:-1}),this._addClass(this.anchors,"ui-tabs-anchor"),this.panels=t(),this.anchors.each(function(i,s){var n,a,o,r=t(s).uniqueId().attr("id"),h=t(s).closest("li"),l=h.attr("aria-controls");e._isLocal(s)?(n=s.hash,o=n.substring(1),a=e.element.find(e._sanitizeSelector(n))):(o=h.attr("aria-controls")||t({}).uniqueId()[0].id,n="#"+o,a=e.element.find(n),a.length||(a=e._createPanel(o),a.insertAfter(e.panels[i-1]||e.tablist)),a.attr("aria-live","polite")),a.length&&(e.panels=e.panels.add(a)),l&&h.data("ui-tabs-aria-controls",l),h.attr({"aria-controls":o,"aria-labelledby":r}),a.attr("aria-labelledby",r)}),this.panels.attr("role","tabpanel"),this._addClass(this.panels,"ui-tabs-panel","ui-widget-content"),i&&(this._off(i.not(this.tabs)),this._off(s.not(this.anchors)),this._off(n.not(this.panels)))},_getList:function(){return this.tablist||this.element.find("ol, ul").eq(0)},_createPanel:function(e){return t("<div>").attr("id",e).data("ui-tabs-destroy",!0)},_setOptionDisabled:function(e){var i,s,n;for(t.isArray(e)&&(e.length?e.length===this.anchors.length&&(e=!0):e=!1),n=0;s=this.tabs[n];n++)i=t(s),e===!0||-1!==t.inArray(n,e)?(i.attr("aria-disabled","true"),this._addClass(i,null,"ui-state-disabled")):(i.removeAttr("aria-disabled"),this._removeClass(i,null,"ui-state-disabled"));this.options.disabled=e,this._toggleClass(this.widget(),this.widgetFullName+"-disabled",null,e===!0)},_setupEvents:function(e){var i={};e&&t.each(e.split(" "),function(t,e){i[e]="_eventHandler"}),this._off(this.anchors.add(this.tabs).add(this.panels)),this._on(!0,this.anchors,{click:function(t){t.preventDefault()}}),this._on(this.anchors,i),this._on(this.tabs,{keydown:"_tabKeydown"}),this._on(this.panels,{keydown:"_panelKeydown"}),this._focusable(this.tabs),this._hoverable(this.tabs)},_setupHeightStyle:function(e){var i,s=this.element.parent();"fill"===e?(i=s.height(),i-=this.element.outerHeight()-this.element.height(),this.element.siblings(":visible").each(function(){var e=t(this),s=e.css("position");"absolute"!==s&&"fixed"!==s&&(i-=e.outerHeight(!0))}),this.element.children().not(this.panels).each(function(){i-=t(this).outerHeight(!0)}),this.panels.each(function(){t(this).height(Math.max(0,i-t(this).innerHeight()+t(this).height()))}).css("overflow","auto")):"auto"===e&&(i=0,this.panels.each(function(){i=Math.max(i,t(this).height("").height())}).height(i))},_eventHandler:function(e){var i=this.options,s=this.active,n=t(e.currentTarget),a=n.closest("li"),o=a[0]===s[0],r=o&&i.collapsible,h=r?t():this._getPanelForTab(a),l=s.length?this._getPanelForTab(s):t(),u={oldTab:s,oldPanel:l,newTab:r?t():a,newPanel:h};e.preventDefault(),a.hasClass("ui-state-disabled")||a.hasClass("ui-tabs-loading")||this.running||o&&!i.collapsible||this._trigger("beforeActivate",e,u)===!1||(i.active=r?!1:this.tabs.index(a),this.active=o?t():a,this.xhr&&this.xhr.abort(),l.length||h.length||t.error("jQuery UI Tabs: Mismatching fragment identifier."),h.length&&this.load(this.tabs.index(a),e),this._toggle(e,u))},_toggle:function(e,i){function s(){a.running=!1,a._trigger("activate",e,i)}function n(){a._addClass(i.newTab.closest("li"),"ui-tabs-active","ui-state-active"),o.length&&a.options.show?a._show(o,a.options.show,s):(o.show(),s())}var a=this,o=i.newPanel,r=i.oldPanel;this.running=!0,r.length&&this.options.hide?this._hide(r,this.options.hide,function(){a._removeClass(i.oldTab.closest("li"),"ui-tabs-active","ui-state-active"),n()}):(this._removeClass(i.oldTab.closest("li"),"ui-tabs-active","ui-state-active"),r.hide(),n()),r.attr("aria-hidden","true"),i.oldTab.attr({"aria-selected":"false","aria-expanded":"false"}),o.length&&r.length?i.oldTab.attr("tabIndex",-1):o.length&&this.tabs.filter(function(){return 0===t(this).attr("tabIndex")}).attr("tabIndex",-1),o.attr("aria-hidden","false"),i.newTab.attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0})},_activate:function(e){var i,s=this._findActive(e);s[0]!==this.active[0]&&(s.length||(s=this.active),i=s.find(".ui-tabs-anchor")[0],this._eventHandler({target:i,currentTarget:i,preventDefault:t.noop}))},_findActive:function(e){return e===!1?t():this.tabs.eq(e)},_getIndex:function(e){return"string"==typeof e&&(e=this.anchors.index(this.anchors.filter("[href$='"+t.ui.escapeSelector(e)+"']"))),e},_destroy:function(){this.xhr&&this.xhr.abort(),this.tablist.removeAttr("role").off(this.eventNamespace),this.anchors.removeAttr("role tabIndex").removeUniqueId(),this.tabs.add(this.panels).each(function(){t.data(this,"ui-tabs-destroy")?t(this).remove():t(this).removeAttr("role tabIndex aria-live aria-busy aria-selected aria-labelledby aria-hidden aria-expanded")}),this.tabs.each(function(){var e=t(this),i=e.data("ui-tabs-aria-controls");i?e.attr("aria-controls",i).removeData("ui-tabs-aria-controls"):e.removeAttr("aria-controls")}),this.panels.show(),"content"!==this.options.heightStyle&&this.panels.css("height","")},enable:function(e){var i=this.options.disabled;i!==!1&&(void 0===e?i=!1:(e=this._getIndex(e),i=t.isArray(i)?t.map(i,function(t){return t!==e?t:null}):t.map(this.tabs,function(t,i){return i!==e?i:null})),this._setOptionDisabled(i))},disable:function(e){var i=this.options.disabled;if(i!==!0){if(void 0===e)i=!0;else{if(e=this._getIndex(e),-1!==t.inArray(e,i))return;i=t.isArray(i)?t.merge([e],i).sort():[e]}this._setOptionDisabled(i)}},load:function(e,i){e=this._getIndex(e);var s=this,n=this.tabs.eq(e),a=n.find(".ui-tabs-anchor"),o=this._getPanelForTab(n),r={tab:n,panel:o},h=function(t,e){"abort"===e&&s.panels.stop(!1,!0),s._removeClass(n,"ui-tabs-loading"),o.removeAttr("aria-busy"),t===s.xhr&&delete s.xhr};this._isLocal(a[0])||(this.xhr=t.ajax(this._ajaxSettings(a,i,r)),this.xhr&&"canceled"!==this.xhr.statusText&&(this._addClass(n,"ui-tabs-loading"),o.attr("aria-busy","true"),this.xhr.done(function(t,e,n){setTimeout(function(){o.html(t),s._trigger("load",i,r),h(n,e)},1)}).fail(function(t,e){setTimeout(function(){h(t,e)},1)})))},_ajaxSettings:function(e,i,s){var n=this;return{url:e.attr("href").replace(/#.*$/,""),beforeSend:function(e,a){return n._trigger("beforeLoad",i,t.extend({jqXHR:e,ajaxSettings:a},s))}}},_getPanelForTab:function(e){var i=t(e).attr("aria-controls");return this.element.find(this._sanitizeSelector("#"+i))}}),t.uiBackCompat!==!1&&t.widget("ui.tabs",t.ui.tabs,{_processTabs:function(){this._superApply(arguments),this._addClass(this.tabs,"ui-tab")}}),t.ui.tabs,t.widget("ui.tooltip",{version:"1.12.1",options:{classes:{"ui-tooltip":"ui-corner-all ui-widget-shadow"},content:function(){var e=t(this).attr("title")||"";return t("<a>").text(e).html()},hide:!0,items:"[title]:not([disabled])",position:{my:"left top+15",at:"left bottom",collision:"flipfit flip"},show:!0,track:!1,close:null,open:null},_addDescribedBy:function(e,i){var s=(e.attr("aria-describedby")||"").split(/\s+/);s.push(i),e.data("ui-tooltip-id",i).attr("aria-describedby",t.trim(s.join(" ")))},_removeDescribedBy:function(e){var i=e.data("ui-tooltip-id"),s=(e.attr("aria-describedby")||"").split(/\s+/),n=t.inArray(i,s);-1!==n&&s.splice(n,1),e.removeData("ui-tooltip-id"),s=t.trim(s.join(" ")),s?e.attr("aria-describedby",s):e.removeAttr("aria-describedby")},_create:function(){this._on({mouseover:"open",focusin:"open"}),this.tooltips={},this.parents={},this.liveRegion=t("<div>").attr({role:"log","aria-live":"assertive","aria-relevant":"additions"}).appendTo(this.document[0].body),this._addClass(this.liveRegion,null,"ui-helper-hidden-accessible"),this.disabledTitles=t([])},_setOption:function(e,i){var s=this;this._super(e,i),"content"===e&&t.each(this.tooltips,function(t,e){s._updateContent(e.element)})},_setOptionDisabled:function(t){this[t?"_disable":"_enable"]()},_disable:function(){var e=this;t.each(this.tooltips,function(i,s){var n=t.Event("blur");n.target=n.currentTarget=s.element[0],e.close(n,!0)}),this.disabledTitles=this.disabledTitles.add(this.element.find(this.options.items).addBack().filter(function(){var e=t(this);return e.is("[title]")?e.data("ui-tooltip-title",e.attr("title")).removeAttr("title"):void 0}))},_enable:function(){this.disabledTitles.each(function(){var e=t(this);e.data("ui-tooltip-title")&&e.attr("title",e.data("ui-tooltip-title"))}),this.disabledTitles=t([])},open:function(e){var i=this,s=t(e?e.target:this.element).closest(this.options.items);s.length&&!s.data("ui-tooltip-id")&&(s.attr("title")&&s.data("ui-tooltip-title",s.attr("title")),s.data("ui-tooltip-open",!0),e&&"mouseover"===e.type&&s.parents().each(function(){var e,s=t(this);s.data("ui-tooltip-open")&&(e=t.Event("blur"),e.target=e.currentTarget=this,i.close(e,!0)),s.attr("title")&&(s.uniqueId(),i.parents[this.id]={element:this,title:s.attr("title")},s.attr("title",""))}),this._registerCloseHandlers(e,s),this._updateContent(s,e))},_updateContent:function(t,e){var i,s=this.options.content,n=this,a=e?e.type:null;return"string"==typeof s||s.nodeType||s.jquery?this._open(e,t,s):(i=s.call(t[0],function(i){n._delay(function(){t.data("ui-tooltip-open")&&(e&&(e.type=a),this._open(e,t,i))})}),i&&this._open(e,t,i),void 0)},_open:function(e,i,s){function n(t){l.of=t,o.is(":hidden")||o.position(l)}var a,o,r,h,l=t.extend({},this.options.position);if(s){if(a=this._find(i))return a.tooltip.find(".ui-tooltip-content").html(s),void 0;i.is("[title]")&&(e&&"mouseover"===e.type?i.attr("title",""):i.removeAttr("title")),a=this._tooltip(i),o=a.tooltip,this._addDescribedBy(i,o.attr("id")),o.find(".ui-tooltip-content").html(s),this.liveRegion.children().hide(),h=t("<div>").html(o.find(".ui-tooltip-content").html()),h.removeAttr("name").find("[name]").removeAttr("name"),h.removeAttr("id").find("[id]").removeAttr("id"),h.appendTo(this.liveRegion),this.options.track&&e&&/^mouse/.test(e.type)?(this._on(this.document,{mousemove:n}),n(e)):o.position(t.extend({of:i},this.options.position)),o.hide(),this._show(o,this.options.show),this.options.track&&this.options.show&&this.options.show.delay&&(r=this.delayedShow=setInterval(function(){o.is(":visible")&&(n(l.of),clearInterval(r))},t.fx.interval)),this._trigger("open",e,{tooltip:o})}},_registerCloseHandlers:function(e,i){var s={keyup:function(e){if(e.keyCode===t.ui.keyCode.ESCAPE){var s=t.Event(e);s.currentTarget=i[0],this.close(s,!0)}}};i[0]!==this.element[0]&&(s.remove=function(){this._removeTooltip(this._find(i).tooltip)}),e&&"mouseover"!==e.type||(s.mouseleave="close"),e&&"focusin"!==e.type||(s.focusout="close"),this._on(!0,i,s)},close:function(e){var i,s=this,n=t(e?e.currentTarget:this.element),a=this._find(n);return a?(i=a.tooltip,a.closing||(clearInterval(this.delayedShow),n.data("ui-tooltip-title")&&!n.attr("title")&&n.attr("title",n.data("ui-tooltip-title")),this._removeDescribedBy(n),a.hiding=!0,i.stop(!0),this._hide(i,this.options.hide,function(){s._removeTooltip(t(this))}),n.removeData("ui-tooltip-open"),this._off(n,"mouseleave focusout keyup"),n[0]!==this.element[0]&&this._off(n,"remove"),this._off(this.document,"mousemove"),e&&"mouseleave"===e.type&&t.each(this.parents,function(e,i){t(i.element).attr("title",i.title),delete s.parents[e]}),a.closing=!0,this._trigger("close",e,{tooltip:i}),a.hiding||(a.closing=!1)),void 0):(n.removeData("ui-tooltip-open"),void 0)},_tooltip:function(e){var i=t("<div>").attr("role","tooltip"),s=t("<div>").appendTo(i),n=i.uniqueId().attr("id");return this._addClass(s,"ui-tooltip-content"),this._addClass(i,"ui-tooltip","ui-widget ui-widget-content"),i.appendTo(this._appendTo(e)),this.tooltips[n]={element:e,tooltip:i}},_find:function(t){var e=t.data("ui-tooltip-id");return e?this.tooltips[e]:null},_removeTooltip:function(t){t.remove(),delete this.tooltips[t.attr("id")]},_appendTo:function(t){var e=t.closest(".ui-front, dialog");return e.length||(e=this.document[0].body),e},_destroy:function(){var e=this;t.each(this.tooltips,function(i,s){var n=t.Event("blur"),a=s.element;n.target=n.currentTarget=a[0],e.close(n,!0),t("#"+i).remove(),a.data("ui-tooltip-title")&&(a.attr("title")||a.attr("title",a.data("ui-tooltip-title")),a.removeData("ui-tooltip-title"))}),this.liveRegion.remove()}}),t.uiBackCompat!==!1&&t.widget("ui.tooltip",t.ui.tooltip,{options:{tooltipClass:null},_tooltip:function(){var t=this._superApply(arguments);return this.options.tooltipClass&&t.tooltip.addClass(this.options.tooltipClass),t}}),t.ui.tooltip});
import React, { useMemo, useState, useEffect, createRef } from 'react' import ReactQuill from 'react-quill' import 'react-quill/dist/quill.snow.css' import Dracula from './Dracula' import { createEditor } from 'slate' import { useFocused, Slate, Editable, withReact } from 'slate-react' import { ChakraProvider, Flex, Box } from '@chakra-ui/react' import { isNil } from 'ramda' import { setImageHook, s2m, s2h, q2s, s2q } from 'asteroid-parser' import ImageUploader from 'quill-image-uploader2' import { sha256 } from 'js-sha256' const entities = require('entities') let Parchment = ReactQuill.Quill.import('parchment') let Delta = ReactQuill.Quill.import('delta') let Break = ReactQuill.Quill.import('blots/break') let Embed = ReactQuill.Quill.import('blots/embed') let Block = ReactQuill.Quill.import('blots/block') class SmartBreak extends Break { length() { return 1 } value() { return '\n' } insertInto(parent, ref) { Embed.prototype.insertInto.call(this, parent, ref) } } SmartBreak.blotName = 'inline-break' SmartBreak.tagName = 'BR' const Strike = ReactQuill.Quill.import('formats/strike') Strike.tagName = 'DEL' ReactQuill.Quill.register(Strike, true) function lineBreakMatcher() { let newDelta = new Delta() newDelta.insert({ ['inline-break']: '' }) return newDelta } ReactQuill.Quill.register(SmartBreak) ImageUploader(ReactQuill.Quill) const App = () => { const [editor] = useState(() => withReact(createEditor())) const [qvalue, setQValue] = useState('') const [upV, setUpV] = useState(null) const [isMarkdown, setIsMarkdown] = useState(true) let quillRef = React.createRef() const [value, setValue] = useState([ { type: 'paragraph', children: [{ text: '' }] } ]) useEffect(() => { setImageHook({ fromBase64: url => { if (/^data\:image\/.+/.test(url)) { const img = window.image_map[sha256(url)] if (!isNil(img)) return `data:image/${img.ext};local,${img.id}` } return url }, toBase64: url => { if (/^data\:image\/.+;local,/.test(url)) { const img = window.image_map[url.split(',')[1]] if (!isNil(img)) return img.url } return url } }) }, []) useEffect(() => { if (isMarkdown) { setQValue(s2q(value)) } setUpV(false) }, [value]) useEffect(() => { if (!isMarkdown) { setUpV(true) setValue(q2s(qvalue)) } }, [qvalue]) const options = { toolbar: [ [{ header: [1, 2, 3, 4, 5, 6, false] }], ['bold', 'italic', 'underline', 'strike', 'blockquote', 'link', 'image'], [{ color: [] }, { background: [] }], [{ list: 'ordered' }, { list: 'bullet' }], ['clean'] ], imageUploader: {}, clipboard: { matchers: [['BR', lineBreakMatcher]] }, keyboard: { bindings: { handleEnter: { key: 13, handler: function (range, context) { if (range.length > 0) { this.quill.scroll.deleteAt(range.index, range.length) } let lineFormats = Object.keys(context.format).reduce(function ( lineFormats, format ) { if ( Parchment.query(format, Parchment.Scope.BLOCK) && !Array.isArray(context.format[format]) ) { lineFormats[format] = context.format[format] } return lineFormats }, {}) var previousChar = this.quill.getText(range.index - 1, 1) this.quill.insertText( range.index, '\n', lineFormats, ReactQuill.Quill.sources.USER ) this.quill.setSelection( range.index + 1, ReactQuill.Quill.sources.SILENT ) try { this.quill.selection.scrollIntoView() } catch (e) {} Object.keys(context.format).forEach(name => { if (lineFormats[name] != null) return if (Array.isArray(context.format[name])) return if (name === 'link') return this.quill.format( name, context.format[name], ReactQuill.Quill.sources.USER ) }) } }, linebreak: { key: 13, shiftKey: true, handler: function (range, context) { var nextChar = this.quill.getText(range.index + 1, 1) var ee = this.quill.insertEmbed( range.index, 'inline-break', true, 'user' ) if (nextChar.length == 0) { var ee = this.quill.insertEmbed( range.index, 'inline-break', true, 'user' ) } this.quill.setSelection( range.index + 1, ReactQuill.Quill.sources.SILENT ) } } } } } const modules = useMemo(() => options, []) return ( <ChakraProvider> <Flex height='100vh'> <style global jsx>{` p, .ql-editor p { margin-bottom: 15px; } .quill { display: flex; flex-direction: column; width: 100%; height: 100%; } .ql-container { flex: 1; overflow-y: auto; font-size: 17px; } .ql-editor { border-left: 1px solid #ccc; } .ql-container.ql-snow { border: 0px; } .ql-tooltip { margin-left: 120px; } `}</style> <Dracula /> <Flex bg='#eee' flex={1} direction='column' height='100%'> <Flex direction='column' flex={1} bg='white' sx={{ overflow: 'auto' }} height='50vh' > <Flex color='#222' justify='center' align='center' height='43px' borderBottom='1px solid #ccc' > Slate Editor </Flex> <Box flex={1} p={3} sx={{ wordBreak: 'break-all' }}> {upV ? null : ( <Slate editor={editor} value={value} onChange={newValue => { setIsMarkdown(true) setValue(newValue) }} > <Editable style={{ height: '100%' }} /> </Slate> )} </Box> </Flex> <Flex flex={1} height='50vh'> <Flex direction='column' flex={1} bg='#eee'> <Flex color='#222' justify='center' align='center' height='43px' borderBottom='1px solid #aaa' borderTop='1px solid #aaa' > Markdown </Flex> <Flex p={3} sx={{ overflow: 'auto', wordBreak: 'break-all' }} flex={1} height='100%' dangerouslySetInnerHTML={{ __html: entities .encodeHTML(s2m(value)) .replace(/\&NewLine\;/g, '<br />') }} ></Flex> </Flex> <Flex direction='column' flex={1} bg='#ddd'> <Flex color='#222' justify='center' align='center' height='43px' borderBottom='1px solid #aaa' borderTop='1px solid #aaa' > HTML </Flex> <Flex p={3} sx={{ overflow: 'auto', wordBreak: 'break-all' }} bg='#ddd' flex={1} height='100%' dangerouslySetInnerHTML={{ __html: entities .encodeHTML(s2h(value)) .replace(/\&NewLine\;/g, '<br />') }} /> </Flex> </Flex> </Flex> <Flex bg='#ddd' flex={1} direction='column'> <Box flex={1} bg='white' sx={{ overflow: 'auto' }}> <ReactQuill ref={el => { if (!isNil(el) && isNil(quillRef)) quillRef = el.getEditor() }} theme='snow' value={qvalue} onChange={(val, d, s, e) => { setQValue(val) }} modules={modules} onFocus={() => setIsMarkdown(false)} onBlur={() => setIsMarkdown(true)} /> </Box> <Flex bg='#ccc' direction='column' flex={1} sx={{ overflow: 'auto' }}> <Flex color='#222' justify='center' align='center' height='43px' borderBottom='1px solid #aaa' borderTop='1px solid #aaa' > Preview </Flex> <Box p={3} flex={1} height='100%' dangerouslySetInnerHTML={{ __html: s2h(value) }} /> </Flex> </Flex> </Flex> </ChakraProvider> ) } export default App
import * as THREE from 'three'; import { UIPanel, UIRow, UIInput, UIButton, UIColor, UICheckbox, UIInteger, UITextArea, UIText, UINumber } from './libs/ui.js'; import { UIBoolean } from './libs/ui.three.js'; import { SetUuidCommand } from './commands/SetUuidCommand.js'; import { SetValueCommand } from './commands/SetValueCommand.js'; import { SetPositionCommand } from './commands/SetPositionCommand.js'; import { SetRotationCommand } from './commands/SetRotationCommand.js'; import { SetScaleCommand } from './commands/SetScaleCommand.js'; import { SetColorCommand } from './commands/SetColorCommand.js'; function SidebarObject( editor ) { const strings = editor.strings; const signals = editor.signals; const container = new UIPanel(); container.setBorderTop( '0' ); container.setPaddingTop( '20px' ); container.setDisplay( 'none' ); // Actions /* let objectActions = new UI.Select().setPosition( 'absolute' ).setRight( '8px' ).setFontSize( '11px' ); objectActions.setOptions( { 'Actions': 'Actions', 'Reset Position': 'Reset Position', 'Reset Rotation': 'Reset Rotation', 'Reset Scale': 'Reset Scale' } ); objectActions.onClick( function ( event ) { event.stopPropagation(); // Avoid panel collapsing } ); objectActions.onChange( function ( event ) { let object = editor.selected; switch ( this.getValue() ) { case 'Reset Position': editor.execute( new SetPositionCommand( editor, object, new Vector3( 0, 0, 0 ) ) ); break; case 'Reset Rotation': editor.execute( new SetRotationCommand( editor, object, new Euler( 0, 0, 0 ) ) ); break; case 'Reset Scale': editor.execute( new SetScaleCommand( editor, object, new Vector3( 1, 1, 1 ) ) ); break; } this.setValue( 'Actions' ); } ); container.addStatic( objectActions ); */ // type const objectTypeRow = new UIRow(); const objectType = new UIText(); objectTypeRow.add( new UIText( strings.getKey( 'sidebar/object/type' ) ).setWidth( '90px' ) ); objectTypeRow.add( objectType ); container.add( objectTypeRow ); // uuid const objectUUIDRow = new UIRow(); const objectUUID = new UIInput().setWidth( '102px' ).setFontSize( '12px' ).setDisabled( true ); const objectUUIDRenew = new UIButton( strings.getKey( 'sidebar/object/new' ) ).setMarginLeft( '7px' ).onClick( function () { objectUUID.setValue( THREE.MathUtils.generateUUID() ); editor.execute( new SetUuidCommand( editor, editor.selected, objectUUID.getValue() ) ); } ); objectUUIDRow.add( new UIText( strings.getKey( 'sidebar/object/uuid' ) ).setWidth( '90px' ) ); objectUUIDRow.add( objectUUID ); objectUUIDRow.add( objectUUIDRenew ); container.add( objectUUIDRow ); // name const objectNameRow = new UIRow(); const objectName = new UIInput().setWidth( '150px' ).setFontSize( '12px' ).onChange( function () { editor.execute( new SetValueCommand( editor, editor.selected, 'name', objectName.getValue() ) ); } ); objectNameRow.add( new UIText( strings.getKey( 'sidebar/object/name' ) ).setWidth( '90px' ) ); objectNameRow.add( objectName ); container.add( objectNameRow ); // position const objectPositionRow = new UIRow(); const objectPositionX = new UINumber().setPrecision( 3 ).setWidth( '50px' ).onChange( update ); const objectPositionY = new UINumber().setPrecision( 3 ).setWidth( '50px' ).onChange( update ); const objectPositionZ = new UINumber().setPrecision( 3 ).setWidth( '50px' ).onChange( update ); objectPositionRow.add( new UIText( strings.getKey( 'sidebar/object/position' ) ).setWidth( '90px' ) ); objectPositionRow.add( objectPositionX, objectPositionY, objectPositionZ ); container.add( objectPositionRow ); // rotation const objectRotationRow = new UIRow(); const objectRotationX = new UINumber().setStep( 10 ).setNudge( 0.1 ).setUnit( '°' ).setWidth( '50px' ).onChange( update ); const objectRotationY = new UINumber().setStep( 10 ).setNudge( 0.1 ).setUnit( '°' ).setWidth( '50px' ).onChange( update ); const objectRotationZ = new UINumber().setStep( 10 ).setNudge( 0.1 ).setUnit( '°' ).setWidth( '50px' ).onChange( update ); objectRotationRow.add( new UIText( strings.getKey( 'sidebar/object/rotation' ) ).setWidth( '90px' ) ); objectRotationRow.add( objectRotationX, objectRotationY, objectRotationZ ); container.add( objectRotationRow ); // scale const objectScaleRow = new UIRow(); const objectScaleX = new UINumber( 1 ).setPrecision( 3 ).setWidth( '50px' ).onChange( update ); const objectScaleY = new UINumber( 1 ).setPrecision( 3 ).setWidth( '50px' ).onChange( update ); const objectScaleZ = new UINumber( 1 ).setPrecision( 3 ).setWidth( '50px' ).onChange( update ); objectScaleRow.add( new UIText( strings.getKey( 'sidebar/object/scale' ) ).setWidth( '90px' ) ); objectScaleRow.add( objectScaleX, objectScaleY, objectScaleZ ); container.add( objectScaleRow ); // fov const objectFovRow = new UIRow(); const objectFov = new UINumber().onChange( update ); objectFovRow.add( new UIText( strings.getKey( 'sidebar/object/fov' ) ).setWidth( '90px' ) ); objectFovRow.add( objectFov ); container.add( objectFovRow ); // left const objectLeftRow = new UIRow(); const objectLeft = new UINumber().onChange( update ); objectLeftRow.add( new UIText( strings.getKey( 'sidebar/object/left' ) ).setWidth( '90px' ) ); objectLeftRow.add( objectLeft ); container.add( objectLeftRow ); // right const objectRightRow = new UIRow(); const objectRight = new UINumber().onChange( update ); objectRightRow.add( new UIText( strings.getKey( 'sidebar/object/right' ) ).setWidth( '90px' ) ); objectRightRow.add( objectRight ); container.add( objectRightRow ); // top const objectTopRow = new UIRow(); const objectTop = new UINumber().onChange( update ); objectTopRow.add( new UIText( strings.getKey( 'sidebar/object/top' ) ).setWidth( '90px' ) ); objectTopRow.add( objectTop ); container.add( objectTopRow ); // bottom const objectBottomRow = new UIRow(); const objectBottom = new UINumber().onChange( update ); objectBottomRow.add( new UIText( strings.getKey( 'sidebar/object/bottom' ) ).setWidth( '90px' ) ); objectBottomRow.add( objectBottom ); container.add( objectBottomRow ); // near const objectNearRow = new UIRow(); const objectNear = new UINumber().onChange( update ); objectNearRow.add( new UIText( strings.getKey( 'sidebar/object/near' ) ).setWidth( '90px' ) ); objectNearRow.add( objectNear ); container.add( objectNearRow ); // far const objectFarRow = new UIRow(); const objectFar = new UINumber().onChange( update ); objectFarRow.add( new UIText( strings.getKey( 'sidebar/object/far' ) ).setWidth( '90px' ) ); objectFarRow.add( objectFar ); container.add( objectFarRow ); // intensity const objectIntensityRow = new UIRow(); const objectIntensity = new UINumber().onChange( update ); objectIntensityRow.add( new UIText( strings.getKey( 'sidebar/object/intensity' ) ).setWidth( '90px' ) ); objectIntensityRow.add( objectIntensity ); container.add( objectIntensityRow ); // color const objectColorRow = new UIRow(); const objectColor = new UIColor().onInput( update ); objectColorRow.add( new UIText( strings.getKey( 'sidebar/object/color' ) ).setWidth( '90px' ) ); objectColorRow.add( objectColor ); container.add( objectColorRow ); // ground color const objectGroundColorRow = new UIRow(); const objectGroundColor = new UIColor().onInput( update ); objectGroundColorRow.add( new UIText( strings.getKey( 'sidebar/object/groundcolor' ) ).setWidth( '90px' ) ); objectGroundColorRow.add( objectGroundColor ); container.add( objectGroundColorRow ); // distance const objectDistanceRow = new UIRow(); const objectDistance = new UINumber().setRange( 0, Infinity ).onChange( update ); objectDistanceRow.add( new UIText( strings.getKey( 'sidebar/object/distance' ) ).setWidth( '90px' ) ); objectDistanceRow.add( objectDistance ); container.add( objectDistanceRow ); // angle const objectAngleRow = new UIRow(); const objectAngle = new UINumber().setPrecision( 3 ).setRange( 0, Math.PI / 2 ).onChange( update ); objectAngleRow.add( new UIText( strings.getKey( 'sidebar/object/angle' ) ).setWidth( '90px' ) ); objectAngleRow.add( objectAngle ); container.add( objectAngleRow ); // penumbra const objectPenumbraRow = new UIRow(); const objectPenumbra = new UINumber().setRange( 0, 1 ).onChange( update ); objectPenumbraRow.add( new UIText( strings.getKey( 'sidebar/object/penumbra' ) ).setWidth( '90px' ) ); objectPenumbraRow.add( objectPenumbra ); container.add( objectPenumbraRow ); // decay const objectDecayRow = new UIRow(); const objectDecay = new UINumber().setRange( 0, Infinity ).onChange( update ); objectDecayRow.add( new UIText( strings.getKey( 'sidebar/object/decay' ) ).setWidth( '90px' ) ); objectDecayRow.add( objectDecay ); container.add( objectDecayRow ); // shadow const objectShadowRow = new UIRow(); objectShadowRow.add( new UIText( strings.getKey( 'sidebar/object/shadow' ) ).setWidth( '90px' ) ); const objectCastShadow = new UIBoolean( false, strings.getKey( 'sidebar/object/cast' ) ).onChange( update ); objectShadowRow.add( objectCastShadow ); const objectReceiveShadow = new UIBoolean( false, strings.getKey( 'sidebar/object/receive' ) ).onChange( update ); objectShadowRow.add( objectReceiveShadow ); container.add( objectShadowRow ); // shadow bias const objectShadowBiasRow = new UIRow(); objectShadowBiasRow.add( new UIText( strings.getKey( 'sidebar/object/shadowBias' ) ).setWidth( '90px' ) ); const objectShadowBias = new UINumber( 0 ).setPrecision( 5 ).setStep( 0.0001 ).setNudge( 0.00001 ).onChange( update ); objectShadowBiasRow.add( objectShadowBias ); container.add( objectShadowBiasRow ); // shadow normal offset const objectShadowNormalBiasRow = new UIRow(); objectShadowNormalBiasRow.add( new UIText( strings.getKey( 'sidebar/object/shadowNormalBias' ) ).setWidth( '90px' ) ); const objectShadowNormalBias = new UINumber( 0 ).onChange( update ); objectShadowNormalBiasRow.add( objectShadowNormalBias ); container.add( objectShadowNormalBiasRow ); // shadow radius const objectShadowRadiusRow = new UIRow(); objectShadowRadiusRow.add( new UIText( strings.getKey( 'sidebar/object/shadowRadius' ) ).setWidth( '90px' ) ); const objectShadowRadius = new UINumber( 1 ).onChange( update ); objectShadowRadiusRow.add( objectShadowRadius ); container.add( objectShadowRadiusRow ); // visible const objectVisibleRow = new UIRow(); const objectVisible = new UICheckbox().onChange( update ); objectVisibleRow.add( new UIText( strings.getKey( 'sidebar/object/visible' ) ).setWidth( '90px' ) ); objectVisibleRow.add( objectVisible ); container.add( objectVisibleRow ); // bloom const objectBloomRow = new UIRow(); const objectBloom = new UICheckbox().onChange( update ); objectBloomRow.add( new UIText( strings.getKey( 'sidebar/object/bloom' ) ).setWidth( '90px' ) ); objectBloomRow.add( objectBloom ); container.add( objectBloomRow ); // frustumCulled const objectFrustumCulledRow = new UIRow(); const objectFrustumCulled = new UICheckbox().onChange( update ); objectFrustumCulledRow.add( new UIText( strings.getKey( 'sidebar/object/frustumcull' ) ).setWidth( '90px' ) ); objectFrustumCulledRow.add( objectFrustumCulled ); container.add( objectFrustumCulledRow ); // renderOrder const objectRenderOrderRow = new UIRow(); const objectRenderOrder = new UIInteger().setWidth( '50px' ).onChange( update ); objectRenderOrderRow.add( new UIText( strings.getKey( 'sidebar/object/renderorder' ) ).setWidth( '90px' ) ); objectRenderOrderRow.add( objectRenderOrder ); container.add( objectRenderOrderRow ); // user data const objectUserDataRow = new UIRow(); const objectUserData = new UITextArea().setWidth( '150px' ).setHeight( '40px' ).setFontSize( '12px' ).onChange( update ); objectUserData.onKeyUp( function () { try { JSON.parse( objectUserData.getValue() ); objectUserData.dom.classList.add( 'success' ); objectUserData.dom.classList.remove( 'fail' ); } catch ( error ) { objectUserData.dom.classList.remove( 'success' ); objectUserData.dom.classList.add( 'fail' ); } } ); objectUserDataRow.add( new UIText( strings.getKey( 'sidebar/object/userdata' ) ).setWidth( '90px' ) ); objectUserDataRow.add( objectUserData ); container.add( objectUserDataRow ); // function update() { const object = editor.selected; if ( object !== null ) { const newPosition = new THREE.Vector3( objectPositionX.getValue(), objectPositionY.getValue(), objectPositionZ.getValue() ); if ( object.position.distanceTo( newPosition ) >= 0.01 ) { editor.execute( new SetPositionCommand( editor, object, newPosition ) ); } const newRotation = new THREE.Euler( objectRotationX.getValue() * THREE.MathUtils.DEG2RAD, objectRotationY.getValue() * THREE.MathUtils.DEG2RAD, objectRotationZ.getValue() * THREE.MathUtils.DEG2RAD ); if ( new THREE.Vector3().setFromEuler( object.rotation ).distanceTo( new THREE.Vector3().setFromEuler( newRotation ) ) >= 0.01 ) { editor.execute( new SetRotationCommand( editor, object, newRotation ) ); } const newScale = new THREE.Vector3( objectScaleX.getValue(), objectScaleY.getValue(), objectScaleZ.getValue() ); if ( object.scale.distanceTo( newScale ) >= 0.01 ) { editor.execute( new SetScaleCommand( editor, object, newScale ) ); } if ( object.fov !== undefined && Math.abs( object.fov - objectFov.getValue() ) >= 0.01 ) { editor.execute( new SetValueCommand( editor, object, 'fov', objectFov.getValue() ) ); object.updateProjectionMatrix(); } if ( object.left !== undefined && Math.abs( object.left - objectLeft.getValue() ) >= 0.01 ) { editor.execute( new SetValueCommand( editor, object, 'left', objectLeft.getValue() ) ); object.updateProjectionMatrix(); } if ( object.right !== undefined && Math.abs( object.right - objectRight.getValue() ) >= 0.01 ) { editor.execute( new SetValueCommand( editor, object, 'right', objectRight.getValue() ) ); object.updateProjectionMatrix(); } if ( object.top !== undefined && Math.abs( object.top - objectTop.getValue() ) >= 0.01 ) { editor.execute( new SetValueCommand( editor, object, 'top', objectTop.getValue() ) ); object.updateProjectionMatrix(); } if ( object.bottom !== undefined && Math.abs( object.bottom - objectBottom.getValue() ) >= 0.01 ) { editor.execute( new SetValueCommand( editor, object, 'bottom', objectBottom.getValue() ) ); object.updateProjectionMatrix(); } if ( object.near !== undefined && Math.abs( object.near - objectNear.getValue() ) >= 0.01 ) { editor.execute( new SetValueCommand( editor, object, 'near', objectNear.getValue() ) ); if ( object.isOrthographicCamera ) { object.updateProjectionMatrix(); } } if ( object.far !== undefined && Math.abs( object.far - objectFar.getValue() ) >= 0.01 ) { editor.execute( new SetValueCommand( editor, object, 'far', objectFar.getValue() ) ); if ( object.isOrthographicCamera ) { object.updateProjectionMatrix(); } } if ( object.intensity !== undefined && Math.abs( object.intensity - objectIntensity.getValue() ) >= 0.01 ) { editor.execute( new SetValueCommand( editor, object, 'intensity', objectIntensity.getValue() ) ); } if ( object.color !== undefined && object.color.getHex() !== objectColor.getHexValue() ) { editor.execute( new SetColorCommand( editor, object, 'color', objectColor.getHexValue() ) ); } if ( object.groundColor !== undefined && object.groundColor.getHex() !== objectGroundColor.getHexValue() ) { editor.execute( new SetColorCommand( editor, object, 'groundColor', objectGroundColor.getHexValue() ) ); } if ( object.distance !== undefined && Math.abs( object.distance - objectDistance.getValue() ) >= 0.01 ) { editor.execute( new SetValueCommand( editor, object, 'distance', objectDistance.getValue() ) ); } if ( object.angle !== undefined && Math.abs( object.angle - objectAngle.getValue() ) >= 0.01 ) { editor.execute( new SetValueCommand( editor, object, 'angle', objectAngle.getValue() ) ); } if ( object.penumbra !== undefined && Math.abs( object.penumbra - objectPenumbra.getValue() ) >= 0.01 ) { editor.execute( new SetValueCommand( editor, object, 'penumbra', objectPenumbra.getValue() ) ); } if ( object.decay !== undefined && Math.abs( object.decay - objectDecay.getValue() ) >= 0.01 ) { editor.execute( new SetValueCommand( editor, object, 'decay', objectDecay.getValue() ) ); } if ( object.visible !== objectVisible.getValue() ) { editor.execute( new SetValueCommand( editor, object, 'visible', objectVisible.getValue() ) ); } if ( object.bloom !== objectBloom.getValue() ) { //editor.execute( new SetValueCommand( editor, object, 'layers', objectBloom.getValue() ) ); if(objectBloom.getValue()){ object.layers.enable(1); } else { object.layers.disable(1); } console.log('changed bloom layers', object.layers); } if ( object.frustumCulled !== objectFrustumCulled.getValue() ) { editor.execute( new SetValueCommand( editor, object, 'frustumCulled', objectFrustumCulled.getValue() ) ); } if ( object.renderOrder !== objectRenderOrder.getValue() ) { editor.execute( new SetValueCommand( editor, object, 'renderOrder', objectRenderOrder.getValue() ) ); } if ( object.castShadow !== undefined && object.castShadow !== objectCastShadow.getValue() ) { editor.execute( new SetValueCommand( editor, object, 'castShadow', objectCastShadow.getValue() ) ); } if ( object.receiveShadow !== objectReceiveShadow.getValue() ) { if ( object.material !== undefined ) object.material.needsUpdate = true; editor.execute( new SetValueCommand( editor, object, 'receiveShadow', objectReceiveShadow.getValue() ) ); } if ( object.shadow !== undefined ) { if ( object.shadow.bias !== objectShadowBias.getValue() ) { editor.execute( new SetValueCommand( editor, object.shadow, 'bias', objectShadowBias.getValue() ) ); } if ( object.shadow.normalBias !== objectShadowNormalBias.getValue() ) { editor.execute( new SetValueCommand( editor, object.shadow, 'normalBias', objectShadowNormalBias.getValue() ) ); } if ( object.shadow.radius !== objectShadowRadius.getValue() ) { editor.execute( new SetValueCommand( editor, object.shadow, 'radius', objectShadowRadius.getValue() ) ); } } try { const userData = JSON.parse( objectUserData.getValue() ); if ( JSON.stringify( object.userData ) != JSON.stringify( userData ) ) { editor.execute( new SetValueCommand( editor, object, 'userData', userData ) ); } } catch ( exception ) { console.warn( exception ); } } } function updateRows( object ) { const properties = { 'fov': objectFovRow, 'left': objectLeftRow, 'right': objectRightRow, 'top': objectTopRow, 'bottom': objectBottomRow, 'near': objectNearRow, 'far': objectFarRow, 'intensity': objectIntensityRow, 'color': objectColorRow, 'groundColor': objectGroundColorRow, 'distance': objectDistanceRow, 'angle': objectAngleRow, 'penumbra': objectPenumbraRow, 'decay': objectDecayRow, 'castShadow': objectShadowRow, 'receiveShadow': objectReceiveShadow, 'shadow': [ objectShadowBiasRow, objectShadowNormalBiasRow, objectShadowRadiusRow ] }; for ( const property in properties ) { const uiElement = properties[ property ]; if ( Array.isArray( uiElement ) === true ) { for ( let i = 0; i < uiElement.length; i ++ ) { uiElement[ i ].setDisplay( object[ property ] !== undefined ? '' : 'none' ); } } else { uiElement.setDisplay( object[ property ] !== undefined ? '' : 'none' ); } } // if ( object.isLight ) { objectReceiveShadow.setDisplay( 'none' ); } if ( object.isAmbientLight || object.isHemisphereLight ) { objectShadowRow.setDisplay( 'none' ); } } function updateTransformRows( object ) { if ( object.isLight || ( object.isObject3D && object.userData.targetInverse ) ) { objectRotationRow.setDisplay( 'none' ); objectScaleRow.setDisplay( 'none' ); } else { objectRotationRow.setDisplay( '' ); objectScaleRow.setDisplay( '' ); } } // events signals.objectSelected.add( function ( object ) { if ( object !== null ) { container.setDisplay( 'block' ); updateRows( object ); updateUI( object ); } else { container.setDisplay( 'none' ); } } ); signals.objectChanged.add( function ( object ) { if ( object !== editor.selected ) return; updateUI( object ); } ); signals.refreshSidebarObject3D.add( function ( object ) { if ( object !== editor.selected ) return; updateUI( object ); } ); function updateUI( object ) { objectType.setValue( object.type ); objectUUID.setValue( object.uuid ); objectName.setValue( object.name ); objectPositionX.setValue( object.position.x ); objectPositionY.setValue( object.position.y ); objectPositionZ.setValue( object.position.z ); objectRotationX.setValue( object.rotation.x * THREE.MathUtils.RAD2DEG ); objectRotationY.setValue( object.rotation.y * THREE.MathUtils.RAD2DEG ); objectRotationZ.setValue( object.rotation.z * THREE.MathUtils.RAD2DEG ); objectScaleX.setValue( object.scale.x ); objectScaleY.setValue( object.scale.y ); objectScaleZ.setValue( object.scale.z ); if ( object.fov !== undefined ) { objectFov.setValue( object.fov ); } if ( object.left !== undefined ) { objectLeft.setValue( object.left ); } if ( object.right !== undefined ) { objectRight.setValue( object.right ); } if ( object.top !== undefined ) { objectTop.setValue( object.top ); } if ( object.bottom !== undefined ) { objectBottom.setValue( object.bottom ); } if ( object.near !== undefined ) { objectNear.setValue( object.near ); } if ( object.far !== undefined ) { objectFar.setValue( object.far ); } if ( object.intensity !== undefined ) { objectIntensity.setValue( object.intensity ); } if ( object.color !== undefined ) { objectColor.setHexValue( object.color.getHexString() ); } if ( object.groundColor !== undefined ) { objectGroundColor.setHexValue( object.groundColor.getHexString() ); } if ( object.distance !== undefined ) { objectDistance.setValue( object.distance ); } if ( object.angle !== undefined ) { objectAngle.setValue( object.angle ); } if ( object.penumbra !== undefined ) { objectPenumbra.setValue( object.penumbra ); } if ( object.decay !== undefined ) { objectDecay.setValue( object.decay ); } if ( object.castShadow !== undefined ) { objectCastShadow.setValue( object.castShadow ); } if ( object.receiveShadow !== undefined ) { objectReceiveShadow.setValue( object.receiveShadow ); } if ( object.shadow !== undefined ) { objectShadowBias.setValue( object.shadow.bias ); objectShadowNormalBias.setValue( object.shadow.normalBias ); objectShadowRadius.setValue( object.shadow.radius ); } objectVisible.setValue( object.visible ); objectBloom.setValue( object.layers.mask == 3); console.log(object.layers); objectFrustumCulled.setValue( object.frustumCulled ); objectRenderOrder.setValue( object.renderOrder ); try { objectUserData.setValue( JSON.stringify( object.userData, null, ' ' ) ); } catch ( error ) { console.log( error ); } objectUserData.setBorderColor( 'transparent' ); objectUserData.setBackgroundColor( '' ); updateTransformRows( object ); } return container; } export { SidebarObject };
const debug = require('debug'); module.exports = module => debug(`${global.APP_NAME}:${module}`);
var ver = "AUDIO/VIDEO PLAYER VERSION 1.0"; //why do we have a version number for this script thats stupid. var audioplayer = document.getElementById("playing"); var videoplayer = document.getElementById("videoplayer"); var currentsystem = ""; var currentlyplay = document.getElementById("cupl"); var currentlyplayingbtn = document.getElementById("cup"); currentlyplayingbtn.style.display = "none"; function play(src, type = "audio"){ if(type == "audio"){ stop(); videoplayer.style.display = "none"; audioplayer.style.display = "block"; audioplayer.src = src; audioplayer.play(); currentlyplayingbtn.style.display = "block"; videoplayer.style.display = "none"; currentsystem = "audio"; sectiondiv(event, "currentlyplaying","#00a2ff","#ab34e6") currentlyplay.innerHTML = src.split(/_(.+)/)[1]; }else if(type == "video"){ stop(); videoplayer.style.display = "block"; audioplayer.style.display = "none"; videoplayer.src = src; videoplayer.play(); currentlyplayingbtn.style.display = "block"; currentsystem = "video"; sectiondiv(event, "currentlyplaying","#00a2ff","#ab34e6") currentlyplay.innerHTML = src.split(/_(.+)/)[1]; }else{ swal("ERROR", `${type} does not exist as a type of file`, "error"); } } //TODO: add extra functions for custom stuff. function stop(){ if(currentsystem == "audio"){ audioplayer.pause(); audioplayer.currentTime = 0; }else if(currentsystem == "video"){ videoplayer.pause(); videoplayer.currentTime = 0; } } function pause(){ if(currentsystem == "audio"){ audioplayer.pause(); }else if(currentsystem == "video"){ videoplayer.pause(); } } function shoottostart(){ if(currentsystem == "audio"){ audioplayer.currentTime = 0; }else if(currentsystem == "video"){ videoplayer.currentTime = 0; } } function apclose(){ stop(); document.title="Welcome to enclica."; currentlyplayingbtn.style.display = "none"; sectiondiv(event, "chats","#00a2ff","#ab34e6") }
import React from 'react' import {findDOMNode} from 'react-dom'; import * as widgetUtil from '../helpers/widgetUtil'; import {SomethingWithIcon, Icons} from '../index'; const ColorPicker = require('../common/colorpicker'); const CaptionComponent = require('../CaptionComponent/CaptionComponent'); const Button = require('../common/Button'); const EducativeUtil = require('../common/ed_util'); const Vivus = require('vivus'); const PureMixin = require('react-pure-render/mixin'); import {FormControl, OverlayTrigger, Tooltip} from 'react-bootstrap'; let selectedLinkedList = null; const LinkedListD3 = React.createClass({ mixins: [PureMixin], getInitialState() { return { prevSelectedNodeId: -1, }; }, componentDidMount() { this.createLinkedList(); this.setClickHandlers(); }, componentWillReceiveProps(nextProps) { this.setState({ prevSelectedNodeId: this.props.selectedNodeId, }); }, componentDidUpdate() { this.createLinkedList(); this.setClickHandlers(); this.applySelectedNodeStyle(); }, applySelectedNodeStyle() { if (this.props.mode != "edit") { return; } const dom = findDOMNode(this); // reset styling on previously selected node. if (this.state.prevSelectedNodeId != -1 && this.state.prevSelectedNodeId != this.props.selectedNodeId) { const tempNode = this.findNode(this.state.prevSelectedNodeId); if (tempNode) { const tempNodeRgb = this.hexToRgb(tempNode.fillcolor); const rgb_string = "rgb({0}, {1}, {2})".format(tempNodeRgb.r, tempNodeRgb.g, tempNodeRgb.b); var selectedNodeIdValue = `#${this.state.prevSelectedNodeId}`; var nodeToSelect = $(dom).find(selectedNodeIdValue).find("path"); nodeToSelect.attr("fill", rgb_string); nodeToSelect.attr("stroke", "rgb(0, 0, 0)"); nodeToSelect.attr("stroke-width", "0.5px"); nodeToSelect.attr("stroke-dasharray", "none"); } } // apply styling on selected node. if (this.props.selectedNodeId != -1) { var selectedNodeIdValue = `#${this.props.selectedNodeId}`; var nodeToSelect = $(dom).find(selectedNodeIdValue).find("path"); nodeToSelect.attr("stroke", "rgb(0, 0, 0)"); nodeToSelect.attr("stroke-width", "1.5px"); nodeToSelect.attr("stroke-dasharray", "5px, 2px"); } }, createGraphvizCodeString() { const nodes = this.props.nodes; let graph_string = 'rankdir=LR; node [fontname = "courier", fontsize=16]; bgcolor="transparent";'; let style = 'filled'; const node_format_string = '{0}[id="{0}" label="{1}" stroke="{2}" fillcolor="{3}" style="{4}" shape={5} width=0.4 height=0.4, penwidth=0.5];'; let lastNodeKey = null; for (let i = 0; i < nodes.length; i++) { const node = nodes[i]; style = 'filled'; let content; if (!this.props.version || this.props.version == '1.0') { content = node.content; } else { content = EducativeUtil.escapeGraphvizLabels(node.content); } const nodeContent = content == "" ? " " : content; graph_string += node_format_string.format(node.id, nodeContent, node.fillcolor, node.fillcolor, style, "Mrecord"); lastNodeKey = node.id; } const edge_format_string = "{0}->{1}[arrowsize=0.8, penwidth=0.6, fillcolor=gray25, stroke=gray25];"; let prev = null; for (let i = 0; i < nodes.length; i++) { if (prev != null) { graph_string += edge_format_string.format(prev, nodes[i].id); } prev = nodes[i].id; } graph_string = `digraph {${graph_string}}`; return graph_string; }, createLinkedList() { let svgString; if (!this.props.svg_string) { // console.log('________Generating SVG String_______*******_______'); const graph_string = this.createGraphvizCodeString(); svgString = widgetUtil.generateSvgFromGraphviz(graph_string); } else { svgString = this.props.svg_string; // console.log('________Generating SVG String_______SKIPPED_______'); } const dom = findDOMNode(this); dom.innerHTML = svgString; this.props.onSvgUpdate(svgString); }, findNode(nodeId) { const nodes = this.props.nodes; for (let i = 0; i < nodes.length; i++) { const node = nodes[i]; if (node.id == nodeId) { return node; } } return null; }, hexToRgb(hex) { // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF") const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i; hex = hex.replace(shorthandRegex, function (m, r, g, b) { return r + r + g + g + b + b; }); const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return (result ? { r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16), } : null); }, setClickHandlers() { if (this.props.mode != "edit") { return; } const onClickNodeCallback = this.props.onClickNodeCallback; const domElement = d3.select(findDOMNode(this)); domElement.selectAll("g.node").on('click', function () { const id = this.id; onClickNodeCallback(id); d3.event.stopPropagation(); }); }, render() { return ( <div width="100%" style={{display:'inline-block'}}></div> ); }, }); class LinkedList extends React.Component { constructor(props, context) { super(props, context); this.addNodeCallback = this.addNodeCallback.bind(this); this.changeDrawEffect = this.changeDrawEffect.bind(this); this.clearSelection = this.clearSelection.bind(this); this.handleCaptionChange = this.handleCaptionChange.bind(this); this.handleKeyDown = this.handleKeyDown.bind(this); this.onClickNodeCallback = this.onClickNodeCallback.bind(this); this.onColorChanged = this.onColorChanged.bind(this); this.onSvgUpdate = this.onSvgUpdate.bind(this); this.onValueChange = this.onValueChange.bind(this); this.removeNodeCallback = this.removeNodeCallback.bind(this); this.state = { selectedNodeId: -1, id: EducativeUtil.getKey(), }; } componentDidMount() { if(this.props.mode == 'view'){ this.setupVivusEffect(); } else { if(this.state.selectedNodeId != -1){ this.setNodeValueInInput(); } } } shouldComponentUpdate(nextProps, nextState) { const result = this.props.content !== nextProps.content || this.props.mode !== nextProps.mode || nextState.selectedNodeId != -1 || nextState.selectedNodeId !== this.state.selectedNodeId || this.props.pageProperties !== nextProps.pageProperties; return result; } componentDidUpdate() { if(this.props.mode == 'view'){ this.setupVivusEffect(); } else { if(this.state.selectedNodeId != -1){ this.setNodeValueInInput(); } } } addNodeCallback() { const nodes = this.props.content.nodes; const length = nodes.length; let newNode; if (length > 0) { const lastNode = nodes[length - 1]; newNode = { id: `node_${String(EducativeUtil.getKey())}`, content: lastNode.content, x: lastNode.x, y: lastNode.y, fillcolor: lastNode.fillcolor, textcolor: lastNode.textcolor, strokecolor: lastNode.strokecolor, }; } else { newNode = LinkedList.getDefaultNodes()[0]; } this.props.updateContentState({ nodes: [...nodes, newNode], svg_string: null, }); } changeDrawEffect() { this.props.updateContentState({draw_effect: !this.props.content.draw_effect}); } clearSelection() { this.setState({selectedNodeId: -1}); } findNodeIndex(node_id) { for (let i = 0; i < this.props.content.nodes.length; i++) { if (this.props.content.nodes[i].id == node_id) { return i; } } return -1; } handleCaptionChange(caption) { this.props.updateContentState({caption}); } handleKeyDown(e) { if (e.key === 'Enter'){ this.updateNodeValue(findDOMNode(this.nodeValueInputRef).value); this.clearSelection(); } else if(e.key === 'Escape') { this.clearSelection(); } else { return; } } onClickNodeCallback(node_id) { selectedLinkedList = this.state.id; this.setState({selectedNodeId: node_id}); if (this.nodeValueInputRef) { const $input = findDOMNode(this.nodeValueInputRef); $input.focus(); $input.select(); } } onColorChanged(colorValue) { if (colorValue.charAt(0) != '#') { colorValue = `#${colorValue}`; } // length must be >= 2 including # if (colorValue.length < 2) { return; } const selectedNodeIndex = this.findNodeIndex(this.state.selectedNodeId); const nodes = this.props.content.nodes; if (nodes[selectedNodeIndex].fillcolor != colorValue) { this.props.updateContentState({ nodes: [ ...nodes.slice(0, selectedNodeIndex), {...nodes[selectedNodeIndex], fillcolor: colorValue}, ...nodes.slice(selectedNodeIndex + 1), ], svg_string: null, }); } } onSvgUpdate(svg_string) { this.props.updateContentState({svg_string}); } onValueChange(event) { this.updateNodeValue(event.target.value); } removeNodeCallback() { const nodeIndex = this.findNodeIndex(this.state.selectedNodeId); const nodes = this.props.content.nodes; let newNodes; if (nodes.length == 1 && nodes[0].id == this.state.selectedNodeId) { newNodes = []; } else { newNodes = [ ...nodes.slice(0, nodeIndex), ...nodes.slice(nodeIndex + 1), ]; } this.state.selectedNodeId = -1; this.props.updateContentState({ nodes: newNodes, svg_string: null, }); } setNodeValueInInput() { if(this.nodeValueInputRef) { const selectedNodeIndex = this.findNodeIndex(this.state.selectedNodeId); findDOMNode(this.nodeValueInputRef).value= this.props.content.nodes[selectedNodeIndex].content; } } setupVivusEffect() { if(this.refs.dsRender && this.props.content.draw_effect){ new Vivus( findDOMNode(this.refs.dsRender).children[0], { type: 'oneByOne', duration: 100, }, function (obj) { obj.el.classList.add('ed-ds-render-finished');}, ); } } updateNodeValue(val) { const nodeIndex = this.findNodeIndex(this.state.selectedNodeId); const nodes = this.props.content.nodes if (nodes[nodeIndex].content != val) { this.props.updateContentState({ nodes: [ ...nodes.slice(0, nodeIndex), {...nodes[nodeIndex], content: val}, ...nodes.slice(nodeIndex + 1), ], svg_string: null, }); } } render() { let addNodeBtn = null; let drawEffectBtn = null; const readOnly = (this.props.mode != 'edit'); let compAlign = 'center'; if (this.props.pageProperties && this.props.pageProperties.pageAlign) { compAlign = this.props.pageProperties.pageAlign; } if (!readOnly) { addNodeBtn = <Button className='btn-append-node' style={{marginLeft:5 }} sm outlined ref="addNodeButtonRight" bsStyle='darkgreen45' onClick={this.addNodeCallback}> <SomethingWithIcon icon={Icons.thinPlus1}/> Append Node </Button>; let drawBtnClass = ''; if(this.props.content.draw_effect == true){ drawBtnClass = '#2EB398'; } else { drawBtnClass = 'darkgray'; } let tooltip = <Tooltip id={"enable draw effect"} placement="bottom">Click here to enable/disable draw effect</Tooltip>; drawEffectBtn = <OverlayTrigger placement="bottom" overlay={tooltip}> <Button className='switch-button' style={{color:drawBtnClass}} onClick={this.changeDrawEffect}> <SomethingWithIcon icon={Icons.thickPencilIcon}/> </Button> </OverlayTrigger>; } let nodeEditComponents = <div> {addNodeBtn} {drawEffectBtn} <span className='fg-darkgray40' style={{marginLeft:5}}>Click on linked list nodes to see options</span> </div>; let selectedNodeId = -1; if (!readOnly && this.state.selectedNodeId != -1 && this.state.id == selectedLinkedList) { selectedNodeId = this.state.selectedNodeId; const selectedNodeIndex = this.findNodeIndex(selectedNodeId); nodeEditComponents = <div style={{padding:1}}> {addNodeBtn} {drawEffectBtn} <FormControl type='text' style={{marginLeft:8 , marginRight:8, width:'200px', display:'inline'}} ref={node => this.nodeValueInputRef = node} onBlur={this.onValueChange} onKeyDown={this.handleKeyDown}/> <ColorPicker value={this.props.content.nodes[selectedNodeIndex].fillcolor} onChange={this.onColorChanged}/> <Button className='fg-darkgray75 delete-button' ref="removeNodeButton" onClick={this.removeNodeCallback}> <SomethingWithIcon icon={Icons.trashIcon}/> </Button> <div style={{display:'inline-block',float:'right',marginRight:8,marginTop:5}}> <a className='fg-darkgray75' style={{cursor:'pointer'}} onClick={this.clearSelection}>Close</a> </div> </div>; } let componentToolbar = null; if (!readOnly) { componentToolbar = <div className='edcomp-toolbar'> {nodeEditComponents} </div>; } let captionComponent = null; if (this.props.config == null || this.props.config.disableCaption == null || this.props.config.disableCaption != true) { captionComponent = <CaptionComponent caption={this.props.content.caption} readOnly={readOnly} onCaptionChange={this.handleCaptionChange}/>; } let displayList = null; if (readOnly && this.props.content.hasOwnProperty('svg_string')) { let tempHtml = {__html: this.props.content.svg_string}; let width = widgetUtil.parseSvgWidth(this.props.content.svg_string); let className = this.props.content.draw_effect ? 'ed-ds-render' : 'ed-ds-view'; displayList = <div ref='dsRender' className={className} dangerouslySetInnerHTML={tempHtml} style={{display:'block', maxWidth:width, margin: widgetUtil.getMargin(compAlign)}}/> this.state.selectedNodeId = -1; } else { displayList = <LinkedListD3 nodes={this.props.content.nodes} mode={this.props.mode} svg_string={this.props.content.svg_string} version={ this.props.content.version ? this.props.content.version : null} onClickNodeCallback={this.onClickNodeCallback} onSvgUpdate={this.onSvgUpdate} selectedNodeId={selectedNodeId}/> } return ( <div> {componentToolbar} <div style={{textAlign:compAlign}}> <div style={{display:'block'}}> {displayList} </div> </div> {captionComponent} </div> ); } } LinkedList.getComponentDefault = function() { const defaultContent = { version: '3.0', caption: '', svg_string: LinkedList.getDefaultSvg(), draw_effect: false, nodes: LinkedList.getDefaultNodes(), }; return defaultContent; }; LinkedList.getDefaultNodes = function() { // Update getDefaultSvg if below nodes are modified. return [{ id: 'node_1', content: "1", x: "50", y: "20", fillcolor: "#bfefff", textcolor: "white", strokecolor: "#FF0000", }, { id: 'node_2', content: "2", x: "50", y: "20", fillcolor: "#bfefff", textcolor: "white", strokecolor: "#FF0000", }, { id: 'node_3', content: "3", x: "50", y: "20", fillcolor: "#bfefff", textcolor: "white", strokecolor: "#FF0000", }]; }; LinkedList.getDefaultSvg = function() { return "<svg width=\"170pt\" height=\"38pt\" viewBox=\"0.00 0.00 170.00 38.00\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" xmlns:xlink=\"http:\/\/www.w3.org\/1999\/xlink\"> <g id=\"graph0\" class=\"graph\" transform=\"scale(1 1) rotate(0) translate(4 34)\"> <title>%3<\/title> <!-- node_1 --> <g id=\"node_1\" class=\"node\"><title>node_1<\/title> <path fill=\"#bfefff\" stroke=\"black\" stroke-width=\"0.5\" d=\"M10.1667,-0.5C10.1667,-0.5 19.8333,-0.5 19.8333,-0.5 24.6667,-0.5 29.5,-5.33333 29.5,-10.1667 29.5,-10.1667 29.5,-19.8333 29.5,-19.8333 29.5,-24.6667 24.6667,-29.5 19.8333,-29.5 19.8333,-29.5 10.1667,-29.5 10.1667,-29.5 5.33333,-29.5 0.5,-24.6667 0.5,-19.8333 0.5,-19.8333 0.5,-10.1667 0.5,-10.1667 0.5,-5.33333 5.33333,-0.5 10.1667,-0.5\"><\/path> <text text-anchor=\"middle\" x=\"15\" y=\"-10.6\" font-family=\"Courier,monospace\" font-size=\"16.00\">1<\/text> <\/g> <!-- node_2 --> <g id=\"node_2\" class=\"node\"><title>node_2<\/title> <path fill=\"#bfefff\" stroke=\"black\" stroke-width=\"0.5\" d=\"M76.1667,-0.5C76.1667,-0.5 85.8333,-0.5 85.8333,-0.5 90.6667,-0.5 95.5,-5.33333 95.5,-10.1667 95.5,-10.1667 95.5,-19.8333 95.5,-19.8333 95.5,-24.6667 90.6667,-29.5 85.8333,-29.5 85.8333,-29.5 76.1667,-29.5 76.1667,-29.5 71.3333,-29.5 66.5,-24.6667 66.5,-19.8333 66.5,-19.8333 66.5,-10.1667 66.5,-10.1667 66.5,-5.33333 71.3333,-0.5 76.1667,-0.5\"><\/path> <text text-anchor=\"middle\" x=\"81\" y=\"-10.6\" font-family=\"Courier,monospace\" font-size=\"16.00\">2<\/text> <\/g> <!-- node_1&#45;&gt;node_2 --> <g id=\"edge1\" class=\"edge\"><title>node_1-&gt;node_2<\/title> <path fill=\"none\" stroke=\"black\" stroke-width=\"0.6\" d=\"M29.5728,-15C37.8882,-15 48.722,-15 58.2156,-15\"><\/path> <polygon fill=\"#404040\" stroke=\"black\" stroke-width=\"0.6\" points=\"58.4468,-17.8001 66.4468,-15 58.4468,-12.2001 58.4468,-17.8001\"><\/polygon> <\/g> <!-- node_3 --> <g id=\"node_3\" class=\"node\"><title>node_3<\/title> <path fill=\"#bfefff\" stroke=\"black\" stroke-width=\"0.5\" d=\"M142.167,-0.5C142.167,-0.5 151.833,-0.5 151.833,-0.5 156.667,-0.5 161.5,-5.33333 161.5,-10.1667 161.5,-10.1667 161.5,-19.8333 161.5,-19.8333 161.5,-24.6667 156.667,-29.5 151.833,-29.5 151.833,-29.5 142.167,-29.5 142.167,-29.5 137.333,-29.5 132.5,-24.6667 132.5,-19.8333 132.5,-19.8333 132.5,-10.1667 132.5,-10.1667 132.5,-5.33333 137.333,-0.5 142.167,-0.5\"><\/path> <text text-anchor=\"middle\" x=\"147\" y=\"-10.6\" font-family=\"Courier,monospace\" font-size=\"16.00\">3<\/text> <\/g> <!-- node_2&#45;&gt;node_3 --> <g id=\"edge2\" class=\"edge\"><title>node_2-&gt;node_3<\/title> <path fill=\"none\" stroke=\"black\" stroke-width=\"0.6\" d=\"M95.5728,-15C103.888,-15 114.722,-15 124.216,-15\"><\/path> <polygon fill=\"#404040\" stroke=\"black\" stroke-width=\"0.6\" points=\"124.447,-17.8001 132.447,-15 124.447,-12.2001 124.447,-17.8001\"><\/polygon> <\/g> <\/g> <\/svg>"; }; module.exports = LinkedList;
import TileData from './TileData.js'; import TileXYIsEqual from '../utils/TileXYIsEqual.js'; import GetRandom from '../../utils/array/GetRandom.js'; var GetNextTile = function (curTileData, preTileData) { var board = this.board; var directions = board.grid.allDirections; var forwardTileData = null, backwardTileData = null; var neighborTileXArray = []; // forward and other neighbors, exclude backward var neighborTileXY, neighborTileData = null; for (var i = 0, cnt = directions.length; i < cnt; i++) { neighborTileXY = board.getNeighborTileXY(curTileData, directions[i]); if (neighborTileXY === null) { continue; } if (!board.contains(neighborTileXY.x, neighborTileXY.y, this.pathTileZ)) { continue; } neighborTileData = new TileData(neighborTileXY.x, neighborTileXY.y, directions[i]); if (directions[i] === curTileData.direction) { forwardTileData = neighborTileData; } if ((preTileData !== undefined) && (TileXYIsEqual(neighborTileXY, preTileData))) { backwardTileData = neighborTileData; } else { neighborTileXArray.push(neighborTileData); } } var nextTileData; if ((backwardTileData === null) && (neighborTileXArray.length === 0)) { // no valid neighbor nextTileData = null; } else if ((backwardTileData === null) && (neighborTileXArray.length === 1)) { // 1 neighbor nextTileData = neighborTileXArray[0]; } else if ((backwardTileData !== null) && (neighborTileXArray.length === 0)) { // 1 backward neighbor nextTileData = backwardTileData; } else { // 2 or more neighobrs switch (this.pickMode) { case 1: // random all if (backwardTileData !== null) { neighborTileXArray.push(backwardTileData); } nextTileData = GetRandom(neighborTileXArray); break; default: // case 0: forward first if (forwardTileData !== null) { nextTileData = forwardTileData; } else { nextTileData = GetRandom(neighborTileXArray); } break; } } return nextTileData; } export default GetNextTile;
import React from 'react' import { IconButton, Grid, Typography } from '@material-ui/core'; import PropTypes from 'prop-types' const Brands = () => { return ( <Grid> <Typography> Brands go here! </Typography> </Grid> ) } Brands.propTypes = { } export default Brands
define([ "backbone", "underscore", "util", "collection/flowCollection", ], function(Backbone,_,Util,FlowCollection){ /* Floodlight specific URL for flows on a switch */ FlowCollection.prototype.url = function() {return "/wm/core/switch/" + this.dpid + "/flow/json";}; FlowCollection.prototype.initialize = function(dpid) { this.dpid = dpid; }; FlowCollection.prototype.parse = function(response){ var innerArray = response[this.dpid]; return innerArray; }; return FlowCollection; });
var table; function preload() { table = loadTable('table.csv', 'header'); } function setup() { console.log(table); for (var i = 0; i < table.rows.length; i++) { for (var j = 0; j < table.columns.length; j++ ) { console.log(table.columns[j] +': '+ table.rows[i].getString(j) ); } console.log('---'); } }
import React, { Component } from 'react'; import { AppRegistry, } from 'react-native'; import Navigation from "./components/Navigation"; AppRegistry.registerComponent('Grasp', () => Navigation);
export default [ { icon: "", title: "Commercial Production", info: "We specialize in large quantities of commercial production of products for some of the leading companies of the world.", }, { icon: "../images/bluesewingmachine", title: "Custom Projects", info: "heloo i am some text heloo i am some text heloo i am some text heloo i am some text heloo i am some text heloo i am some text heloo i am some text ", }, { icon: "../images/bluecomputer", title: "3D CAD Design", info: "heloo i am some text heloo i am some text heloo i am some text heloo i am some text heloo i am some text heloo i am some text heloo i am some text ", }, ]
import './price.scss'; import { CURRENCY_SYMBOL } from '../../constants'; const Price = ({ price }) => { /** * Format Price * @param {*} price * @returns */ const formatPrice = (price) => { return price.toFixed(2).replace('.',','); } return ( <div className="price"> {CURRENCY_SYMBOL}{formatPrice(price)} </div> ); }; export default Price;